KMMainViewController+Action.swift 258 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. let document = self.listView.document
  11. if let data = document?.isFinding, data {
  12. document?.cancelFindString()
  13. }
  14. if searchString == "" {
  15. self.searchResults = []
  16. self.leftSideViewController.searchResults = self.searchResults
  17. self.listView.setHighlightedSelections([])
  18. self.listView.setHighlightedSelection(nil, animated: false)
  19. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  20. } else {
  21. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  22. var findArray : [[CPDFSelection]]
  23. if isCase {
  24. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  25. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  26. } else {
  27. findArray = self.listView.document.findString(searchString) ?? []
  28. }
  29. } else {
  30. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  31. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  32. } else {
  33. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  34. }
  35. }
  36. self.searchResults.removeAll()
  37. var _selections: [CPDFSelection] = []
  38. for selections in findArray {
  39. for selection in selections {
  40. let mode : KMSearchMode = KMSearchMode()
  41. mode.selection = selection
  42. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  43. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  44. self.searchResults.insert(mode, at: self.searchResults.count)
  45. _selections.append(selection)
  46. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  47. // self.listView.setHighlight(selection, forBorderColor: .yellow, fill: .red, animated: false)
  48. }
  49. // self.listView.setHighlightedSelections(selections )
  50. }
  51. if needShowAll {
  52. self.listView.setHighlightedSelections(_selections)
  53. }
  54. if _selections.isEmpty {
  55. self.listView.setHighlightedSelection(nil, animated: false)
  56. }
  57. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  58. self.leftSideViewController.searchResults = self.searchResults
  59. }
  60. if display {
  61. if self.leftSideViewController.findPaneState == .singular {
  62. self.leftSideViewController.displayFindViewAnimating(true)
  63. } else {
  64. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  65. }
  66. }
  67. }
  68. func removeSignatures(signatures:[CPDFSignature]) {
  69. for signature in signatures {
  70. self.listView.document.removeSignature(signature)
  71. }
  72. for i in 0..<self.listView.document.pageCount {
  73. let page : CPDFPage = self.listView.document.page(at: i)
  74. let annotations : [CPDFAnnotation] = page.annotations
  75. for j in 0..<annotations.count {
  76. let annotation = annotations[j]
  77. if annotation is CPDFSignatureWidgetAnnotation {
  78. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  79. }
  80. }
  81. }
  82. self.listView.setNeedsDisplayForVisiblePages()
  83. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  84. var mSignatures : [CPDFSignature] = []
  85. for sign in tSignatures {
  86. if sign.signers.count > 0 {
  87. mSignatures.append(sign)
  88. }
  89. }
  90. // self.leftSideViewController.signatureViewController.signatures = signatures
  91. // self.leftSideViewController.signatureViewController.reloadData()
  92. }
  93. //MARK: menu菜单
  94. func fontColorMenuItem()->NSMenuItem {
  95. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  96. return fontColorItem;
  97. }
  98. func fontSizeMenuItem()->NSMenuItem {
  99. let currentFontSize = self.listView.editingTextFontSize()
  100. let fontSizes = self.fontSizes()
  101. let submenu = NSMenu(title: "")
  102. for i in 0 ... fontSizes.count - 1 {
  103. let fontSize : String = fontSizes.object(at: i) as! String
  104. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  105. item.target = self
  106. item.tag = i
  107. submenu.addItem(item)
  108. if (Int(currentFontSize) == Int(fontSize)) {
  109. item.state = .on
  110. }
  111. }
  112. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  113. fontSizeItem.submenu = submenu
  114. return fontSizeItem;
  115. }
  116. func corpImageMenuItem()->NSMenuItem {
  117. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  118. return corpImageItem
  119. }
  120. func cancelCorpImageMenuItem()->NSMenuItem {
  121. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  122. return cancelCorpImageItem
  123. }
  124. func restoreCorpImageMenuItem()->NSMenuItem {
  125. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  126. return cancelCorpImageItem
  127. }
  128. func cutImageArea()->NSMenuItem {
  129. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  130. return deleteItem
  131. }
  132. func editAddBlanMenu(menu:NSMenu){
  133. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  134. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  135. }
  136. func addText() -> NSMenuItem {
  137. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  138. return addTextItem
  139. }
  140. func addImage() -> NSMenuItem {
  141. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  142. return addImageItem
  143. }
  144. func replaceImageArea()->NSMenuItem {
  145. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  146. return replaceItem
  147. }
  148. func exportImageArea()->NSMenuItem {
  149. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  150. return exportItem
  151. }
  152. func exportImageStampItem()->NSMenuItem {
  153. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  154. let menu = NSMenu()
  155. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  156. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  157. exportItem.submenu = menu
  158. return exportItem
  159. }
  160. func exportMenu() -> NSMenu {
  161. let menu = NSMenu()
  162. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  163. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  164. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  165. return menu
  166. }
  167. func cropMenu() -> NSMenu {
  168. let menu = NSMenu()
  169. _ = menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  170. _ = menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  171. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  172. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(smartAutoCropAll), target: self, at: 2)
  173. return menu
  174. }
  175. func zoomSelectionMenuItem() -> NSMenuItem {
  176. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  177. return item
  178. }
  179. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  180. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  181. return item
  182. }
  183. func enterAnnotationStype() -> NSMenuItem {
  184. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  185. let stypeMenu = NSMenu()
  186. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  187. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  188. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  189. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  190. stypeMenu.addItem(NSMenuItem.separator())
  191. }
  192. // stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  193. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  194. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  195. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  196. stypeMenu.addItem(NSMenuItem.separator())
  197. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  198. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  199. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  200. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  201. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  202. if self.isReadMode {
  203. } else {
  204. stypeMenu.addItem(NSMenuItem.separator())
  205. // _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  206. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  207. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  208. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  209. }
  210. stypItem.submenu = stypeMenu
  211. if self.listView.annotationType == .ink {
  212. stypeMenu.item(withTitle: NSLocalizedString("Freehand", comment: ""))?.state = .on
  213. } else if self.listView.annotationType == .freeText {
  214. stypeMenu.item(withTitle: NSLocalizedString("Text Note", comment: ""))?.state = .on
  215. } else if self.listView.annotationType == .anchored {
  216. stypeMenu.item(withTitle: NSLocalizedString("Anchored Note", comment: ""))?.state = .on
  217. } else if self.listView.annotationType == .square {
  218. stypeMenu.item(withTitle: NSLocalizedString("Rectangle", comment: ""))?.state = .on
  219. } else if self.listView.annotationType == .circle {
  220. stypeMenu.item(withTitle: NSLocalizedString("Circle", comment: ""))?.state = .on
  221. } else if self.listView.annotationType == .arrow {
  222. stypeMenu.item(withTitle: NSLocalizedString("Arrow", comment: ""))?.state = .on
  223. } else if self.listView.annotationType == .line {
  224. stypeMenu.item(withTitle: NSLocalizedString("Line", comment: ""))?.state = .on
  225. } else if self.listView.annotationType == .link {
  226. stypeMenu.item(at: 7)?.state = .on
  227. } else if self.listView.annotationType == .stamp {
  228. stypeMenu.item(withTitle: NSLocalizedString("Stamp", comment: ""))?.state = .on
  229. } else if self.listView.annotationType == .signSignature {
  230. stypeMenu.item(withTitle: NSLocalizedString("Signature", comment: ""))?.state = .on
  231. }
  232. return stypItem
  233. }
  234. func setAnnotationToolStype() -> NSMenuItem {
  235. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  236. let stypeMenu = NSMenu()
  237. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.textToolMode.rawValue)
  238. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  239. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  240. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  241. // stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  242. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  243. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  244. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  245. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  246. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  247. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  248. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  249. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  250. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  251. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  252. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  253. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  254. stypItem.submenu = stypeMenu
  255. if self.toolbarController.toolbarType == .Annatiton {
  256. stypeMenu.item(at: 0)?.state = .on
  257. } else if self.toolbarController.toolbarType == .Move {
  258. stypeMenu.item(at: 1)?.state = .on
  259. } else if self.toolbarController.toolbarType == .Magnify {
  260. stypeMenu.item(at: 2)?.state = .on
  261. } else if self.toolbarController.toolbarType == .Select {
  262. stypeMenu.item(at: 3)?.state = .on
  263. } else if self.toolbarController.toolbarType == .SelectZoom {
  264. stypeMenu.item(at: 4)?.state = .on
  265. }
  266. return stypItem
  267. }
  268. func addReadModelStype() -> NSMenuItem {
  269. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)
  270. if self.isReadMode {
  271. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)
  272. }
  273. return stypItem
  274. }
  275. func addOutlineStype() -> NSMenuItem {
  276. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  277. return stypItem
  278. }
  279. func setTTSStype() -> NSMenuItem {
  280. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  281. return stypItem
  282. }
  283. func setShareStype() -> NSMenuItem {
  284. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  285. var string = ""
  286. if listView.activeAnnotation != nil {
  287. string = self.listView?.activeAnnotation?.contents ?? ""
  288. }
  289. if string.count < 1{
  290. string = self.listView?.currentSelection?.string() ?? ""
  291. }
  292. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  293. return stypItem
  294. }
  295. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  296. var number = 0
  297. var indexN = 0
  298. guard str.count > 0 else {return (0, 0)}
  299. for i in 0...str.count - 1 {
  300. let c: unichar = (str as NSString).character(at: i)
  301. if (c >= 0x4E00) {
  302. number += 2
  303. }else {
  304. number += 1
  305. }
  306. if number > 56{
  307. indexN = i
  308. number = 100
  309. break
  310. }
  311. }
  312. return (number, indexN)
  313. }
  314. func setLookUpStype() -> NSMenuItem {
  315. let str = listView?.currentSelection?.string() ?? ""//String(format: "Look Up %@", listView?.currentSelection?.string() ?? "")
  316. let dic = numberOfChars(str)
  317. var newStr = str
  318. if dic.num == 100{
  319. newStr = str.prefix(dic.indexN) + "..."
  320. }
  321. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  322. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  323. return stypItem
  324. }
  325. func setSearchBaiduStype() -> NSMenuItem {
  326. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  327. return stypItem
  328. }
  329. func setCutStype() -> NSMenuItem {
  330. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  331. return stypItem
  332. }
  333. func setDeleteStype() -> NSMenuItem {
  334. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  335. return stypItem
  336. }
  337. func setColorsStype() -> NSMenuItem {
  338. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  339. return stypItem
  340. }
  341. func setLinesStype() -> NSMenuItem {
  342. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  343. return stypItem
  344. }
  345. func setEditNoteStype() -> NSMenuItem {
  346. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  347. return stypItem
  348. }
  349. func setRotateStype() -> NSMenuItem {
  350. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  351. let stypeMenu = NSMenu()
  352. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  353. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  354. stypItem.submenu = stypeMenu
  355. if self.toolbarController.toolbarType == .Annatiton {
  356. stypeMenu.item(at: 0)?.state = .on
  357. } else if self.toolbarController.toolbarType == .Move {
  358. stypeMenu.item(at: 1)?.state = .on
  359. }
  360. return stypItem
  361. }
  362. func setNextPageStype() -> NSMenuItem {
  363. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  364. stypItem.isEnabled = false
  365. if listView.canGoToNextPage() {
  366. stypItem.isEnabled = true
  367. }
  368. return stypItem
  369. }
  370. func setPreviousPageStype() -> NSMenuItem {
  371. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  372. stypItem.isEnabled = false
  373. if listView.canGoToPreviousPage() {
  374. stypItem.isEnabled = true
  375. }
  376. return stypItem
  377. }
  378. func setTranslateStype() -> NSMenuItem {
  379. let str = listView?.currentSelection?.string() ?? ""//String(format: "Translate %@", listView?.currentSelection?.string() ?? "")
  380. let dic = numberOfChars(str)
  381. var newStr = str
  382. if dic.num == 100{
  383. newStr = str.prefix(dic.indexN) + "..."
  384. }
  385. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  386. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  387. return stypItem
  388. }
  389. func setAutoScrollStype() -> NSMenuItem {
  390. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  391. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  392. return stypItem
  393. }
  394. func setSnapshotStype() -> NSMenuItem {
  395. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  396. let stypeMenu = NSMenu()
  397. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  398. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  399. stypItem.submenu = stypeMenu
  400. // if self.toolbarController.toolbarType == .Annatiton {
  401. // stypeMenu.item(at: 0)?.state = .on
  402. // } else if self.toolbarController.toolbarType == .Move {
  403. // stypeMenu.item(at: 1)?.state = .on
  404. // }
  405. return stypItem
  406. }
  407. func setServicesStype() -> NSMenuItem {
  408. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  409. let stypeMenu = NSMenu()
  410. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  411. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  412. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  413. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  414. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  415. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  416. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  417. stypItem.submenu = stypeMenu
  418. // if self.toolbarController.toolbarType == .Annatiton {
  419. // stypeMenu.item(at: 0)?.state = .on
  420. // } else if self.toolbarController.toolbarType == .Move {
  421. // stypeMenu.item(at: 1)?.state = .on
  422. // }
  423. return stypItem
  424. }
  425. func setCropStype() -> NSMenuItem {
  426. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  427. let stypeMenu = NSMenu()
  428. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  429. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  430. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  431. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  432. if NSIsEmptyRect(listView.selectionRect){
  433. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  434. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  435. }
  436. stypItem.submenu = stypeMenu
  437. // if self.toolbarController.toolbarType == .Annatiton {
  438. // stypeMenu.item(at: 0)?.state = .on
  439. // } else if self.toolbarController.toolbarType == .Move {
  440. // stypeMenu.item(at: 1)?.state = .on
  441. // } else if self.toolbarController.toolbarType == .Magnify {
  442. // stypeMenu.item(at: 2)?.state = .on
  443. // } else if self.toolbarController.toolbarType == .Select {
  444. // stypeMenu.item(at: 3)?.state = .on
  445. // } else if self.toolbarController.toolbarType == .SelectZoom {
  446. // stypeMenu.item(at: 4)?.state = .on
  447. // }
  448. return stypItem
  449. }
  450. func setAITranslateStype() -> NSMenuItem {
  451. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  452. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  453. return stypItem
  454. }
  455. func setAIProofreadStype() -> NSMenuItem {
  456. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  457. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  458. return stypItem
  459. }
  460. func setAIRewriteStype() -> NSMenuItem {
  461. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  462. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  463. return stypItem
  464. }
  465. func addHighlightLinksStype() -> NSMenuItem {
  466. let highlightLink = KMPreferenceManager.shared.highlightLinks
  467. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  468. if highlightLink {
  469. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  470. }
  471. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  472. return highlightLinksItem
  473. }
  474. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  475. if item == nil {
  476. return
  477. }
  478. let menu = NSMenu()
  479. item?.submenu = menu
  480. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  481. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  482. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  483. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  484. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  485. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  486. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  487. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  488. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  489. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  490. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)
  491. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  492. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  493. if listView.currentSelection.selectionType() != .image {
  494. menu.insertItem(height, at: menu.items.count)
  495. menu.insertItem(underline, at: menu.items.count)
  496. menu.insertItem(strickout, at: menu.items.count)
  497. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  498. }
  499. if self.isReadMode {
  500. } else {
  501. if listView.currentSelection.selectionType() != .image &&
  502. listView.currentSelection.selectionType() != .text {
  503. menu.insertItem(text, at: menu.items.count)
  504. menu.insertItem(note, at: menu.items.count)
  505. }
  506. }
  507. if self.isReadMode {
  508. } else {
  509. if listView.currentSelection.selectionType() != .image {
  510. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  511. menu.insertItem(rectangle, at: menu.items.count)
  512. menu.insertItem(oval, at: menu.items.count)
  513. }
  514. }
  515. if self.isReadMode {
  516. } else {
  517. if listView.currentSelection.selectionType() != .image &&
  518. listView.currentSelection.selectionType() != .text {
  519. menu.insertItem(line, at: menu.items.count)
  520. }
  521. }
  522. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  523. if self.isReadMode {
  524. } else {
  525. menu.insertItem(link, at: menu.items.count)
  526. }
  527. if self.isReadMode {
  528. } else {
  529. if listView.currentSelection.selectionType() != .image {
  530. menu.insertItem(outline, at: menu.items.count)
  531. }
  532. }
  533. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  534. if self.isReadMode {
  535. } else {
  536. if (listView.currentSelection.selectionType() != .image) {
  537. menu.insertItem(aiTranslation, at: menu.items.count)
  538. }
  539. }
  540. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  541. }
  542. func addBookmarkMenu() -> NSMenuItem {
  543. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  544. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  545. return bookMarkItem
  546. } else {
  547. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  548. return bookMarkItem
  549. }
  550. }
  551. func findStringMenu() -> NSMenuItem {
  552. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  553. menuItem.keyEquivalent = "f"
  554. return menuItem
  555. }
  556. func printingMenu() -> NSMenuItem {
  557. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  558. return menuItem
  559. }
  560. func fontSizes()->NSArray {
  561. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  562. }
  563. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  564. if interactionMode == .presentation {
  565. listView.goToPreviousPage(nil)
  566. return true
  567. }
  568. return false
  569. }
  570. func canEnterFullscreen() -> Bool {
  571. if (mwcFlags.isSwitchingFullScreen != 0) {
  572. return false
  573. }
  574. if useNativeFullScreen() {
  575. return interactionMode == .normal || interactionMode == .presentation
  576. } else {
  577. return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
  578. }
  579. }
  580. override func canEnterPresentation() -> Bool {
  581. let can = super.canEnterPresentation()
  582. if can == false {
  583. return false
  584. }
  585. guard let doc = self.listView?.document, doc.isLocked == false else {
  586. return false
  587. }
  588. return can
  589. }
  590. func useNativeFullScreen() -> Bool {
  591. var isFull = false
  592. // NSWindow.instancesRespond(toSelector: #selector(toggleFullScreen:))
  593. let sel = NSSelectorFromString("toggleFullscreen:")
  594. if NSWindow.instancesRespond(to: sel) && UserDefaults.standard.bool(forKey: "SKUseLegacyFullScreenKey"){
  595. isFull = true
  596. }
  597. return isFull
  598. }
  599. func enterPresentation() {
  600. self.view.window?.enterPresentation(provider: self)
  601. }
  602. func removeBlankingWindows() {
  603. // blankingWindows.makeObjectsPerform(#selector(fadeOut))
  604. // blankingWindows = nil
  605. }
  606. func hideLeftSideWindow() {
  607. // if leftSideViewController.view.window == leftSideWindow {
  608. // self.leftView.remove()
  609. // if leftSideWindow.firstResponder()?.isDescendant(of: leftSideController.view()) {
  610. // leftSideWindow.makeFirstResponder(nil)
  611. // }
  612. // leftSideController.view().setFrame(SKShrinkRect(NSInsetRect(leftSideContentView.bounds, -1.0, -1.0), 1.0, .maxYEdge))
  613. // leftSideContentView.addSubview(leftSideController.view())
  614. //
  615. // if self.interactionMode() == SKPresentationMode {
  616. // self.setLeftSidePaneState(mwcFlags.savedLeftSidePaneState)
  617. // }
  618. //
  619. // leftSideWindow = nil
  620. // }
  621. }
  622. func hideRightSideWindow() {
  623. // if rightSideController.view().window() == rightSideWindow {
  624. // rightSideWindow.remove()
  625. // if rightSideWindow.firstResponder()?.isDescendant(of: rightSideController.view()) {
  626. // rightSideWindow.makeFirstResponder(nil)
  627. // }
  628. // rightSideController.view().setFrame(SKShrinkRect(NSInsetRect(rightSideContentView.bounds, -1.0, -1.0), 1.0, .maxYEdge))
  629. // rightSideContentView.addSubview(rightSideController.view())
  630. //
  631. // rightSideWindow = nil
  632. // }
  633. }
  634. func forceSubwindowsOnTop(_ flag: Bool) {
  635. // let winC: NSWindowController = self.kmCurrentWindowC!
  636. // for wc in winC.document!.windowControllers {
  637. // let sel = NSSelectorFromString("setForceOnTop:")
  638. // if wc.responds(to: sel){
  639. // wc.
  640. // }
  641. // }
  642. }
  643. func enterPresentationMode() {
  644. let scrollView = listView.documentView().enclosingScrollView
  645. savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: KMMainModel.Key.kHasHorizontalScroller)
  646. savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: KMMainModel.Key.kHasVerticalsCroller)
  647. savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: KMMainModel.Key.kAutoHidesScrollers)
  648. // Set up presentation mode
  649. // if RUNNING(version: 10_12) {
  650. // pdfView.setBackgroundColor(NSColor.black)
  651. // } else {
  652. listView.backgroundColor = NSColor.clear
  653. // }
  654. listView.autoScales = true
  655. // listView.setDisplayMode(kPDFDisplaySinglePage)
  656. listView.setDisplay(.singlePage)
  657. // listView.setDisplayBox(kPDFDisplayBoxCropBox)
  658. listView.displayBox = .cropBox
  659. // listView.setDisplaysPageBreaks(false)
  660. listView.displaysPageBreaks = false
  661. // scrollView.setAutohidesScrollers(true)
  662. scrollView?.autohidesScrollers = true
  663. // scrollView.setHasHorizontalScroller(false)
  664. scrollView?.hasHorizontalScroller = false
  665. // scrollView.setHasVerticalScroller(false)
  666. scrollView?.hasVerticalScroller = false
  667. listView.setCurrentSelection(nil, animate: true)
  668. // if listView.hasReadingBar() {
  669. // listView.toggleReadingBar()
  670. // }
  671. // myDocument!.currentPage(presentationNotesDocument.pdfDocument().page(at: listView.currentPage().pageIndex()))
  672. // Prevent sleep
  673. // if activityAssertionID == kIOPMNullAssertionID && kIOReturnSuccess != IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, "Skim" as CFString, &activityAssertionID) {
  674. // activityAssertionID = kIOPMNullAssertionID
  675. // }
  676. }
  677. func exitFullscreenMode() {
  678. if self.interactionMode == .presentation {
  679. self.exitPresentationMode()
  680. }
  681. self.applyPDFSettings(self.savedNormalSetup)
  682. self.savedNormalSetup.removeAllObjects()
  683. self.listView.layoutDocumentView()
  684. self.listView.requiresDisplay()
  685. // if ([[[self pdfView] currentPage] isEqual:page] == NO)
  686. // [[self pdfView] goToPage:page];
  687. if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
  688. self.listView.backgroundColor = backgroundColor
  689. self.secondaryPdfView?.backgroundColor = backgroundColor
  690. }
  691. }
  692. func applyPDFSettings(_ setup: NSDictionary) {
  693. if let data = setup.object(forKey: KMMainModel.Key.kAutoScales) as? NSNumber {
  694. self.listView.autoScales = data.boolValue
  695. }
  696. if self.listView.autoScales == false {
  697. if let data = setup.object(forKey: KMMainModel.Key.kScaleFactor) as? NSNumber {
  698. self.listView.scaleFactor = data.floatValue.cgFloat
  699. }
  700. }
  701. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysPageBreaks) as? NSNumber {
  702. self.listView.displaysPageBreaks = data.boolValue
  703. }
  704. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysAsBook) as? NSNumber {
  705. self.listView.displaysAsBook = data.boolValue
  706. }
  707. if let data = setup.object(forKey: KMMainModel.Key.kDisplayMode) as? NSNumber {
  708. self.listView.displayMode = CPDFDisplayMode(rawValue: data.intValue) ?? .normal
  709. }
  710. if let data = setup.object(forKey: KMMainModel.Key.kDisplayBox) as? NSNumber {
  711. self.listView.displayBox = CPDFDisplayBox(rawValue: data.intValue) ?? .cropBox
  712. }
  713. }
  714. func exitPresentationMode() {
  715. // if (activityAssertionID != kIOPMNullAssertionID && kIOReturnSuccess == IOPMAssertionRelease(activityAssertionID))
  716. // activityAssertionID = kIOPMNullAssertionID;
  717. //
  718. // NSScrollView *scrollView = [[pdfView documentView] enclosingScrollView];
  719. // [scrollView setHasHorizontalScroller:[[savedNormalSetup objectForKey:HASHORIZONTALSCROLLER_KEY] boolValue]];
  720. // [scrollView setHasVerticalScroller:[[savedNormalSetup objectForKey:HASVERTICALSCROLLER_KEY] boolValue]];
  721. // [scrollView setAutohidesScrollers:[[savedNormalSetup objectForKey:AUTOHIDESSCROLLERS_KEY] boolValue]];
  722. }
  723. func currentPDFSettings() -> NSDictionary {
  724. var setup = NSMutableDictionary()
  725. setup[KMMainModel.Key.kDisplaysPageBreaks] = NSNumber(value: listView.displaysPageBreaks)
  726. setup[KMMainModel.Key.kDisplaysAsBook] = NSNumber(value: listView.displaysAsBook)
  727. setup[KMMainModel.Key.kDisplayBox] = NSNumber(value: listView.displayBox.rawValue)
  728. setup[KMMainModel.Key.kScaleFactor] = NSNumber(value: listView.scaleFactor)
  729. setup[KMMainModel.Key.kAutoScales] = NSNumber(value: listView.autoScales)
  730. setup[KMMainModel.Key.kDisplayMode] = NSNumber(value: listView.displayMode.rawValue)
  731. return setup
  732. }
  733. //MARK: menuItem Action
  734. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  735. let color = listView.editingSelectionFontColor()
  736. let panel = NSColorPanel.shared
  737. panel.setTarget(self)
  738. panel.setAction(#selector(fontColorChangeAction))
  739. panel.orderFront(nil)
  740. panel.showsAlpha = false
  741. panel.color = color ?? NSColor.black
  742. }
  743. @objc func fontColorChangeAction(sender: NSColorPanel) {
  744. self.listView.setEditingSelectionFontColor(sender.color)
  745. }
  746. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  747. let fontSize = self.fontSizes().object(at: sender.tag)
  748. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  749. }
  750. @objc func addImageText(sender: NSMenuItem) {
  751. let event = NSApp.currentEvent
  752. let clickLocation = event?.locationInWindow
  753. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  754. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  755. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  756. point = point2
  757. if sender.tag == 0 {
  758. KMPrint("添加文字")
  759. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  760. if !isSelect {
  761. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  762. }
  763. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  764. } else if sender.tag == 1 {
  765. KMPrint("添加图片")
  766. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  767. if !isSelect {
  768. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  769. }
  770. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  771. } else if sender.tag == 2 {
  772. KMPrint("粘贴")
  773. }
  774. }
  775. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  776. if self.rightSideViewController.eidtPDFImageProperty != nil {
  777. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  778. } else {
  779. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  780. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  781. }
  782. }
  783. }
  784. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  785. if self.rightSideViewController.eidtPDFImageProperty != nil {
  786. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  787. } else {
  788. self.listView.exitCrop(with: self.listView.selectImageAreas)
  789. self.listView.cropAreas = nil
  790. self.listView.isEditImage = false
  791. }
  792. }
  793. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  794. if self.rightSideViewController.eidtPDFImageProperty != nil {
  795. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  796. } else {
  797. self.listView.resetCrop(with: self.listView.selectImageAreas)
  798. }
  799. }
  800. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  801. if self.listView.selectImageAreas != nil {
  802. self.listView.isEditImage = true
  803. self.listView.enterCrop(with: self.listView.selectImageAreas)
  804. self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  805. }
  806. }
  807. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  808. if self.listView.selectImageAreas == nil {
  809. return
  810. }
  811. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  812. let panel = NSOpenPanel()
  813. panel.allowsMultipleSelection = false
  814. panel.allowedFileTypes = ["png","jpg"]
  815. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  816. if response == .OK {
  817. let openPath = panel.url?.path
  818. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  819. if s {
  820. }
  821. }
  822. }
  823. }
  824. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  825. if self.listView.selectImageAreas == nil {
  826. return
  827. }
  828. let panel = NSSavePanel()
  829. // panel.nameFieldStringValue = "[新文件].png"
  830. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  831. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  832. // button.state = .on
  833. // panel.accessoryView = button
  834. panel.isExtensionHidden = true
  835. let response = panel.runModal()
  836. if response == .OK {
  837. let url = panel.url
  838. if FileManager.default.fileExists(atPath: url!.path) {
  839. try?FileManager.default.removeItem(atPath: url!.path)
  840. }
  841. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  842. if result {
  843. NSWorkspace.shared.activateFileViewerSelecting([url!])
  844. // if button.state == .on { /// 开启文档
  845. // NSWorkspace.shared.openFile(url!.path)
  846. // } else {
  847. //
  848. // }
  849. }
  850. }
  851. }
  852. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  853. }
  854. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  855. }
  856. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  857. }
  858. @objc func OpenItemAction(sender: NSMenuItem) {
  859. }
  860. @objc func cropAllPageItem(sender: NSMenuItem) {
  861. self.cropAll(nil)
  862. }
  863. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  864. self.crop(nil)
  865. }
  866. @objc func autoCropAllItem(sender: NSMenuItem) {
  867. self.autoCropAll(nil)
  868. }
  869. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  870. self.smartAutoCropAll(nil)
  871. }
  872. @objc func customCropModel(sender: NSMenuItem) {
  873. let pdfDoc: CPDFDocument = self.listView.document
  874. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  875. let alert = NSAlert()
  876. alert.alertStyle = .critical
  877. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  878. alert.runModal()
  879. return
  880. }
  881. let window = NSWindow.currentWindow()
  882. let currentPage = pdfDoc.index(for: self.listView.currentPage())
  883. let cropVC = KMPDFCropWindowController(document: pdfDoc, pwd: "", currentPage: Int(currentPage), cropSize: CGRectMake(100, 100, 50, 80), selectPageString: "\(currentPage)")
  884. window.km_beginSheet(windowC: cropVC)
  885. cropVC.cropWindowCloseBlock = { [weak self] doc in
  886. window.km_quick_endSheet()
  887. let isSuccessful = doc.write(to: self?.listView.document.documentURL)
  888. if isSuccessful {
  889. if let documen = CPDFDocument(url: self?.document?.documentURL) {
  890. if documen.isLocked {
  891. documen.unlock(withPassword: pdfDoc.password)
  892. }
  893. self?.setDocument = documen
  894. }
  895. }
  896. }
  897. }
  898. @objc func rotateRightAction(sender: NSMenuItem) {
  899. }
  900. @objc func rotateLeftAction(sender: NSMenuItem) {
  901. }
  902. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  903. self.listView.toolMode = .noteToolMode
  904. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  905. var model : KMToolbarViewType = .None
  906. switch sender.tag {
  907. case 0:
  908. identifier = KMDocumentAnnotationToolbarItemIdentifier
  909. model = .Annatiton
  910. case 1:
  911. identifier = KMToolbarMoveToolModeItemIdentifier
  912. model = .Move
  913. case 2:
  914. identifier = KMToolbarMagnifyToolModeItemIdentifier
  915. model = .Magnify
  916. case 3:
  917. identifier = KMToolbarSelectToolModeItemIdentifier
  918. model = .Select
  919. case 4:
  920. identifier = KMToolbarZoomToSelectionItemIdentifier
  921. model = .SelectZoom
  922. default:
  923. break
  924. }
  925. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  926. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  927. }
  928. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  929. var itemId: String?
  930. if sender.tag == CAnnotationType.highlight.rawValue {
  931. itemId = KMToolbarHighlightAnnotationItemIdentifier
  932. } else if sender.tag == CAnnotationType.underline.rawValue {
  933. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  934. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  935. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  936. } else if sender.tag == CAnnotationType.ink.rawValue {
  937. itemId = KMToolbarInkAnnotationItemIdentifier
  938. } else if sender.tag == CAnnotationType.freeText.rawValue {
  939. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  940. } else if sender.tag == CAnnotationType.anchored.rawValue {
  941. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  942. } else if sender.tag == CAnnotationType.square.rawValue {
  943. itemId = KMToolbarSquareAnnotationItemIdentifier
  944. } else if sender.tag == CAnnotationType.circle.rawValue {
  945. itemId = KMToolbarCircleAnnotationItemIdentifier
  946. } else if sender.tag == CAnnotationType.arrow.rawValue {
  947. itemId = KMToolbarArrowAnnotationItemIdentifier
  948. } else if sender.tag == CAnnotationType.line.rawValue {
  949. itemId = KMToolbarLineAnnotationItemIdentifier
  950. } else if sender.tag == CAnnotationType.link.rawValue {
  951. itemId = KMToolbarLinkAnnotationItemIdentifier
  952. }
  953. if let data = itemId {
  954. self.toolbarController.clickItem(data)
  955. }
  956. }
  957. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  958. var annotationType : CAnnotationType = .unkown
  959. switch sender.tag {
  960. case 0:
  961. annotationType = .highlight
  962. case 1:
  963. annotationType = .underline
  964. case 2:
  965. annotationType = .strikeOut
  966. case 3:
  967. annotationType = .freeText
  968. case 4:
  969. annotationType = .anchored
  970. case 5:
  971. annotationType = .square
  972. case 6:
  973. annotationType = .circle
  974. case 7:
  975. annotationType = .line
  976. case 8:
  977. annotationType = .link
  978. case 9:
  979. // var newOutline : CPDFOutline = CPDFOutline()
  980. // newOutline.label = "11111111"
  981. // let des = self.listView.currentDestination
  982. // if "\(des?.point.x ?? 0)" != "nan" {
  983. // newOutline.destination = self.listView.currentDestination
  984. // } else {
  985. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  986. // newOutline.destination = destination
  987. // }
  988. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  989. // let parent = current.parent ?? CPDFOutline()
  990. // let index = current.index + 1
  991. // parent.insertChild(newOutline, at: index)
  992. if self.model.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  993. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  994. }
  995. // self.leftSideViewController.outlineViewController.addItemAction()
  996. return
  997. case 10:
  998. annotationType = .unkown
  999. default:
  1000. break
  1001. }
  1002. if (annotationType != .link) {
  1003. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  1004. self.listView.currentSelection = nil;
  1005. return
  1006. }
  1007. // link
  1008. let selection = self.listView.currentSelection
  1009. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  1010. DispatchQueue.main.async {
  1011. Task { @MainActor in
  1012. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  1013. self.listView.currentSelection = nil;
  1014. if (annotation != nil) {
  1015. self.listView.updateActiveAnnotations([annotation!])
  1016. }
  1017. }
  1018. }
  1019. }
  1020. @objc func aiTranslationAction(sender: NSMenuItem) {
  1021. let content = self.listView.currentSelection.string() ?? ""
  1022. let origin = self.listView.currentSelection.bounds.origin
  1023. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  1024. self.aiTranslationWindow?.content = content
  1025. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  1026. self.aiTranslationWindow!.window?.center()
  1027. }
  1028. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  1029. Task { @MainActor in
  1030. let idx = sender.tag
  1031. if idx == 10 {
  1032. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1033. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1034. return
  1035. }
  1036. }
  1037. var point = mouseRightMenuEvent?.locationInWindow
  1038. if (point == nil) {
  1039. point = NSZeroPoint
  1040. }
  1041. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  1042. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  1043. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  1044. var annotation: CPDFAnnotation?
  1045. if self.isReadMode {
  1046. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1047. self.listView.toolMode = .noteToolMode
  1048. }
  1049. switch sender.tag {
  1050. case 0:
  1051. self.listView.annotationType = CAnnotationType.ink
  1052. case 1:
  1053. // self.listView.annotationType = CAnnotationType.freeText
  1054. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1055. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1056. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1057. if ((annotation) != nil) {
  1058. self.listView.updateActiveAnnotations([annotation!])
  1059. self.listView.edit(annotation)
  1060. }
  1061. case 2:
  1062. // self.listView.annotationType = CAnnotationType.anchored
  1063. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1064. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1065. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1066. self.listView.edit(annotation)
  1067. case 3:
  1068. // self.listView.annotationType = CAnnotationType.square
  1069. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1070. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1071. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1072. case 4:
  1073. // self.listView.annotationType = CAnnotationType.circle
  1074. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1075. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1076. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1077. case 5:
  1078. // self.listView.annotationType = CAnnotationType.arrow
  1079. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1080. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1081. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1082. case 6:
  1083. // self.listView.annotationType = CAnnotationType.line
  1084. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1085. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1086. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1087. case 7:
  1088. self.listView.annotationType = CAnnotationType.link
  1089. self.openRightPane()
  1090. case 8:
  1091. self.listView.annotationType = CAnnotationType.stamp
  1092. self.openRightPane()
  1093. case 9:
  1094. self.listView.annotationType = CAnnotationType.signSignature
  1095. self.openRightPane()
  1096. default:
  1097. break
  1098. }
  1099. self.rightSideViewController.isHidden = true
  1100. self.rightSideViewController.subViewType = .AnnotationProperts
  1101. } else {
  1102. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1103. if(self.toolbarController.toolbarType == .None) {
  1104. self.toolbarController.toolbarType = .Annatiton
  1105. }
  1106. self.listView.toolMode = .noteToolMode
  1107. }
  1108. switch sender.tag {
  1109. case 0:
  1110. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  1111. self.model.rightMouseEventing = true
  1112. if(self.toolbarController.toolbarType == .None) {
  1113. self.toolbarController.toolbarType = .Annatiton
  1114. }
  1115. self.listView.toolMode = .noteToolMode
  1116. self.listView.annotationType = CAnnotationType.ink
  1117. case 1:
  1118. // self.listView.annotationType = CAnnotationType.freeText
  1119. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1120. if (pagePoint.x - defaultSize.width > 0){
  1121. pagePoint.x -= defaultSize.width;
  1122. }else{
  1123. pagePoint.x = 0;
  1124. }
  1125. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1126. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1127. // self.view.window?.makeFirstResponder()
  1128. if ((annotation) != nil) {
  1129. // self.listView.updateActiveAnnotations([annotation!])
  1130. self.listView.edit(annotation)
  1131. }
  1132. case 2:
  1133. // self.listView.annotationType = CAnnotationType.anchored
  1134. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1135. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1136. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1137. self.listView.edit(annotation)
  1138. case 3:
  1139. // self.listView.annotationType = CAnnotationType.square
  1140. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1141. if (pagePoint.x - defaultSize.width > 0){
  1142. pagePoint.x -= defaultSize.width;
  1143. }else{
  1144. pagePoint.x = 0;
  1145. }
  1146. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1147. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1148. case 4:
  1149. // self.listView.annotationType = CAnnotationType.circle
  1150. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1151. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1152. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1153. case 5:
  1154. // self.listView.annotationType = CAnnotationType.arrow
  1155. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1156. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1157. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1158. case 6:
  1159. // self.listView.annotationType = CAnnotationType.line
  1160. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1161. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1162. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1163. case 7:
  1164. self.listView.annotationType = CAnnotationType.link
  1165. self.openRightPane()
  1166. case 8:
  1167. self.listView.annotationType = CAnnotationType.stamp
  1168. self.openRightPane()
  1169. case 9:
  1170. self.listView.annotationType = CAnnotationType.signSignature
  1171. self.openRightPane()
  1172. case 10:
  1173. self.addImgAnnotationToView(center: pagePoint)
  1174. default:
  1175. break
  1176. }
  1177. self.rightSideViewController.isHidden = false
  1178. self.rightSideViewController.subViewType = .AnnotationProperts
  1179. if annotation != nil{
  1180. self.listView.activeAnnotations.removeAllObjects()
  1181. // self.listView.activeAnnotations.add(annotation as Any)
  1182. var newAnnonations : [CPDFAnnotation] = []
  1183. newAnnonations.append(annotation!)
  1184. self.listView.updateActiveAnnotations(newAnnonations)
  1185. // self.openRightPane()
  1186. }
  1187. // self.rightSideViewController.view.isHidden = false
  1188. }
  1189. // if (annotation != nil) {
  1190. // self.listView.updateIsRightActiveAnnotations([annotation!])
  1191. // }
  1192. }
  1193. }
  1194. func addImgAnnotationToView(center: NSPoint) {
  1195. let accessoryCtr = KMImageAccessoryController()
  1196. let openPanel = NSOpenPanel()
  1197. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1198. openPanel.allowsMultipleSelection = false
  1199. openPanel.accessoryView = accessoryCtr.view
  1200. openPanel.isAccessoryViewDisclosed = true
  1201. openPanel.beginSheetModal(for: self.view.window!) { result in
  1202. if result == .OK {
  1203. let fileURL = openPanel.urls.first
  1204. let filePath = fileURL!.path
  1205. if filePath.pathExtension == "pdf" {
  1206. let pdf = CPDFDocument(url: fileURL)
  1207. if pdf!.isEncrypted {
  1208. NSSound.beep()
  1209. return
  1210. }
  1211. }
  1212. let img = NSImage(contentsOfFile: filePath)
  1213. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  1214. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  1215. }
  1216. }
  1217. }
  1218. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  1219. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  1220. let index = self.listView.currentPageIndex
  1221. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  1222. self.listView.setNeedsDisplayForVisiblePages()
  1223. } else {
  1224. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1225. self.listView.setNeedsDisplayForVisiblePages()
  1226. }
  1227. if self.isReadMode {
  1228. } else {
  1229. if self.model.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  1230. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  1231. }
  1232. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1233. if bookMark != nil {
  1234. let item = KMBookMarkItem()
  1235. item.bookMark = bookMark!
  1236. item.label = (bookMark?.label)!
  1237. item.index = UInt(bookMark!.pageIndex)
  1238. // self.leftSideViewController.bookViewController.reloadData()
  1239. // self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  1240. } else {
  1241. // self.leftSideViewController.bookViewController.reloadData()
  1242. }
  1243. }
  1244. }
  1245. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  1246. self.leftSideViewController.refreshMethodType(methodType: .Search)
  1247. }
  1248. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  1249. let rect = listView.currentSelectionRect()
  1250. let page = listView.currentPage()
  1251. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  1252. copyPage.setBounds(rect, for: .cropBox)
  1253. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  1254. // let pdfDocument : PDFDocument = PDFDocument()
  1255. // let newpage : PDFPage = PDFPage(image: image)!
  1256. // pdfDocument.insert(newpage, at: 0)
  1257. // 执行右键操作后,需要取消框选区域
  1258. if self.listView.toolMode == .selectToolMode {
  1259. objc_sync_enter(self)
  1260. self.listView.selectionRect = NSZeroRect
  1261. self.listView.selectionPageIndex = UInt(NSNotFound)
  1262. objc_sync_exit(self)
  1263. }
  1264. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1265. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1266. if (result == .cancel) {
  1267. return
  1268. }
  1269. // 解除权限
  1270. self?.model.isSaveKeyChain = false
  1271. self?.listView.document.unlock(withPassword: password)
  1272. // 隐藏提示
  1273. self?.hiddenSecureLimitTip()
  1274. // 去打印
  1275. KMPrintWindowController.printImage(image: image)
  1276. }
  1277. return
  1278. }
  1279. KMPrintWindowController.printImage(image: image)
  1280. }
  1281. func splitView(withTag tag: Int) {
  1282. if tag == 0 {
  1283. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1284. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1285. } else if tag == 1 {
  1286. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1287. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1288. } else if tag == 2 {
  1289. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1290. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1291. }
  1292. self.listView.needsDisplay = true
  1293. }
  1294. // MARK: - 幻灯片
  1295. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1296. let view: NSView = self.view.window!.firstResponder as! NSView
  1297. if view.isDescendant(of: pdfSplitView){
  1298. self.view.window?.makeFirstResponder(nil)
  1299. }
  1300. self.mainWindow = self.view.window
  1301. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1302. fullScreenWindow.interactionParent = self.view.window
  1303. self.mainWindow?.delegate = nil
  1304. fullScreenWindow.fadeInBlocking()
  1305. self.browserWindowController?.window = fullScreenWindow
  1306. fullScreenWindow.makeKey()
  1307. // NSApp.updatePresentationOptions(for: fullScreenWindow)
  1308. let sel = NSSelectorFromString("setAnimationBehavior:")
  1309. if self.mainWindow?.responds(to: sel) ?? false{
  1310. self.mainWindow?.animationBehavior = .none
  1311. }
  1312. self.mainWindow?.orderOut(nil)
  1313. if self.mainWindow?.responds(to: sel) ?? false{
  1314. self.mainWindow?.animationBehavior = .default
  1315. }
  1316. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1317. fullScreenWindow.orderFront(nil)
  1318. // NSApp.addWindowsItem(fullScreenWindow, title: windowTitleForDocumentDisplayName(self.document?.displayName) ?? "", filename: false)
  1319. }
  1320. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1321. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1322. return
  1323. }
  1324. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1325. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1326. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1327. fullScreenWindow.contentView?.addSubview(view)
  1328. self.listView.layoutDocumentView()
  1329. self.listView.requiresDisplay()
  1330. fullScreenWindow.makeFirstResponder(self.listView)
  1331. fullScreenWindow.recalculateKeyViewLoop()
  1332. fullScreenWindow.delegate = self.browserWindowController
  1333. // if (RUNNING_BEFORE(10_7))
  1334. // [fullScreenWindow display];
  1335. fullScreenWindow.display()
  1336. fadeWindow.fadeOut()
  1337. }
  1338. // MARK: Redact 【密文标记】
  1339. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1340. self.listView.remove(self.listView.activeAnnotation)
  1341. }
  1342. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1343. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1344. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1345. self.view.window?.beginSheet(windowController.window!)
  1346. self.currentWindowController = windowController
  1347. windowController.itemClick = { [weak self] index, value in
  1348. if (index == 1) { /// 取消
  1349. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1350. self?.currentWindowController = nil
  1351. return
  1352. }
  1353. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1354. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1355. annotaton.setBorderColor(windowController_redact.outsideColor)
  1356. annotaton.setInteriorColor(windowController_redact.fillColor)
  1357. if (windowController_redact.isOver) {
  1358. annotaton.setFontColor(windowController_redact.fontColor)
  1359. annotaton.setAlignment(windowController_redact.aligement)
  1360. annotaton.setFont(windowController_redact.font)
  1361. annotaton.setOverlayText(windowController_redact.overText)
  1362. }
  1363. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1364. self?.currentWindowController = nil
  1365. }
  1366. }
  1367. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1368. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1369. return
  1370. }
  1371. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1372. let model = CPDFAnnotationModel(annotationType: .redact)
  1373. model?.setColor(annotation.borderColor())
  1374. model?.setInteriorColor(annotation.interiorColor())
  1375. let overlayText: String = annotation.overlayText()
  1376. if (overlayText.isEmpty) {
  1377. model?.setIsOverlayText(false)
  1378. } else {
  1379. model?.setIsOverlayText(true)
  1380. model?.setOverlayText(overlayText)
  1381. model?.setFontColor(annotation.fontColor())
  1382. model?.setAlignment(annotation.alignment())
  1383. model?.setFontName(annotation.font().fontName)
  1384. model?.setFontSize(annotation.font().pointSize)
  1385. }
  1386. }
  1387. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1388. let anno = self.listView.activeAnnotation
  1389. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1390. return
  1391. }
  1392. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1393. windowController.pageCount = Int(self.listView.document.pageCount)
  1394. self.currentWindowController = windowController
  1395. self.view.window?.beginSheet(windowController.window!)
  1396. windowController.itemClick = { [weak self] index, value in
  1397. if (index == 1) {
  1398. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1399. self!.currentWindowController = nil
  1400. return
  1401. }
  1402. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1403. let pageType = windowController_mutilPageFlag.pageType
  1404. let pageString = windowController_mutilPageFlag.pageString
  1405. if (pageType == 4) { /// 自定义页面
  1406. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  1407. if (array.count == 0) {
  1408. let alert = NSAlert()
  1409. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1410. alert.runModal()
  1411. return
  1412. }
  1413. }
  1414. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1415. self!.currentWindowController = nil
  1416. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  1417. if (indexs.count == 0) {
  1418. return
  1419. }
  1420. for i in indexs {
  1421. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1422. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1423. self?.listView.add(redactAnno, to: page)
  1424. }
  1425. }
  1426. }
  1427. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1428. self.exeRedactConfirm(.redactOne) {}
  1429. }
  1430. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1431. self.exeRedactConfirm(.eraserOne) {}
  1432. }
  1433. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1434. }
  1435. @objc func exportStampImage(sender:NSMenuItem) {
  1436. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1437. var image : NSImage = NSImage()
  1438. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1439. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1440. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1441. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1442. }
  1443. let data = image.tiffRepresentation
  1444. if sender.tag == 0 {
  1445. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1446. imageRep.size = image.size
  1447. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1448. let savePanel = NSSavePanel()
  1449. savePanel.allowedFileTypes = ["png"]
  1450. savePanel.beginSheetModal(for: self.view.window!) { response in
  1451. if (response != .OK) {
  1452. return
  1453. }
  1454. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1455. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1456. }
  1457. }
  1458. } else {
  1459. let pdfdocument = CPDFDocument()
  1460. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1461. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1462. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1463. let savePanel = NSSavePanel()
  1464. savePanel.allowedFileTypes = ["pdf"]
  1465. savePanel.beginSheetModal(for: self.view.window!) { response in
  1466. if (response != .OK) {
  1467. return
  1468. }
  1469. if pdfdocument!.write(to: savePanel.url!) {
  1470. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. }
  1477. @objc func exportCorpImage(sender:NSMenuItem) {
  1478. let rect = NSIntegralRect(listView.currentSelectionRect())
  1479. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1480. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1481. page.setBounds(rect, for: .cropBox)
  1482. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1483. let data = image.tiffRepresentation
  1484. guard let data = data else { return }
  1485. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1486. imageRep.size = rect.size
  1487. let savePanel = NSSavePanel()
  1488. switch sender.tag {
  1489. case 0:
  1490. savePanel.allowedFileTypes = ["png"]
  1491. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1492. savePanel.beginSheetModal(for: self.view.window!) { response in
  1493. if (response != .OK) {
  1494. return
  1495. }
  1496. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1497. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1498. }
  1499. }
  1500. case 1:
  1501. savePanel.allowedFileTypes = ["jpg"]
  1502. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1503. savePanel.beginSheetModal(for: self.view.window!) { response in
  1504. if (response != .OK) {
  1505. return
  1506. }
  1507. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1508. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1509. }
  1510. }
  1511. case 2:
  1512. savePanel.allowedFileTypes = ["pdf"]
  1513. let pdfdocument = CPDFDocument()
  1514. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1515. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1516. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1517. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1518. savePanel.beginSheetModal(for: self.view.window!) { response in
  1519. if (response != .OK) {
  1520. return
  1521. }
  1522. if pdfdocument!.write(to: savePanel.url!) {
  1523. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1524. }
  1525. }
  1526. }
  1527. default:
  1528. break
  1529. }
  1530. // 执行右键操作后,需要取消框选区域
  1531. if self.listView.toolMode == .selectToolMode {
  1532. objc_sync_enter(self)
  1533. self.listView.selectionRect = NSZeroRect
  1534. self.listView.selectionPageIndex = UInt(NSNotFound)
  1535. objc_sync_exit(self)
  1536. }
  1537. }
  1538. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1539. let rect = listView.currentSelectionRect()
  1540. let page = listView.currentPage()
  1541. if NSIsEmptyRect(rect) == false && page != nil {
  1542. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1543. var bounds = listView.bounds
  1544. var scale = 1.0
  1545. if isLegacy {
  1546. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1547. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1548. }
  1549. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1550. scale = NSHeight(bounds) / NSHeight(rect)
  1551. } else {
  1552. scale = NSWidth(bounds) / NSWidth(rect)
  1553. }
  1554. listView.setScaleFactor(scale, animated: false)
  1555. let scrollView = listView.scroll()
  1556. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1557. if ((scrollView?.hasVerticalScroller) != nil) {
  1558. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1559. }
  1560. if ((scrollView?.hasHorizontalScroller) != nil) {
  1561. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1562. }
  1563. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1564. scale = NSHeight(bounds) / NSHeight(rect)
  1565. } else {
  1566. scale = NSWidth(bounds) / NSWidth(rect)
  1567. }
  1568. listView.setScaleFactor(scale, animated: false)
  1569. }
  1570. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1571. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1572. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1573. };
  1574. }
  1575. // 执行右键操作后,需要取消框选区域
  1576. if self.listView.toolMode == .selectToolMode {
  1577. objc_sync_enter(self)
  1578. self.listView.selectionRect = NSZeroRect
  1579. self.listView.selectionPageIndex = UInt(NSNotFound)
  1580. objc_sync_exit(self)
  1581. }
  1582. }
  1583. private func cropPagesToRects(rects:NSPointerArray) {
  1584. }
  1585. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1586. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1587. switch sender.tag {
  1588. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1589. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1590. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1591. var red: CGFloat = 0.0
  1592. var green: CGFloat = 0.0
  1593. var blue: CGFloat = 0.0
  1594. var alpha: CGFloat = 0.0
  1595. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1596. if sender.tag == CAnnotationType.highlight.rawValue {
  1597. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1598. } else if sender.tag == CAnnotationType.underline.rawValue {
  1599. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1600. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1601. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1602. }
  1603. case CAnnotationType.ink.rawValue:
  1604. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1605. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1606. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1607. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1608. var red: CGFloat = 0.0
  1609. var green: CGFloat = 0.0
  1610. var blue: CGFloat = 0.0
  1611. var alpha: CGFloat = 0.0
  1612. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1613. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1614. case CAnnotationType.freeText.rawValue:
  1615. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1616. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1617. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1618. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1619. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1620. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1621. var red: CGFloat = 0.0
  1622. var green: CGFloat = 0.0
  1623. var blue: CGFloat = 0.0
  1624. var alpha: CGFloat = 0.0
  1625. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1626. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1627. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1628. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1629. UserDefaults.standard.synchronize()
  1630. }
  1631. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1632. if (alignment == .left || alignment == .center || alignment == .right) {
  1633. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1634. UserDefaults.standard.synchronize()
  1635. }
  1636. case CAnnotationType.anchored.rawValue:
  1637. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1638. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1639. var red: CGFloat = 0.0
  1640. var green: CGFloat = 0.0
  1641. var blue: CGFloat = 0.0
  1642. var alpha: CGFloat = 0.0
  1643. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1644. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1645. case CAnnotationType.square.rawValue:
  1646. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1647. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1648. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1649. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1650. var red: CGFloat = 0.0
  1651. var green: CGFloat = 0.0
  1652. var blue: CGFloat = 0.0
  1653. var alpha: CGFloat = 0.0
  1654. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1655. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1656. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1657. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1658. case CAnnotationType.circle.rawValue:
  1659. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1660. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1661. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1662. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1663. var red: CGFloat = 0.0
  1664. var green: CGFloat = 0.0
  1665. var blue: CGFloat = 0.0
  1666. var alpha: CGFloat = 0.0
  1667. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1668. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1669. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1670. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1671. default:
  1672. break
  1673. }
  1674. }
  1675. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1676. self.showOrHideNotes()
  1677. }
  1678. //MARK: - action
  1679. @objc func cropCurrentPage() {
  1680. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1681. var page: CPDFPage?
  1682. if let data = self.listView.currentSelectionPage() {
  1683. page = data
  1684. } else {
  1685. page = self.listView.currentPage()
  1686. }
  1687. if (NSIsEmptyRect(rect)) {
  1688. rect = KMCropTools.getPageForegroundBox(page!)
  1689. }
  1690. let index: UInt = (page?.pageIndex()) ?? 0
  1691. self._cropPage(at: index, in: rect)
  1692. // 执行右键操作后,需要取消框选区域
  1693. if self.listView.toolMode == .selectToolMode {
  1694. objc_sync_enter(self)
  1695. self.listView.selectionRect = NSZeroRect
  1696. self.listView.selectionPageIndex = UInt(NSNotFound)
  1697. objc_sync_exit(self)
  1698. }
  1699. self.handlePageBoundsDidChange(page: page, action: CPDFPage.Action.crop)
  1700. }
  1701. @objc private func _cropPage(at index: UInt, in rect: NSRect) {
  1702. let oldRect = self.listView?.document?.page(at: index)?.bounds(for: .cropBox) ?? .zero
  1703. let undoManager = self.listView.undoManager
  1704. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)?._cropPage(at: index, in: oldRect)
  1705. let page = self.listView.document.page(at: index)
  1706. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox)) ?? .zero)
  1707. page?.setBounds(newRect, for: .cropBox)
  1708. /// 刷新预览视图
  1709. self.listView.layoutDocumentView()
  1710. self.listView.displayBox = .cropBox
  1711. }
  1712. func beginProgressSheet(with message: String, maxValue: UInt) {
  1713. let progress = SKProgressController()
  1714. // progress.window?.backgroundColor = NSColor.km_init(hex: "#ffffff")
  1715. progress.window?.contentView?.wantsLayer = true
  1716. // progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#ffffff").cgColor
  1717. // progress.progressField.textColor = NSColor.black
  1718. progress.message = NSLocalizedString("Converting...", comment: "")
  1719. self.progressC = progress
  1720. self.progressC?.message = message
  1721. if maxValue > 0 {
  1722. progressC?.indeterminate = false
  1723. progressC?.maxValue = Double(maxValue)
  1724. } else {
  1725. progressC?.indeterminate = true
  1726. }
  1727. self.km_beginSheet(windowC: progressC!)
  1728. }
  1729. // 白边距
  1730. @objc func smart_cropAllPage() {
  1731. var size = NSZeroSize
  1732. for i in 0 ..< self.listView.document.pageCount {
  1733. let page = self.listView.document.page(at: i)
  1734. let rect = KMCropTools.getPageForegroundBox(page!)
  1735. size.width = fmax(size.width, NSWidth(rect))
  1736. size.height = fmax(size.height, NSHeight(rect))
  1737. }
  1738. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1739. var rectArray: Array<NSRect> = []
  1740. for i in 0 ..< self.listView.document.pageCount {
  1741. progressC?.increment(by: Double(i))
  1742. progressC?.doubleValue = Double(i)
  1743. let page = self.listView.document.page(at: i)
  1744. var rect = KMCropTools.getPageForegroundBox(page!)
  1745. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1746. // if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1747. // rect.origin.x = rect.maxX-size.width
  1748. // }
  1749. // rect.origin.y = rect.maxY-size.height
  1750. // rect.size = size
  1751. // if (NSWidth(rect) > NSWidth(bounds)) {
  1752. // rect.size.width = NSWidth(bounds)
  1753. // }
  1754. // if (NSHeight(rect) > NSHeight(bounds)) {
  1755. // rect.size.height = NSHeight(bounds)
  1756. // }
  1757. //
  1758. // if (NSMinX(rect) < NSMinX(bounds)) {
  1759. // rect.origin.x = NSMinX(bounds)
  1760. // } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1761. // rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1762. // }
  1763. //
  1764. // if (NSMinY(rect) < NSMinY(bounds)) {
  1765. // rect.origin.y = NSMinY(bounds)
  1766. // } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1767. // rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1768. // }
  1769. rectArray.append(rect)
  1770. }
  1771. cropPages(to: rectArray)
  1772. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1773. }
  1774. // 自动
  1775. @objc func auto_cropAllPage() {
  1776. var size = NSZeroSize
  1777. for i in 0 ..< self.listView.document.pageCount {
  1778. let page = self.listView.document.page(at: i)
  1779. let rect = KMCropTools.getPageForegroundBox(page!)
  1780. size.width = fmax(size.width, NSWidth(rect))
  1781. size.height = fmax(size.height, NSHeight(rect))
  1782. }
  1783. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1784. var rectArray: Array<NSRect> = []
  1785. for i in 0 ..< self.listView.document.pageCount {
  1786. progressC?.increment(by: Double(i))
  1787. progressC?.doubleValue = Double(i)
  1788. let page = self.listView.document.page(at: i)
  1789. var rect = KMCropTools.getPageForegroundBox(page!)
  1790. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1791. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1792. rect.origin.x = rect.maxX-size.width
  1793. }
  1794. rect.origin.y = rect.maxY-size.height
  1795. rect.size = size
  1796. if (NSWidth(rect) > NSWidth(bounds)) {
  1797. rect.size.width = NSWidth(bounds)
  1798. }
  1799. if (NSHeight(rect) > NSHeight(bounds)) {
  1800. rect.size.height = NSHeight(bounds)
  1801. }
  1802. if (NSMinX(rect) < NSMinX(bounds)) {
  1803. rect.origin.x = NSMinX(bounds)
  1804. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1805. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1806. }
  1807. if (NSMinY(rect) < NSMinY(bounds)) {
  1808. rect.origin.y = NSMinY(bounds)
  1809. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1810. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1811. }
  1812. rectArray.append(rect)
  1813. }
  1814. cropPages(to: rectArray)
  1815. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1816. }
  1817. @objc func cropAllPage() {
  1818. var rect = [NSIntegralRect(self.listView?.currentSelectionRect() ?? .zero), .zero]
  1819. var rectArray: Array<NSRect> = []
  1820. let emptySelection = NSIsEmptyRect(rect.first ?? .zero)
  1821. if (emptySelection) {
  1822. guard let count = self.listView?.document?.pageCount, count > 0 else {
  1823. KMPrint("listView | document is nil.", beep: true)
  1824. return
  1825. }
  1826. rect[0] = .zero
  1827. rect[1] = .zero
  1828. self.beginProgressSheet(withMessage: NSLocalizedString("Cropping Pages", comment: "Message for progress sheet"), maxValue: min(18, count))
  1829. if (count == 1) {
  1830. if let page = self.listView.document.page(at: 0) {
  1831. rect[0] = KMCropTools.getPageForegroundBox(page)
  1832. }
  1833. progressC?.increment(by: 1)
  1834. } else if (count < 19) {
  1835. for i in 0 ..< 19 {
  1836. if let page = self.listView.document.page(at: UInt(i)) {
  1837. rect[i % 2] = NSUnionRect(rect[i % 2], KMCropTools.getPageForegroundBox(page))
  1838. progressC?.increment(by: Double(i))
  1839. }
  1840. }
  1841. } else {
  1842. let start = [1, (count - 5) / 2, count - 6]
  1843. var cnt = 0
  1844. for j in 0 ..< 3 {
  1845. for i in 0 ..< 6 {
  1846. let k = Int(start[j] + UInt(i))
  1847. if let page = self.listView.document.page(at: UInt(k)) {
  1848. rect[k % 2] = NSUnionRect(rect[k % 2], KMCropTools.getPageForegroundBox(page))
  1849. cnt += 1
  1850. progressC?.increment(by: Double(cnt))
  1851. }
  1852. }
  1853. }
  1854. }
  1855. let w = fmax(NSWidth(rect[0]), NSWidth(rect[1]))
  1856. let h = fmax(NSHeight(rect[0]), NSHeight(rect[1]))
  1857. for j in 0 ..< 2 {
  1858. rect[j] = NSMakeRect(floor(NSMidX(rect[j]) - 0.5 * w), floor(NSMidY(rect[j]) - 0.5 * h), w, h)
  1859. }
  1860. rectArray.append(rect.first ?? .zero)
  1861. rectArray.append(rect.last ?? .zero)
  1862. } else {
  1863. rectArray.append(rect.first ?? .zero)
  1864. }
  1865. self.cropPages(to: rectArray)
  1866. // 执行右键操作后,需要取消框选区域
  1867. if self.listView.toolMode == .selectToolMode {
  1868. objc_sync_enter(self)
  1869. self.listView.selectionRect = NSZeroRect
  1870. self.listView.selectionPageIndex = UInt(NSNotFound)
  1871. objc_sync_exit(self)
  1872. }
  1873. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1874. }
  1875. func cropPages(to rects: Array<NSRect>) {
  1876. let currentPage = self.listView.currentPage()
  1877. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1878. var oldRectArray: Array<NSRect> = []
  1879. let rectCount = rects.count
  1880. for i in 0 ..< self.listView.document.pageCount {
  1881. let page = self.listView.document.page(at: i)
  1882. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page?.bounds(for: .mediaBox))!)
  1883. let oldRect = page?.bounds(for: .cropBox)
  1884. oldRectArray.append(oldRect!)
  1885. page?.setBounds(rect, for: .cropBox)
  1886. }
  1887. let undoManager = self.listView.undoManager
  1888. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1889. /// 刷新预览视图
  1890. self.listView.layoutDocumentView()
  1891. self.listView.displayBox = .cropBox
  1892. self.listView.go(to: currentPage)
  1893. self.listView.go(to: visibleRect, on: currentPage)
  1894. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1895. self.dismissProgressSheet()
  1896. }
  1897. }
  1898. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1899. if (limit) {
  1900. let document = self.listView.document ?? CPDFDocument()
  1901. if document?.documentURL == nil {
  1902. return
  1903. }
  1904. var doucumentURL : URL = self.listView.document.documentURL
  1905. if doucumentURL.path.count > 0 {
  1906. let docDir = NSTemporaryDirectory()
  1907. let documentName : String = doucumentURL.path.lastPathComponent
  1908. let path = docDir.stringByAppendingPathComponent(documentName)
  1909. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1910. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1911. let writeSuccess = data != nil
  1912. if writeSuccess == false {
  1913. __NSBeep()
  1914. return;
  1915. }
  1916. doucumentURL = URL(fileURLWithPath: path)
  1917. }
  1918. let array = [doucumentURL]
  1919. let picker = NSSharingServicePicker.init(items: array)
  1920. if sender.shareButton.window != nil {
  1921. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1922. } else {
  1923. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1924. }
  1925. return
  1926. }
  1927. let document = self.listView.document ?? CPDFDocument()
  1928. if document?.documentURL == nil {
  1929. return
  1930. }
  1931. var doucumentURL : URL = self.listView.document.documentURL
  1932. if doucumentURL.path.count > 0 {
  1933. let docDir = NSTemporaryDirectory()
  1934. let documentName : String = doucumentURL.path.lastPathComponent
  1935. let path = docDir.stringByAppendingPathComponent(documentName)
  1936. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1937. if writeSuccess == false {
  1938. __NSBeep()
  1939. return;
  1940. }
  1941. doucumentURL = URL(fileURLWithPath: path)
  1942. }
  1943. let array = [doucumentURL]
  1944. let picker = NSSharingServicePicker.init(items: array)
  1945. if sender.shareButton.window != nil {
  1946. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1947. } else {
  1948. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1949. }
  1950. }
  1951. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1952. if (limit) {
  1953. let document = self.listView.document ?? CPDFDocument()
  1954. var path: String?
  1955. if document?.documentURL != nil {
  1956. path = document?.documentURL.path ?? ""
  1957. }
  1958. if path?.count ?? 0 > 0 {
  1959. let docDir = NSTemporaryDirectory()
  1960. let documentName : String = path?.lastPathComponent ?? ""
  1961. path = docDir.stringByAppendingPathComponent(documentName)
  1962. }
  1963. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  1964. var tfileName = path?.deletingPathExtension.lastPathComponent
  1965. let tStdFileSuffix = "_flatten"
  1966. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  1967. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  1968. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path ?? ""))
  1969. let success = data != nil
  1970. if success {
  1971. let url = URL(fileURLWithPath: path ?? "")
  1972. let picker = NSSharingServicePicker.init(items: [url])
  1973. if sender.shareButton.window != nil {
  1974. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1975. } else {
  1976. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1977. }
  1978. }
  1979. return
  1980. }
  1981. let document = self.listView.document ?? CPDFDocument()
  1982. var path: String?
  1983. if document?.documentURL != nil {
  1984. path = document?.documentURL.path ?? ""
  1985. }
  1986. if path?.count ?? 0 > 0 {
  1987. let docDir = NSTemporaryDirectory()
  1988. let documentName : String = path?.lastPathComponent ?? ""
  1989. path = docDir.stringByAppendingPathComponent(documentName)
  1990. }
  1991. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  1992. var tfileName = path?.deletingPathExtension.lastPathComponent
  1993. let tStdFileSuffix = "_flatten"
  1994. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  1995. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  1996. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  1997. if success {
  1998. let url = URL(fileURLWithPath: path ?? "")
  1999. let picker = NSSharingServicePicker.init(items: [url])
  2000. if sender.shareButton.window != nil {
  2001. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2002. } else {
  2003. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2004. }
  2005. }
  2006. }
  2007. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  2008. if (limit) {
  2009. let document = self.listView.document ?? CPDFDocument()
  2010. var path: String?
  2011. if document?.documentURL != nil {
  2012. path = document?.documentURL.path ?? ""
  2013. }
  2014. if path?.count ?? 0 > 0{
  2015. let docDir = NSTemporaryDirectory()
  2016. let documentName : String = path?.lastPathComponent ?? ""
  2017. path = docDir.stringByAppendingPathComponent(documentName)
  2018. }
  2019. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  2020. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path ?? ""), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2021. var writeSuccess = data != nil
  2022. if writeSuccess == false {
  2023. __NSBeep()
  2024. return;
  2025. }
  2026. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2027. for i in 0 ... (newDocument?.pageCount ?? 1)-1 {
  2028. let page = newDocument?.page(at: i)
  2029. var annotations : [CPDFAnnotation] = []
  2030. for annotation in page!.annotations {
  2031. annotations.append(annotation)
  2032. }
  2033. for annotation in annotations {
  2034. annotation.page.removeAnnotation(annotation)
  2035. }
  2036. }
  2037. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? "")) ?? false
  2038. if writeSuccess {
  2039. let url = URL(fileURLWithPath: path ?? "")
  2040. let picker = NSSharingServicePicker.init(items: [url])
  2041. if sender.shareButton.window != nil {
  2042. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2043. } else {
  2044. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2045. }
  2046. }
  2047. return
  2048. }
  2049. let document = self.listView.document ?? CPDFDocument()
  2050. var path: String?
  2051. if document?.documentURL != nil {
  2052. path = document?.documentURL.path ?? ""
  2053. }
  2054. if path?.count ?? 0 > 0 {
  2055. let docDir = NSTemporaryDirectory()
  2056. let documentName : String = path?.lastPathComponent ?? ""
  2057. path = docDir.stringByAppendingPathComponent(documentName)
  2058. }
  2059. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  2060. if writeSuccess == false {
  2061. __NSBeep()
  2062. return;
  2063. }
  2064. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2065. for i in 0 ... (newDocument?.pageCount ?? 1)-1 {
  2066. let page = newDocument!.page(at: i)
  2067. var annotations : [CPDFAnnotation] = []
  2068. for annotation in page!.annotations {
  2069. annotations.append(annotation)
  2070. }
  2071. for annotation in annotations {
  2072. annotation.page.removeAnnotation(annotation)
  2073. }
  2074. }
  2075. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  2076. if writeSuccess ?? false {
  2077. let url = URL(fileURLWithPath: path ?? "")
  2078. let picker = NSSharingServicePicker.init(items: [url])
  2079. if sender.shareButton.window != nil {
  2080. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2081. } else {
  2082. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2083. }
  2084. }
  2085. }
  2086. // 开启/关闭左边栏
  2087. @objc func toggleLeftPane() -> Void {
  2088. // if lastLeftPanWidth >= functionWidth {
  2089. self.model.leftPanelOpen = true
  2090. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2091. // } else {
  2092. // leftPanelOpen = false
  2093. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  2094. // }
  2095. }
  2096. // 开启左边栏
  2097. @objc func openLeftPane() -> Void {
  2098. self.model.leftPanelOpen = true
  2099. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2100. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  2101. }
  2102. // 关闭左边栏
  2103. @objc func closeLeftPane() -> Void {
  2104. self.model.leftPanelOpen = false
  2105. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2106. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = false
  2107. }
  2108. // 开启/关闭右边栏
  2109. @objc func toggleRightPane() -> Void {
  2110. if self.model.lastRightPanWidth > 5 {
  2111. self.model.rightPanelIsOpen = false
  2112. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2113. } else {
  2114. self.model.rightPanelIsOpen = true
  2115. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2116. }
  2117. }
  2118. @objc func openRightPane() -> Void {
  2119. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2120. if self.model.rightPanelIsOpen {
  2121. return
  2122. }
  2123. self.model.rightPanelIsOpen = true
  2124. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  2125. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2126. }
  2127. }
  2128. @objc func closeRightPane() -> Void {
  2129. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2130. self.model.rightPanelIsOpen = false
  2131. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  2132. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2133. }
  2134. }
  2135. func rename(_ sender: NSNotification) -> Void {
  2136. if (self.view.window == nil || self.view.window!.isVisible == false) {
  2137. return
  2138. }
  2139. let tabController = sender.object as? CTTabController
  2140. if tabController?.title == self.document?.documentURL.lastPathComponent {
  2141. if let doc = self.myDocument, doc.isDocumentEdited {
  2142. Task {
  2143. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  2144. if resp != .alertFirstButtonReturn { // 取消
  2145. return
  2146. }
  2147. doc.updateChangeCount(.changeCleared)
  2148. // doc.save(nil)
  2149. self.document?.write(to: doc.fileURL)
  2150. Task { @MainActor in
  2151. self._renameForSavePanel(tabController)
  2152. }
  2153. }
  2154. return
  2155. }
  2156. self._renameForSavePanel(tabController)
  2157. }
  2158. }
  2159. func pdfSaveAlertView(_ sender: NSNotification) {
  2160. if AutoSaveManager.manager.isSaving{
  2161. return
  2162. }
  2163. var num = 0
  2164. if self.listView.document != nil{
  2165. num = Int(self.listView.document.pageCount)
  2166. }
  2167. if Thread.current.isMainThread {
  2168. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2169. } else {
  2170. DispatchQueue.main.async {
  2171. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2172. }
  2173. }
  2174. }
  2175. func pdfSaveFinishAlertView(_ sender: NSNotification) {
  2176. if AutoSaveManager.manager.isSaving{
  2177. return
  2178. }
  2179. if Thread.current.isMainThread {
  2180. self.dismissProgressSheet()
  2181. } else {
  2182. DispatchQueue.main.async {
  2183. self.dismissProgressSheet()
  2184. }
  2185. }
  2186. }
  2187. private func _renameForSavePanel(_ tabC: CTTabController?) {
  2188. let outputSavePanel = NSSavePanel()
  2189. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  2190. outputSavePanel.allowedFileTypes = ["pdf"]
  2191. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  2192. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  2193. let resp = outputSavePanel.runModal()
  2194. if resp == .OK {
  2195. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  2196. let fileURL = pdfDocument?.documentURL
  2197. let fileManager = FileManager.default
  2198. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  2199. var result = true
  2200. do {
  2201. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  2202. } catch {
  2203. result = false
  2204. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  2205. }
  2206. if (result) {
  2207. tabC?.title = outputSavePanel.url!.lastPathComponent
  2208. // self.myDocument?.fileURL = newFileURL
  2209. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  2210. self.model.isSaveKeyChain = false
  2211. newPdfDocument.unlock(withPassword: self.document?.password)
  2212. if (newPdfDocument.pageCount > 0) {
  2213. self.setDocument = newPdfDocument
  2214. }
  2215. }
  2216. }
  2217. } else {
  2218. outputSavePanel.close()
  2219. }
  2220. }
  2221. func showInFinder(_ sender: Any) -> Void {
  2222. if sender is NSNotification {
  2223. let tabController = (sender as! NSNotification).object as? CTTabController
  2224. if tabController?.title == self.document?.documentURL.lastPathComponent {
  2225. let file: URL = (self.myDocument?.fileURL)!
  2226. if FileManager.default.fileExists(atPath: file.path) {
  2227. NSWorkspace.shared.activateFileViewerSelecting([file])
  2228. }
  2229. }
  2230. } else {
  2231. guard let url = self.myDocument?.fileURL else { return }
  2232. let file: URL = url
  2233. if FileManager.default.fileExists(atPath: file.path) {
  2234. NSWorkspace.shared.activateFileViewerSelecting([file])
  2235. }
  2236. }
  2237. }
  2238. func showOrHideNotes() {
  2239. self.listView.hideNotes = !self.listView.hideNotes
  2240. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  2241. //BOTA 注释列表显示隐藏
  2242. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2243. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2244. }
  2245. func closeTab(_ sender: NSNotification) -> Void {
  2246. let tabController = sender.object as? CTTabController
  2247. if tabController?.title == self.document?.documentURL.lastPathComponent {
  2248. print("closeTab")
  2249. self.leftSideViewController.clearAnnotationFilterData()
  2250. self.leftSideViewController.clearNotification()
  2251. }
  2252. }
  2253. @IBAction func toggleSplitPDF(_ sender: Any) {
  2254. if let menuItem = sender as? NSMenuItem {
  2255. splitView(withTag: menuItem.tag)
  2256. }
  2257. }
  2258. @IBAction func readMode(_ sender: Any) {
  2259. isReadMode = !isReadMode
  2260. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  2261. UserDefaults.standard.synchronize()
  2262. if isReadMode {
  2263. CustomAlertView.alertView(message: NSLocalizedString("Read Mode On", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2264. } else {
  2265. CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2266. }
  2267. }
  2268. func handlePageBoundsDidChange(page: CPDFPage?, action: String) {
  2269. // NSDictionary *info = [notification userInfo];
  2270. // PDFPage *page = [info objectForKey:SKPDFPagePageKey];
  2271. // NSString *action = [info objectForKey:SKPDFPageActionKey];
  2272. // BOOL displayChanged = [action isEqualToString:SKPDFPageActionCrop] == NO || [pdfView displayBox] == kPDFDisplayBoxCropBox;
  2273. let displayChanged = action == CPDFPage.Action.crop || self.listView.displayBox == .cropBox
  2274. // if self.listView.displayBox == .cropBox {
  2275. // KMPrint("cropBox")
  2276. // } else if self.listView.displayBox == .artBox {
  2277. // KMPrint("artBox")
  2278. // } else if self.listView.displayBox == .trimBox {
  2279. // KMPrint("trimBox")
  2280. // } else if self.listView.displayBox == .bleedBox {
  2281. // KMPrint("bleedBox")
  2282. // } else if self.listView.displayBox == .mediaBox {
  2283. // KMPrint("mediaBox")
  2284. // } else {
  2285. // KMPrint("other \(self.listView.displayBox.rawValue)")
  2286. // }
  2287. if (displayChanged) {
  2288. self.listView.layoutDocumentView()
  2289. }
  2290. if (page != nil) {
  2291. let idx = page!.pageIndex()
  2292. if (displayChanged) {
  2293. self.leftSideViewController.updateThumbnail(at: Int(idx))
  2294. }
  2295. } else {
  2296. if (displayChanged) {
  2297. self.leftSideViewController.allThumbnailsNeedUpdate()
  2298. }
  2299. }
  2300. self.leftSideViewController.updateSnapshotsIfNeed(for: page)
  2301. // [secondaryPdfView requiresDisplay];
  2302. self.secondaryPdfView?.setNeedsDisplayForVisiblePages()
  2303. //
  2304. if UserDefaults.standard.bool(forKey: SKDisplayPageBoundsKey) {
  2305. // [self updateRightStatus];
  2306. }
  2307. }
  2308. func changeLineAttribute(_ sender: Any?) {
  2309. var inspector = sender as? KMLineInspector
  2310. if inspector == nil {
  2311. inspector = KMLineInspector.shared
  2312. }
  2313. let action = inspector?.currentLineChangeAction ?? .no
  2314. for annotation in self.listView.activeAnnotations {
  2315. guard let anno = annotation as? CPDFAnnotation else {
  2316. continue
  2317. }
  2318. if anno.hasBorder() {
  2319. // if (mwcFlags.updatingLine == 0 && [annotation hasBorder]) {
  2320. // mwcFlags.updatingLine = 1;
  2321. switch (action) {
  2322. case .lineWidth:
  2323. anno.setLineWidth(inspector?.lineWidth ?? 0)
  2324. break
  2325. case .style:
  2326. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  2327. break
  2328. case .dashPattern:
  2329. anno.setDashPattern(inspector?.dashPattern ?? [])
  2330. break
  2331. case .startLineStyle:
  2332. if anno.isLine() {
  2333. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  2334. }
  2335. break
  2336. case .endLineStyle:
  2337. if anno.isLine() {
  2338. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  2339. }
  2340. break
  2341. case .no:
  2342. break
  2343. }
  2344. // mwcFlags.updatingLine = 0;
  2345. // in case one property changes another, e.g. when adding a dashPattern the borderStyle can change
  2346. }
  2347. }
  2348. // [self updateLineInspector];
  2349. }
  2350. // MARK: -
  2351. // MARK: 显示窗口
  2352. internal func showCompressWindow(url: URL? = nil) {
  2353. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  2354. KMPrint("压缩窗口已显示")
  2355. return
  2356. }
  2357. let windowController = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  2358. self.view.window?.beginSheet(windowController.window!)
  2359. self.currentWindowController = windowController
  2360. windowController.password = self.listView?.document?.password ?? ""
  2361. // if let _url = url {
  2362. // windowController.oriDocumentUrl = self.listView.document.documentURL
  2363. // windowController.documentURL = _url
  2364. // } else {
  2365. windowController.documentURL = self.listView.document.documentURL
  2366. // }
  2367. windowController.itemClick = { [weak self] in
  2368. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2369. self?.currentWindowController = nil
  2370. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2371. }
  2372. windowController.batchAction = { [weak self] view, filePaths in
  2373. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2374. self?.currentWindowController = nil
  2375. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2376. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2377. // batchWindowController.window?.makeKeyAndOrderFront("")
  2378. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2379. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2380. batchWindowController.window?.makeKeyAndOrderFront("")
  2381. }
  2382. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  2383. if (result) {
  2384. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2385. self?.currentWindowController = nil
  2386. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2387. if (openDocument) {
  2388. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2389. } else {
  2390. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2391. }
  2392. } else {
  2393. let alert = NSAlert()
  2394. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2395. alert.runModal()
  2396. }
  2397. }
  2398. }
  2399. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  2400. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  2401. KMPrint("转档窗口已显示")
  2402. return
  2403. }
  2404. var convertT: KMConvertType = .Word
  2405. var windowController: KMConvertBaseWindowController?
  2406. if (type == .word) { /// Word
  2407. convertT = .Word
  2408. } else if (type == .excel) {
  2409. convertT = .Excel
  2410. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  2411. if (type == .ppt) {
  2412. convertT = .PPT
  2413. } else if (type == .rtf) {
  2414. convertT = .RTF
  2415. } else if (type == .html) {
  2416. convertT = .HTML
  2417. } else if (type == .conversion_text) {
  2418. convertT = .Text
  2419. }
  2420. } else if (type == .csv) {
  2421. convertT = .CSV
  2422. } else if (type == .conversion_image) {
  2423. windowController = KMConvertImageWindowController()
  2424. convertT = .JPEG
  2425. }
  2426. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  2427. var url: URL?
  2428. if (documentUrl != nil) {
  2429. url = documentUrl
  2430. windowController?.oriDocumentUrl = self.listView.document.documentURL
  2431. } else {
  2432. url = self.listView.document.documentURL
  2433. }
  2434. self.showAllConvertWindow(convertT: convertT)
  2435. }
  2436. //MARK: 转档 -
  2437. func showAllConvertWindow(convertT: KMConvertType) {
  2438. self.ConvertTrackEvent(type: convertT)
  2439. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  2440. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2441. var type: KMConvertWithPDFType = .WordAdvance
  2442. switch convertT {
  2443. case .Word:
  2444. break
  2445. case .Excel:
  2446. type = .Excel
  2447. case .PPT:
  2448. type = .PowerPoint
  2449. case .RTF:
  2450. type = .RTF
  2451. case .CSV:
  2452. type = .CSV
  2453. case .HTML:
  2454. type = .HTML
  2455. case .Text:
  2456. type = .Text
  2457. case .JPEG:
  2458. type = .JPEG
  2459. case .PNG:
  2460. type = .PNG
  2461. case .GIF:
  2462. type = .GIF
  2463. case .JPG:
  2464. type = .JPG
  2465. case .TIFF:
  2466. type = .TIFF
  2467. case .TGA:
  2468. type = .TGA
  2469. case .BMP:
  2470. type = .BMP
  2471. case .JP2:
  2472. type = .JPEG2000
  2473. case .AdvancedWord:
  2474. break
  2475. default:
  2476. break
  2477. }
  2478. // let document = self.document
  2479. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2480. var needShowHint = false
  2481. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2482. needShowHint = true
  2483. } else {
  2484. var needContinue = false
  2485. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2486. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2487. let ss = self.document?.documentURL.path
  2488. if arr.contains(ss!) {
  2489. needContinue = false
  2490. }else {
  2491. needContinue = true
  2492. }
  2493. }else {
  2494. needContinue = true
  2495. }
  2496. if needContinue {
  2497. let ss = self.document?.documentURL.path
  2498. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2499. file.password = document?.password ?? ""
  2500. KMBatchOperateManager.defaultManager.files?.append(file)
  2501. }
  2502. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2503. batchWindowController.switchToConvertType(convertType: type)
  2504. }
  2505. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2506. if needShowHint {
  2507. batchWindowController.showIsConvertingHint()
  2508. } else {
  2509. }
  2510. }
  2511. }
  2512. self.km_beginSheet(windowC: convertWC)
  2513. }
  2514. func ConvertTrackEvent(type: KMConvertType) {
  2515. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  2516. switch type {
  2517. case .Word:
  2518. eventStr = "Btn_SubTbr_Converter_ToWord"
  2519. break
  2520. case .Excel:
  2521. eventStr = "Btn_SubTbr_Converter_ToExcel"
  2522. case .PPT:
  2523. eventStr = "Btn_SubTbr_Converter_ToPPT"
  2524. case .RTF:
  2525. eventStr = "Btn_SubTbr_Converter_ToRTF"
  2526. case .CSV:
  2527. eventStr = "Btn_SubTbr_Converter_ToCSV"
  2528. case .HTML:
  2529. eventStr = "Btn_SubTbr_Converter_ToHTML"
  2530. case .Text:
  2531. eventStr = "Btn_SubTbr_Converter_ToText"
  2532. case .JPEG:
  2533. eventStr = "Btn_SubTbr_Converter_ToImage"
  2534. case .PNG:
  2535. eventStr = "Btn_SubTbr_Converter_ToImage"
  2536. case .GIF:
  2537. eventStr = "Btn_SubTbr_Converter_ToImage"
  2538. case .JPG:
  2539. eventStr = "Btn_SubTbr_Converter_ToImage"
  2540. case .TIFF:
  2541. eventStr = "Btn_SubTbr_Converter_ToImage"
  2542. case .TGA:
  2543. eventStr = "Btn_SubTbr_Converter_ToImage"
  2544. case .BMP:
  2545. eventStr = "Btn_SubTbr_Converter_ToImage"
  2546. case .JP2:
  2547. eventStr = "Btn_SubTbr_Converter_ToImage"
  2548. case .AdvancedWord:
  2549. eventStr = "Btn_SubTbr_Converter_ToWord"
  2550. break
  2551. default:
  2552. break
  2553. }
  2554. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  2555. }
  2556. //MARK: 转档 - OCR
  2557. func showOCRWindow() {
  2558. if !IAPProductsManager.default().isAvailableAllFunction(){
  2559. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2560. return
  2561. }
  2562. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  2563. com.currentIndexPage = self.listView.currentPageIndex
  2564. self.km_beginSheet(windowC: com)
  2565. }
  2566. //MARK: 导出图片
  2567. func extractImageAction(num: Int) {
  2568. if !IAPProductsManager.default().isAvailableAllFunction(){
  2569. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2570. return
  2571. }
  2572. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2573. let alert = NSAlert()
  2574. alert.alertStyle = .critical
  2575. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2576. alert.runModal()
  2577. return
  2578. }
  2579. // if sender is KMToolbarItem {
  2580. // (sender as! KMToolbarItem).isSelected = false
  2581. // }
  2582. let document = self.listView.document
  2583. var fileURL = document?.documentURL
  2584. if num == 1 {
  2585. let pageCount = document?.pageCount ?? 0
  2586. let indeSet = NSMutableIndexSet()
  2587. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2588. if indeSet.count == 0 {
  2589. return
  2590. }
  2591. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2592. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2593. let outputSavePanel = NSSavePanel()
  2594. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2595. outputSavePanel.allowsOtherFileTypes = true
  2596. outputSavePanel.isExtensionHidden = true
  2597. outputSavePanel.canCreateDirectories = true
  2598. outputSavePanel.nameFieldStringValue = tFileName
  2599. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2600. if result == NSApplication.ModalResponse.OK {
  2601. DispatchQueue.main.async {
  2602. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2603. let tDestFile = outputSavePanel.url!.path
  2604. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2605. let pdfconverter = PDFConvertObject()
  2606. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2607. self.dismissProgressSheet()
  2608. let fileManager = FileManager.default
  2609. if fileManager.fileExists(atPath: tDestFile) {
  2610. let workspace = NSWorkspace.shared
  2611. let url = URL(fileURLWithPath: tDestFile)
  2612. workspace.activateFileViewerSelecting([url])
  2613. }
  2614. }
  2615. }
  2616. })
  2617. return
  2618. }
  2619. if fileURL != nil {
  2620. self.myDocument?.save(nil)
  2621. } else {
  2622. let myDocument = self.myDocument
  2623. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2624. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2625. if writeSuccess {
  2626. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2627. fileURL = document?.documentURL
  2628. } else {
  2629. NSSound.beep()
  2630. return
  2631. }
  2632. }
  2633. let extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2634. extract.docPath = fileURL?.path ?? ""
  2635. extract.password = document?.password ?? ""
  2636. extract.currentPage = self.listView.currentPageIndex
  2637. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2638. self.km_beginSheet(windowC: extract)
  2639. extract.selectCurrentPageBtn()
  2640. // self.showCreateStamp()
  2641. // self.showAddSignature()
  2642. }
  2643. //MARK: 创建文字图章示例实际上不会在这里使用
  2644. func showCreateStamp() {
  2645. let stampCreaterWindowController = KMStampCreaterWindowController()
  2646. stampCreaterWindowController.window?.backgroundColor = .clear
  2647. self.km_beginSheet(windowC: stampCreaterWindowController)
  2648. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  2649. if result == 1 {
  2650. }
  2651. }
  2652. }
  2653. //MARK: 添加签名示例实际上不会在这里使用
  2654. func showAddSignature() {
  2655. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")
  2656. // signatureWindowController.window?.backgroundColor = .clear
  2657. // signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2658. //
  2659. // }
  2660. self.view.window?.beginSheet(signatureWindowController.window!, completionHandler: { returnCode in
  2661. })
  2662. }
  2663. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2664. // if progressController == nil {
  2665. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2666. // }
  2667. let progress = SKProgressController()
  2668. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2669. progress.window?.contentView?.wantsLayer = true
  2670. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2671. progress.progressField.textColor = NSColor.white
  2672. progress.message = NSLocalizedString("Converting...", comment: "")
  2673. progressC = progress
  2674. progressC?.message = message
  2675. if maxValue > 0 {
  2676. progressC?.indeterminate = false
  2677. progressC?.maxValue = Double(maxValue)
  2678. progressC?.progressBar.doubleValue = 0.3
  2679. } else {
  2680. progressC?.indeterminate = true
  2681. }
  2682. self.km_beginSheet(windowC: progressC!)
  2683. }
  2684. func dismissProgressSheet() {
  2685. progressC?.stopAnimation()
  2686. self.km_endSheet()
  2687. progressC = nil
  2688. }
  2689. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2690. let newArr = NSMutableArray()
  2691. for item in files {
  2692. newArr.add(item.filePath)
  2693. }
  2694. return newArr as! [String]
  2695. }
  2696. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2697. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2698. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2699. if (result == .cancel) {
  2700. return
  2701. }
  2702. // 解除权限
  2703. self?.listView.document.unlock(withPassword: password)
  2704. // 隐藏提示
  2705. self?.hiddenSecureLimitTip()
  2706. // 去打印
  2707. if let data = self?.saveWatermarkFlag, !data {
  2708. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  2709. return
  2710. }
  2711. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  2712. _ = CPDFDocument(url: _url)
  2713. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  2714. } else {
  2715. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2716. }
  2717. }
  2718. return
  2719. }
  2720. if (!self.saveWatermarkFlag) {
  2721. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2722. return
  2723. }
  2724. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  2725. let _document = CPDFDocument(url: _url)
  2726. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  2727. } else {
  2728. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2729. }
  2730. }
  2731. // MARK: - 图片注释
  2732. @IBAction func imageAnnotation(_ sender: Any) {
  2733. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  2734. changeAnnotationMode(sender)
  2735. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2736. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2737. return
  2738. }
  2739. let accessoryCtr = KMImageAccessoryController()
  2740. let openPanel = NSOpenPanel()
  2741. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2742. openPanel.allowsMultipleSelection = false
  2743. openPanel.accessoryView = accessoryCtr.view
  2744. // if #available(macOS 10.11, *) {
  2745. openPanel.canSelectHiddenExtension = true
  2746. // }
  2747. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2748. if result == .OK {
  2749. guard let url = openPanel.url else {
  2750. return
  2751. }
  2752. let filePath = url.path
  2753. if filePath.pathExtension.lowercased() == "pdf" {
  2754. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2755. NSSound.beep()
  2756. return
  2757. }
  2758. }
  2759. let image = NSImage(contentsOfFile: url.path)
  2760. let isDamageImage: Bool = self.isDamageImage(image!, imagePath: url.path)
  2761. if isDamageImage {
  2762. let alert = NSAlert()
  2763. alert.alertStyle = .critical
  2764. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2765. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2766. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2767. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2768. if response == .alertFirstButtonReturn {
  2769. // Handle cancel button clicked
  2770. }
  2771. }
  2772. }
  2773. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2774. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2775. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2776. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  2777. }
  2778. }
  2779. }
  2780. }
  2781. @IBAction func tableAnnotation(_ sender: Any) {
  2782. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2783. changeAnnotationMode(sender)
  2784. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2785. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2786. return
  2787. }
  2788. listView.addAnnotationWithTable()
  2789. openRightPane()
  2790. }
  2791. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2792. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2793. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2794. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2795. }
  2796. if let data = image.tiffRepresentation,
  2797. let imageRep = NSBitmapImageRep(data: data) {
  2798. imageRep.size = image.size
  2799. var imageData: Data?
  2800. if path.lowercased() == "png" {
  2801. imageData = imageRep.representation(using: .png, properties: [:])
  2802. } else {
  2803. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2804. }
  2805. if let imageData = imageData {
  2806. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2807. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2808. return true
  2809. } else {
  2810. return false
  2811. }
  2812. }
  2813. }
  2814. return false
  2815. }
  2816. func tagString() -> String {
  2817. let dateFormatter = DateFormatter()
  2818. dateFormatter.dateFormat = "yyMMddHHmmss"
  2819. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2820. }
  2821. // MARK: - Split View
  2822. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2823. }
  2824. @objc func removeSecondaryPdfContentView(_ sender: Notification?) {
  2825. if let _ = sender {
  2826. NotificationCenter.default.removeObserver(self, name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  2827. }
  2828. self.secondaryPdfContentView?.removeFromSuperview()
  2829. self.newPDFSplitView.adjustSubviews()
  2830. }
  2831. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2832. if !isSinglePage && isHorizontal {
  2833. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  2834. }
  2835. if (!isSinglePage && !isHorizontal) {
  2836. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2837. }
  2838. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  2839. }
  2840. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  2841. if isSinglePage {
  2842. if self.newPDFSplitView.animating {
  2843. return
  2844. }
  2845. if self.secondaryPdfContentView?.window != nil {
  2846. self.lastSplitPDFHeight = self.lastSplitPDFHeightFloat(self.secondaryPdfContentView?.frame ?? .zero)
  2847. self.newPDFSplitView.setPosition(self.newPDFSplitView.maxPossiblePositionOfDivider(at: 0), ofDividerAt: 0, animate: true)
  2848. if self.newPDFSplitView.animating {
  2849. NotificationCenter.default.addObserver(self, selector: #selector(removeSecondaryPdfContentView), name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  2850. } else {
  2851. self.removeSecondaryPdfContentView(nil)
  2852. }
  2853. }
  2854. self.view.window?.recalculateKeyViewLoop()
  2855. if self.interactionMode == .legacyFullScreen {
  2856. self.view.window?.makeFirstResponder(self.listView)
  2857. }
  2858. } else {
  2859. if self.newPDFSplitView.animating {
  2860. return
  2861. }
  2862. self.newPDFSplitView.dividerStyle = .paneSplitter
  2863. self.newPDFSplitView.isVertical = isHorizontal
  2864. if self.secondaryPdfView?.window == nil {
  2865. let frame = self.newPDFSplitView.bounds
  2866. if (self.lastSplitPDFHeight <= 0.0) {
  2867. var DEFAULT_SPLIT_PDF_FACTOR: Float = 0.3
  2868. self.lastSplitPDFHeight = floorf(DEFAULT_SPLIT_PDF_FACTOR * self.lastSplitPDFHeightFloat(frame))
  2869. }
  2870. var position = self.lastSplitPDFHeightFloat(frame)-self.lastSplitPDFHeight-Float(self.newPDFSplitView.dividerThickness)
  2871. var point: NSPoint = .zero
  2872. var page: CPDFPage?
  2873. self.newPDFSplitView.setPosition(position.cgFloat, ofDividerAt: 0, animate: true)
  2874. if (self.secondaryPdfContentView == nil) {
  2875. // secondaryPdfContentView = [[SKGradientView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 200.0, 20.0)];
  2876. self.secondaryPdfContentView = NSView(frame: NSMakeRect(0, 0, 200, 20))
  2877. self.secondaryPdfView = KMSecondaryPDFView(frame: self.secondaryPdfContentView?.bounds ?? .zero)
  2878. self.secondaryPdfView?.autoresizingMask = [.width, .height]
  2879. // self.secondaryPdfContentView?.isHidden = true
  2880. self.secondaryPdfContentView?.addSubview(self.secondaryPdfView!)
  2881. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  2882. // self.newPDFSplitView.addArrangedSubview(self.secondaryPdfContentView!)
  2883. // // Because of a PDFView bug, display properties can not be changed before it is placed in a window
  2884. self.secondaryPdfView?.synchronizedPDFView = self.listView
  2885. self.secondaryPdfView?.backgroundColor = self.listView.backgroundColor
  2886. // [secondaryPdfView applyDefaultPageBackgroundColor];
  2887. self.secondaryPdfView?.displaysPageBreaks = false
  2888. self.secondaryPdfView?.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  2889. self.secondaryPdfView?.applyDefaultInterpolationQuality()
  2890. self.secondaryPdfView?.setGreekingThreshold(KMPreference.shared.greekThreshold.cgFloat)
  2891. self.secondaryPdfView?.setSynchronizeZoom(true)
  2892. // // [secondaryPdfView setDocument:[pdfView document]];
  2893. point = NSMakePoint(NSMinX(frame), NSMaxY(frame) - position.cgFloat - self.newPDFSplitView.dividerThickness)
  2894. page = self.listView.page(for: point, nearest: true)
  2895. //
  2896. let controlView = self.secondaryPdfView?.controlView
  2897. var color = NSColor(calibratedWhite: 0.97, alpha: 1.0)
  2898. if KMAppearance.isDarkMode() {
  2899. color = KMAppearance.Layout.l0Color()
  2900. }
  2901. // [(SKGradientView *)secondaryPdfContentView setGradient:[[[NSGradient alloc] initWithStartingColor:color endingColor:color] autorelease]];
  2902. // [(SKGradientView *)secondaryPdfContentView setAlternateGradient:nil];
  2903. var pdfRect: NSRect = .zero
  2904. var controlRect: NSRect = .zero
  2905. NSDivideRect(self.secondaryPdfContentView?.bounds ?? .zero, &controlRect, &pdfRect, NSHeight(controlView?.frame ?? .zero), .minY)
  2906. controlRect.size.width = NSWidth(controlView?.frame ?? .zero)
  2907. controlView?.frame = controlRect
  2908. controlView?.autoresizingMask = [.maxXMargin, .maxYMargin, .width]
  2909. // [(SKGradientView *)secondaryPdfContentView setMinSize:controlRect.size];
  2910. self.secondaryPdfView?.frame = pdfRect
  2911. self.secondaryPdfContentView?.addSubview(controlView!)
  2912. self.openSecondaryPdfView = KMSecondaryViewController()
  2913. self.openSecondaryPdfView?.view.frame = self.secondaryPdfContentView?.frame ?? .zero
  2914. self.secondaryPdfContentView?.addSubview(self.openSecondaryPdfView!.view)
  2915. self.openSecondaryPdfView?.secondaryView.receivedFileUrlBlock = { [weak self] fileUrl in
  2916. if let docUrl = fileUrl {
  2917. _ = self?.displaySecondaryPDFView(withUrl: docUrl)
  2918. self?.openSecondaryPdfView?.view.removeFromSuperview()
  2919. self?.openSecondaryPdfView = nil
  2920. }
  2921. }
  2922. self.openSecondaryPdfView?.delegate = self
  2923. if (!isHorizontal) {
  2924. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2925. }
  2926. } else {
  2927. self.secondaryPdfContentView?.isHidden = true
  2928. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  2929. }
  2930. // self.newPDFSplitView.setPosition(self.secondaryPdfContentView?.bounds.size.width ?? 120, ofDividerAt: 1, animate: true)
  2931. if (page != nil) {
  2932. self.secondaryPdfView?.go(toPageIndex: Int(page!.pageIndex()), animated: false)
  2933. // point = [secondaryPdfView convertPoint:[secondaryPdfView convertPoint:[pdfView convertPoint:point toPage:page] fromPage:page] toView:[secondaryPdfView documentView]];
  2934. let tmpP = self.listView.convert(point, to: page)
  2935. let conP = self.secondaryPdfView?.convert(tmpP, from: page) ?? .zero
  2936. point = self.secondaryPdfView?.convert(conP, to: self.secondaryPdfView?.documentView()) ?? .zero
  2937. if let docView = self.secondaryPdfView?.documentView(), docView.contentView.isFlipped == false {
  2938. point.y -= docView.isFlipped ? -NSHeight(docView.visibleRect) : NSHeight(docView.visibleRect)
  2939. }
  2940. self.secondaryPdfView?.documentView()?.scroll(point)
  2941. self.secondaryPdfView?.layoutDocumentView()
  2942. }
  2943. }
  2944. self.view.window?.recalculateKeyViewLoop()
  2945. if self.interactionMode == .legacyFullScreen {
  2946. self.view.window?.makeFirstResponder(self.listView)
  2947. }
  2948. if self.secondaryPdfView?.document == nil {
  2949. self.openSecondaryPdfView?.viewHighlyAdaptive()
  2950. }
  2951. }
  2952. }
  2953. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  2954. if (self.newPDFSplitView.isVertical) {
  2955. return Float(NSWidth(rect))
  2956. } else {
  2957. return Float(NSHeight(rect))
  2958. }
  2959. }
  2960. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  2961. let document = CPDFDocument.init(url: url)
  2962. if document != nil {
  2963. self.secondaryPdfView?.document = nil
  2964. self.secondaryPdfView?.document = document
  2965. self.rightSideViewController.annotationProperties.openPropertiesType = .pageDisplay
  2966. return true
  2967. } else {
  2968. return false
  2969. }
  2970. }
  2971. func updateNextAndPreViousButtonState() {
  2972. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2973. let view = item?.customizeView as? KMToolbarPreviousNextItemView
  2974. if let can = self.listView?.canGoToPreviousPage() {
  2975. view?.previousButton.isEnabled = can
  2976. } else {
  2977. view?.previousButton.isEnabled = false
  2978. }
  2979. if let can = self.listView?.canGoToNextPage() {
  2980. view?.nextButton.isEnabled = can
  2981. } else {
  2982. view?.nextButton.isEnabled = false
  2983. }
  2984. }
  2985. func updateBackAndForwardButtonState() {
  2986. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2987. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2988. if self.listView.km_canGoBack() {
  2989. item?.unEnabled = false
  2990. } else {
  2991. item?.unEnabled = true
  2992. }
  2993. if self.listView.km_canGoForward() {
  2994. toItem?.unEnabled = false
  2995. } else {
  2996. toItem?.unEnabled = true
  2997. }
  2998. }
  2999. func updateZoomInOutButtonState() {
  3000. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  3001. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  3002. if self.listView.canZoomIn {
  3003. item.unEnabled = false
  3004. } else {
  3005. item.unEnabled = true
  3006. }
  3007. if self.listView.canZoomOut {
  3008. toItem.unEnabled = false
  3009. } else {
  3010. toItem.unEnabled = true
  3011. }
  3012. }
  3013. }
  3014. // MARK: -
  3015. // MARK: - KMSecondaryViewControllerDelegate
  3016. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  3017. func receivedFileUrl(_ url: URL!) {
  3018. let state = self.displaySecondaryPDFView(withUrl: url)
  3019. if !state {
  3020. let alert = NSAlert()
  3021. alert.alertStyle = .critical
  3022. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3023. alert.runModal()
  3024. return
  3025. } else {
  3026. self.openSecondaryPdfView?.view.removeFromSuperview()
  3027. self.openSecondaryPdfView = nil
  3028. }
  3029. }
  3030. func controllerDidClose(_ controller: KMSecondaryViewController!) {
  3031. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  3032. }
  3033. }
  3034. // MARK: -
  3035. // MARK: - KMMainToolbarControllerDelegate
  3036. extension KMMainViewController : KMMainToolbarControllerDelegate {
  3037. func changeModelAction(mode: CToolMode) {
  3038. self.listView.toolMode = mode
  3039. if mode == .editPDFToolMode {
  3040. self.childToolbarController.updateType(newType: .editPDF)
  3041. }
  3042. }
  3043. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  3044. switch selectedTag {
  3045. case 2:
  3046. if self.listView.scaleFactor != 1.0 {
  3047. self.listView.scaleFactor = 1.0
  3048. self.listView.autoScales = false
  3049. }
  3050. break
  3051. case 1:
  3052. let pageHeight = self.listView.currentPage()!.size.height
  3053. let pdfviewHeight = self.listView.bounds.size.height
  3054. self.listView.scaleFactor = pdfviewHeight/pageHeight
  3055. self.listView.autoScales = false
  3056. break
  3057. case 0:
  3058. // self.listView.autoScales = !self.listView.autoScales
  3059. self.listView.autoScales = true
  3060. break
  3061. case 3:
  3062. self.listView.scaleFactor = 0.1
  3063. break
  3064. case 4:
  3065. self.listView.scaleFactor = 0.25
  3066. break
  3067. case 5:
  3068. self.listView.scaleFactor = 0.5
  3069. break
  3070. case 6:
  3071. self.listView.scaleFactor = 0.75
  3072. break
  3073. case 7:
  3074. self.listView.scaleFactor = 1.0
  3075. break
  3076. case 8:
  3077. self.listView.scaleFactor = 1.5
  3078. break
  3079. case 9:
  3080. self.listView.scaleFactor = 2.0
  3081. break
  3082. case 10:
  3083. self.listView.scaleFactor = 4.0
  3084. break
  3085. case 11:
  3086. self.listView.scaleFactor = 8.0
  3087. break
  3088. case 12:
  3089. self.listView.scaleFactor = 16.0
  3090. break
  3091. case 13:
  3092. self.listView.scaleFactor = 32.0
  3093. break
  3094. case 14:
  3095. self.listView.scaleFactor = 64.0
  3096. break
  3097. case 15:
  3098. self.listView.scaleFactor = 100.0
  3099. break
  3100. default:
  3101. break
  3102. }
  3103. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3104. }
  3105. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  3106. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3107. if scale > 100 {
  3108. scale = 100
  3109. }
  3110. if (scale <= 0.101) {
  3111. self.listView.scaleFactor = self.listView.minScaleFactor()
  3112. } else {
  3113. self.listView.scaleFactor = scale
  3114. }
  3115. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3116. DispatchQueue.main.async {
  3117. self.updateZoomInOutButtonState()
  3118. }
  3119. }
  3120. func changePDFViewZoomInAction() {
  3121. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3122. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3123. switch scale {
  3124. case 0...0.25:
  3125. scale += 0.25
  3126. case 0.25...3:
  3127. scale += 0.25
  3128. case 3.1...10:
  3129. scale += 0.4
  3130. case 10.1...100:
  3131. scale += 1
  3132. default:
  3133. scale += 1
  3134. }
  3135. self.listView.scaleFactor = scale
  3136. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  3137. // self.listView.zoomIn(nil)
  3138. }
  3139. func changePDFViewZoomOutAction() {
  3140. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3141. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3142. switch scale {
  3143. case 0...0.25:
  3144. scale = 0
  3145. case 0.25...3:
  3146. scale -= 0.25
  3147. case 3.1...10:
  3148. scale -= 0.4
  3149. case 10.1...100:
  3150. scale -= 1
  3151. default:
  3152. scale -= 1
  3153. }
  3154. self.listView.scaleFactor = scale
  3155. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  3156. // self.listView.zoomOut(nil)
  3157. // self.updateZoomInOutButtonState()
  3158. }
  3159. func changePDFViewGotoNextPageAction() {
  3160. self.listView.km_goBack(nil)
  3161. if (self.listView.canGoToNextPage()) {
  3162. self.listView.goToNextPage(nil)
  3163. }
  3164. self.updateNextAndPreViousButtonState()
  3165. }
  3166. func changePDFViewGoToPreviousPageAction() {
  3167. if (self.listView.canGoToPreviousPage()) {
  3168. self.listView.goToPreviousPage(nil)
  3169. }
  3170. self.updateNextAndPreViousButtonState()
  3171. }
  3172. func changePDFViewGotoBackAction() {
  3173. self.listView.km_goBack(nil)
  3174. self.updateBackAndForwardButtonState()
  3175. }
  3176. func changePDFViewGoToForwardAction() {
  3177. self.listView.km_goForward(nil)
  3178. self.updateBackAndForwardButtonState()
  3179. }
  3180. func aiTranslationPDFFileAction() {
  3181. #if VERSION_DMG
  3182. #else
  3183. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  3184. KMLoginWindowController.show(window: NSApp.mainWindow!)
  3185. return
  3186. }
  3187. #endif
  3188. self.trackEvent_aiTranslate()
  3189. self._aiTranslationPDFFileAction()
  3190. // Task { @MainActor in
  3191. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3192. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  3193. // if (isClose) {
  3194. // return
  3195. // }
  3196. // if (isSub) {
  3197. // self._aiTranslationPDFFileAction()
  3198. // return
  3199. // }
  3200. // }
  3201. // return
  3202. // }
  3203. //
  3204. // self._aiTranslationPDFFileAction()
  3205. // }
  3206. }
  3207. private func _aiTranslationPDFFileAction() {
  3208. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  3209. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  3210. let alert = NSAlert()
  3211. alert.alertStyle = .critical
  3212. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  3213. alert.runModal()
  3214. return
  3215. } else if isExceedsLimit {
  3216. let alert = NSAlert()
  3217. alert.alertStyle = .critical
  3218. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  3219. alert.runModal()
  3220. return
  3221. }
  3222. let alert = NSAlert()
  3223. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  3224. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  3225. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3226. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  3227. if (result == .alertFirstButtonReturn) {
  3228. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  3229. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  3230. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  3231. } else if result == .alertSecondButtonReturn {
  3232. return
  3233. }
  3234. }
  3235. }
  3236. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  3237. self.trackEvent_share()
  3238. }
  3239. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  3240. if (!self.saveWatermarkFlag) {
  3241. self.shareDocument(sender: viewController)
  3242. return
  3243. }
  3244. Task { @MainActor in
  3245. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3246. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  3247. if (isClose) {
  3248. return
  3249. }
  3250. if (isSubscribeSuccess) {
  3251. self.shareDocument(sender: viewController)
  3252. return
  3253. }
  3254. if (isWaterMarkExport) {
  3255. self.shareDocument(sender: viewController, limit: true)
  3256. return
  3257. }
  3258. }
  3259. return
  3260. }
  3261. self.shareDocument(sender: viewController)
  3262. }
  3263. }
  3264. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  3265. if IAPProductsManager.default().isAvailableAllFunction() == false {
  3266. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3267. return
  3268. }
  3269. self.shareFlatten(sender: viewController)
  3270. }
  3271. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  3272. if (!self.saveWatermarkFlag) {
  3273. self.shareOriginalPDF(sender: viewController)
  3274. return
  3275. }
  3276. Task { @MainActor in
  3277. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3278. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  3279. if (isClose) {
  3280. return
  3281. }
  3282. if (isSubscribeSuccess) {
  3283. self.shareOriginalPDF(sender: viewController)
  3284. return
  3285. }
  3286. if (isWaterMarkExport) {
  3287. self.shareOriginalPDF(sender: viewController, limit: true)
  3288. return
  3289. }
  3290. }
  3291. return
  3292. }
  3293. self.shareOriginalPDF(sender: viewController)
  3294. }
  3295. }
  3296. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  3297. if(0 == selectedTag) {
  3298. // self.documentAIViewController?.enteredIncreaseAllPage()
  3299. // self.documentAIViewController?.updateToolState(false)
  3300. } else {
  3301. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  3302. // self.documentAIViewController?.recognitionPartModel(with: .english)
  3303. // self.documentAIViewController?.updateToolState(true)
  3304. }
  3305. // 0 : Scan 1:OCR Text
  3306. }
  3307. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  3308. if beforeType == .editPDF {}
  3309. if(type != .Page) {
  3310. if (hasEnterPageEdit()) {
  3311. self.exitPageEdit()
  3312. }
  3313. }
  3314. if type != .redact {
  3315. if self.hasEnterRedact() {
  3316. self.exitRedact()
  3317. }
  3318. }
  3319. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  3320. if self.hasShowDigitalSign() {
  3321. self.exitDigitalSign()
  3322. }
  3323. }
  3324. if item.itemIdentifier != KMDocumentViewDisplayToolbarItemIdentifier {
  3325. self.toolbarController.findItem(KMDocumentViewDisplayToolbarItemIdentifier)?.isSelected = false
  3326. }
  3327. if(type != .Form) {
  3328. self.removeFromAlertView()
  3329. }
  3330. if (type == .Page) {
  3331. if (hasEnterPageEdit()) {
  3332. self.exitPageEdit()
  3333. } else {
  3334. self.enterPageEdit(pages)
  3335. }
  3336. } else if type == .editPDF {
  3337. self.enterEditPDF()
  3338. } else if type == .Annatiton {
  3339. self.rightSideViewController.subViewType = .AnnotationProperts
  3340. } else if type == .redact {
  3341. if self.needSaveDocument() {
  3342. self.saveDocumentWithProgressAlert { [unowned self] params in
  3343. self.enterRedact()
  3344. }
  3345. return
  3346. }
  3347. self.enterRedact()
  3348. } else if type == .Tool {
  3349. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  3350. } else if type == . Conversion {
  3351. self.loadOpenFileFunctionGuide(.convertGuide)
  3352. }else if type == .Form {
  3353. self.showFormAlertView()
  3354. }else if type == .Select {
  3355. self.rightSideViewController.isHidden = true
  3356. self.closeRightPane()
  3357. }
  3358. }
  3359. func clickChildTool(type: KMToolbarType, index: Int) {
  3360. if (type == .secure) {
  3361. if (index == 1) {
  3362. self.trackEvent_setPassword()
  3363. } else if (index == 2) {
  3364. self.trackEvent_removePassword()
  3365. }
  3366. } else {
  3367. self.trackEvent(toolBarType: type)
  3368. }
  3369. Task { @MainActor in
  3370. if (type == .compress) { /// 压缩
  3371. if !self.documentAllowsEdit() {
  3372. return
  3373. }
  3374. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3375. // self.view.window?.contentView?.superview?.beginLoading()
  3376. let document = self.listView.document
  3377. let secureOptions = self.secureOptions
  3378. let removeSecureFlag = self.removeSecureFlag
  3379. // DispatchQueue.global().async { [unowned self] in
  3380. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  3381. // DispatchQueue.main.async {
  3382. // self.view.window?.contentView?.superview?.endLoading()
  3383. // }
  3384. return
  3385. }
  3386. // DispatchQueue.main.async {
  3387. // self.view.window?.contentView?.superview?.endLoading()
  3388. self.showCompressWindow(url: _url)
  3389. // }
  3390. // }
  3391. return
  3392. }
  3393. if (self.needSaveDocument()) {
  3394. self.saveDocumentWithProgressAlert { [unowned self] params in
  3395. self.showCompressWindow()
  3396. }
  3397. return
  3398. }
  3399. self.showCompressWindow()
  3400. return
  3401. }
  3402. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  3403. var identifier: String?
  3404. if (type == .word) { /// Word
  3405. identifier = KMToolbarConversionWordItemIdentifier
  3406. } else if (type == .excel) {
  3407. identifier = KMToolbarConversionExcelItemIdentifier
  3408. } else if (type == .ppt) {
  3409. identifier = KMToolbarConversionPPTItemIdentifier
  3410. } else if (type == .rtf) {
  3411. identifier = KMToolbarConversionRTFItemIdentifier
  3412. } else if (type == .html) {
  3413. identifier = KMToolbarConversionHTMLItemIdentifier
  3414. } else if (type == .conversion_text) {
  3415. identifier = KMToolbarConversionTextItemIdentifier
  3416. } else if (type == .csv) {
  3417. identifier = KMToolbarConversionCSVItemIdentifier
  3418. } else if (type == .conversion_image) {
  3419. identifier = KMToolbarConversionImageItemIdentifier
  3420. }
  3421. if (self.needSaveDocument()) {
  3422. self.saveDocumentWithProgressAlert { [unowned self] params in
  3423. self.showConvertWindow(type: type, identifier: identifier)
  3424. }
  3425. return
  3426. }
  3427. self.showConvertWindow(type: type, identifier: identifier)
  3428. return
  3429. }
  3430. if (type == .merge) { /// 合并
  3431. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  3432. if !self.documentAllowsEdit() {
  3433. return
  3434. }
  3435. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3436. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  3437. return
  3438. }
  3439. self.showMergeWindow(url: _url, self.model.password)
  3440. return
  3441. }
  3442. if (self.needSaveDocument()) {
  3443. self.saveDocumentWithProgressAlert { [unowned self] params in
  3444. self.showMergeWindow(self.listView.document.password)
  3445. }
  3446. return
  3447. }
  3448. self.showMergeWindow(self.listView.document.password)
  3449. return
  3450. }
  3451. if (type == .bates || type == .headerAndFooter) {
  3452. if !IAPProductsManager.default().isAvailableAllFunction(){
  3453. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3454. return
  3455. }
  3456. if !self.documentAllowsEdit() {
  3457. return
  3458. }
  3459. if (index == 1) {
  3460. var windowController: KMBaseWindowController = KMBaseWindowController()
  3461. if (type == .bates) {
  3462. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3463. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3464. let fpath = self.document?.documentURL?.path ?? ""
  3465. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3466. }
  3467. windowController.isBates = true
  3468. } else if (type == .headerAndFooter) {
  3469. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3470. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3471. let fpath = self.document?.documentURL?.path ?? ""
  3472. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3473. }
  3474. } else if (type == .background) {
  3475. } else if (type == .watermark) {
  3476. // controller = KMWatermarkViewController()
  3477. }
  3478. windowController.pdfDocument = self.listView.document
  3479. windowController.cancelAction = { [unowned self] controller in
  3480. self.view.window?.endSheet((self.currentWindowController.window)!)
  3481. self.currentWindowController = nil
  3482. }
  3483. self.currentWindowController = windowController
  3484. await self.view.window?.beginSheet(windowController.window!)
  3485. return
  3486. }
  3487. if (index == 1) { /// 取消
  3488. self.toolbarController.exitWatermarkAdjective()
  3489. // self.rightSideViewController.view.isHidden = true
  3490. self.rightSideViewController.isHidden = true
  3491. self.rightSideViewController.subViewType = .None
  3492. self.closeRightPane()
  3493. return
  3494. } else if index == 3 {
  3495. let fpath = self.document?.documentURL?.path ?? ""
  3496. if type == .bates {
  3497. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3498. } else {
  3499. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3500. }
  3501. } else if index == 4 {
  3502. let fpath = self.document?.documentURL?.path ?? ""
  3503. if type == .bates {
  3504. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  3505. } else {
  3506. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  3507. }
  3508. } else if (index == 2) { //// 移除
  3509. if type == .headerAndFooter {
  3510. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3511. let savePanel = NSSavePanel()
  3512. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3513. savePanel.allowedFileTypes = ["pdf"]
  3514. savePanel.accessoryView = savePanelAccessoryViewController.view
  3515. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3516. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3517. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3518. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3519. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3520. }
  3521. } else {
  3522. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3523. }
  3524. }
  3525. }
  3526. }
  3527. } else if type == .bates {
  3528. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3529. let savePanel = NSSavePanel()
  3530. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3531. savePanel.allowedFileTypes = ["pdf"]
  3532. savePanel.accessoryView = savePanelAccessoryViewController.view
  3533. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3534. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3535. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3536. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3537. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3538. }
  3539. } else {
  3540. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3541. }
  3542. }
  3543. }
  3544. }
  3545. }
  3546. return
  3547. } else if (index == 2) { /// 应用
  3548. let model = self.rightSideViewController.model
  3549. if (type == .bates || type == .headerAndFooter) {
  3550. if (model == nil || (model?.isKind(of: KMHeaderFooterObject.self) == false)) {
  3551. let alert = NSAlert()
  3552. alert.alertStyle = .critical
  3553. alert.messageText = "没有找到模型"
  3554. alert.runModal()
  3555. return
  3556. }
  3557. if ((model as! KMHeaderFooterObject).hasVaild == false) {
  3558. let alert = NSAlert()
  3559. alert.alertStyle = .critical
  3560. alert.messageText = "没有找到内容"
  3561. alert.runModal()
  3562. return
  3563. }
  3564. }
  3565. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  3566. result in
  3567. DispatchQueue.main.async {
  3568. self.listView.layoutDocumentView()
  3569. self.listView.setNeedsDisplayForVisiblePages()
  3570. }
  3571. if (result) {
  3572. let alert = NSAlert()
  3573. alert.alertStyle = .warning
  3574. alert.messageText = "成功"
  3575. alert.runModal()
  3576. } else {
  3577. let alert = NSAlert()
  3578. alert.alertStyle = .critical
  3579. alert.messageText = "失败"
  3580. alert.runModal()
  3581. }
  3582. }
  3583. return
  3584. } else if index == 5 {
  3585. self.rightSideViewController.isHidden = false
  3586. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3587. self.openRightPane()
  3588. }
  3589. } else if (type == .redact) { /// 标记密文
  3590. if !IAPProductsManager.default().isAvailableAllFunction(){
  3591. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3592. return
  3593. }
  3594. if (index == 1) { /// 取消
  3595. if (self.model.hasAddRedact) {
  3596. let alert = NSAlert()
  3597. alert.messageText = NSLocalizedString("You can save a document with unapplied cipher text and edit it again. If you do not save, all changes will be lost.", comment: "")
  3598. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  3599. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3600. let result = alert.runModal()
  3601. if (result == .alertFirstButtonReturn) {
  3602. self.listView.toolMode = .moveToolMode
  3603. self.toolbarController.exitRedact()
  3604. }
  3605. return
  3606. }
  3607. self.listView.toolMode = .moveToolMode
  3608. self.toolbarController.exitRedact()
  3609. return
  3610. }
  3611. if (index == 2) { /// 擦除
  3612. self.exeRedactConfirm(.eraserAll) {}
  3613. return
  3614. }
  3615. if (index == 3) { /// 应用
  3616. self.exeRedactConfirm(.redactAll) {}
  3617. return
  3618. }
  3619. if (index == 4) { /// 文本&图像
  3620. self.listView.toolMode = .redactToolMode
  3621. return
  3622. }
  3623. if (index == 5) { /// 页面
  3624. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3625. await self.view.window?.beginSheet(windowController.window!)
  3626. self.currentWindowController = windowController
  3627. windowController.itemClick = { [weak self] index, value in
  3628. if (index == 1) {
  3629. let topBarView = self?.toolbarController.fetchTopBarView()
  3630. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  3631. return
  3632. }
  3633. (topBarView as! KMRedactTopToolBar).selectItem(0)
  3634. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3635. self?.currentWindowController = nil
  3636. return
  3637. }
  3638. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3639. let pageType = windowController_pageRange.pageType
  3640. let pageString = windowController_pageRange.pageString
  3641. if (pageType == 5) { /// 自定义页面
  3642. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  3643. if (array.count == 0) {
  3644. let alert = NSAlert()
  3645. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3646. alert.runModal()
  3647. return
  3648. }
  3649. }
  3650. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3651. self!.currentWindowController = nil
  3652. var indexs: IndexSet = []
  3653. if (pageType == 1) { /// 当前页面
  3654. indexs.insert((self?.listView.currentPageIndex)!)
  3655. } else {
  3656. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  3657. }
  3658. if (indexs.count == 0) {
  3659. return
  3660. }
  3661. for i in indexs {
  3662. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3663. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3664. redactAnno.bounds = page.bounds
  3665. self?.listView.add(redactAnno, to: page)
  3666. }
  3667. }
  3668. return
  3669. }
  3670. } else if (type == .secure) { /// 安全
  3671. if (index == 1) { /// 设置密码
  3672. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3673. if !self.documentAllowsEdit() {
  3674. return
  3675. }
  3676. // KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  3677. // if (result == .cancel) {
  3678. // return
  3679. // }
  3680. //
  3681. // self?.isSaveKeyChain = false
  3682. // self?.listView.document.unlock(withPassword: password)
  3683. // self?.hiddenSecureLimitTip()
  3684. //
  3685. // self?.showSecureWindow((self?.listView.document.documentURL)!)
  3686. // }
  3687. // return
  3688. }
  3689. self.showSecureWindow(self.listView.document.documentURL)
  3690. return
  3691. } else if index == 2 {
  3692. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3693. let alert = NSAlert()
  3694. alert.alertStyle = .warning
  3695. alert.messageText = NSLocalizedString("Warning", comment: "")
  3696. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3697. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3698. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3699. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3700. if returnCode == .alertSecondButtonReturn {
  3701. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3702. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3703. if success {
  3704. self.document?.unlock(withPassword: resultPassword)
  3705. self.clickChildTool(type: .secure, index: 2)
  3706. }
  3707. }
  3708. }
  3709. }
  3710. }
  3711. } else {
  3712. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3713. controller.pdfDocument = self.document
  3714. self.currentWindowController = controller
  3715. controller.batchAction = { [unowned self] controller, files in
  3716. self.view.window?.endSheet((self.currentWindowController.window)!)
  3717. self.currentWindowController = nil
  3718. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3719. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  3720. if #available(macOS 10.13, *) {
  3721. baseWindowController.window?.makeKeyAndOrderFront(nil)
  3722. } else {
  3723. baseWindowController.showWindow(nil)
  3724. }
  3725. let arr = NSMutableArray()
  3726. let file = KMBatchOperateFile(filePath: self.listView!.document!.documentURL!.path, type: .RemovePassword)
  3727. file.password = document?.password ?? ""
  3728. arr.add(file)
  3729. // baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .RemovePassword, files: arr as! [KMBatchOperateFile])
  3730. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  3731. }
  3732. controller.cancelAction = { [unowned self] controller in
  3733. self.view.window?.endSheet((self.currentWindowController.window)!)
  3734. self.currentWindowController = nil
  3735. }
  3736. controller.doneAction = { [unowned self] controller in
  3737. self.view.window?.endSheet((self.currentWindowController.window)!)
  3738. self.currentWindowController = nil
  3739. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  3740. if success {
  3741. // let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3742. let savePanel = NSSavePanel()
  3743. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  3744. savePanel.allowedFileTypes = ["pdf"]
  3745. // savePanel.accessoryView = savePanelAccessoryViewController.view
  3746. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  3747. guard result == .OK else { return }
  3748. /// 删除安全性设置
  3749. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3750. self.model.isSaveKeyChain = false
  3751. self.listView.document.unlock(withPassword: resultPassword)
  3752. }
  3753. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  3754. guard let document = document else { return }
  3755. document.unlock(withPassword: resultPassword)
  3756. let success = document.writeDecrypt(to: savePanel.url)
  3757. if success {
  3758. self.hiddenSecureLimitTip()
  3759. let tip = KMRemovePasswordResultTipView()
  3760. tip.result = .success
  3761. tip.showInView(superView: (self.listView.superview)!)
  3762. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3763. } else {
  3764. self.hiddenSecureLimitTip()
  3765. let tip = KMRemovePasswordResultTipView()
  3766. tip.result = .failure
  3767. tip.showInView(superView: (self.listView.superview)!)
  3768. }
  3769. }
  3770. }
  3771. }
  3772. }
  3773. await NSWindow.currentWindow().beginSheet(controller.window!)
  3774. }
  3775. return
  3776. }
  3777. } else if type == .comparison {
  3778. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  3779. if !IAPProductsManager.default().isAvailableAllFunction(){
  3780. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3781. return
  3782. }
  3783. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3784. self.currentWindowController = controller
  3785. controller.password = self.document?.password ?? ""
  3786. controller.filePath = (self.document?.documentURL.path)!
  3787. controller.cancelAction = { [unowned self] controller in
  3788. self.view.window?.endSheet((self.currentWindowController.window)!)
  3789. self.currentWindowController = nil
  3790. }
  3791. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3792. self.view.window?.endSheet((self.currentWindowController.window)!)
  3793. self.currentWindowController = nil
  3794. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3795. }
  3796. controller.coveringComplete = { [unowned self] controller, document in
  3797. self.view.window?.endSheet((self.currentWindowController.window)!)
  3798. self.currentWindowController = nil
  3799. self.openCoveringCompareVC(with: document)
  3800. }
  3801. if index == 1 {
  3802. controller.fileType = .content
  3803. } else {
  3804. controller.fileType = .coverting
  3805. }
  3806. await NSWindow.currentWindow().beginSheet(controller.window!)
  3807. } else if type == .watermark {
  3808. if !IAPProductsManager.default().isAvailableAllFunction(){
  3809. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3810. return
  3811. }
  3812. if !self.documentAllowsEdit() {
  3813. return
  3814. }
  3815. if index == 1 {
  3816. let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  3817. self.currentWindowController = controller
  3818. controller.pdfDocument = self.document
  3819. controller.cancelAction = { [unowned self] controller in
  3820. self.view.window?.endSheet((self.currentWindowController.window)!)
  3821. self.currentWindowController = nil
  3822. }
  3823. controller.operateCallBack = { [unowned self] controller, watermark, countType in
  3824. self.view.window?.endSheet((self.currentWindowController.window)!)
  3825. self.currentWindowController = nil
  3826. let fpath = self.document?.documentURL?.path ?? ""
  3827. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  3828. }
  3829. // NSWindow.currentWindow().beginSheet(controller.window!)
  3830. NSWindow.currentWindow().beginSheet(controller.window!, completionHandler: nil)
  3831. } else if index == 2 {
  3832. let watermarks = self.listView.document.watermarks()
  3833. if (watermarks == nil || watermarks!.count <= 0) {
  3834. let alert = NSAlert()
  3835. alert.alertStyle = .warning
  3836. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Reader Pro添加的,因此无法被检测到。", comment: "")
  3837. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  3838. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3839. alert.runModal()
  3840. return
  3841. }
  3842. let alert = NSAlert()
  3843. alert.alertStyle = .warning
  3844. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  3845. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  3846. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3847. let result = alert.runModal()
  3848. if (result != .alertFirstButtonReturn) {
  3849. return
  3850. }
  3851. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3852. let savePanel = NSSavePanel()
  3853. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  3854. savePanel.allowedFileTypes = ["pdf"]
  3855. savePanel.accessoryView = savePanelAccessoryViewController.view
  3856. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3857. guard result == .OK else { return }
  3858. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  3859. KMWatermarkAdjectiveTools.delete(oType, self.listView, savePanel.url!.path) {
  3860. result in
  3861. DispatchQueue.main.async {
  3862. self.listView.layoutDocumentView()
  3863. self.listView.setNeedsDisplayForVisiblePages()
  3864. }
  3865. if (result) {
  3866. let alert = NSAlert()
  3867. alert.alertStyle = .warning
  3868. alert.messageText = "成功"
  3869. alert.runModal()
  3870. } else {
  3871. let alert = NSAlert()
  3872. alert.alertStyle = .critical
  3873. alert.messageText = "失败"
  3874. alert.runModal()
  3875. }
  3876. }
  3877. }
  3878. } else if index == 3 {
  3879. let fpath = self.document?.documentURL?.path ?? ""
  3880. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  3881. } else if index == 4 {
  3882. let fpath = self.document?.documentURL?.path ?? ""
  3883. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  3884. } else if index == 5 {
  3885. self.rightSideViewController.isHidden = false
  3886. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3887. self.openRightPane()
  3888. return
  3889. }
  3890. } else if type == .background {
  3891. if !IAPProductsManager.default().isAvailableAllFunction(){
  3892. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3893. return
  3894. }
  3895. if !self.documentAllowsEdit() {
  3896. return
  3897. }
  3898. if index == 1 {
  3899. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  3900. self.currentWindowController = controller
  3901. controller.pdfDocument = self.document
  3902. controller.cancelAction = { [unowned self] controller in
  3903. self.view.window?.endSheet((self.currentWindowController.window)!)
  3904. self.currentWindowController = nil
  3905. }
  3906. controller.operateCallBack = { [unowned self] controller, background, countType in
  3907. let fpath = self.document?.documentURL?.path ?? ""
  3908. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  3909. }
  3910. await NSWindow.currentWindow().beginSheet(controller.window!)
  3911. } else if index == 2 {
  3912. guard let document = self.document else { return }
  3913. if !document.allowsPrinting || !document.allowsCopying {
  3914. let alert = NSAlert()
  3915. alert.alertStyle = .critical
  3916. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3917. alert.runModal()
  3918. return
  3919. }
  3920. guard let documentURL = document.documentURL else { return }
  3921. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3922. let savePanel = NSSavePanel()
  3923. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  3924. savePanel.allowedFileTypes = ["pdf"]
  3925. savePanel.accessoryView = savePanelAccessoryViewController.view
  3926. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3927. guard result == .OK else { return }
  3928. KMAddBackgroundView.saveAsPDFRemoveAllBackground(PDFDocument: document, password: document.password, toPath: savePanel.url!.path, completionHandler: { [unowned self] success in
  3929. if success == 1 {
  3930. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3931. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { _, _, _ in }
  3932. } else {
  3933. NSWorkspace.shared.selectFile(savePanel.url!.path, inFileViewerRootedAtPath: "")
  3934. }
  3935. }
  3936. })
  3937. }
  3938. } else if index == 3 {
  3939. let fpath = self.document?.documentURL?.path ?? ""
  3940. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  3941. } else if index == 4 {
  3942. let fpath = self.document?.documentURL?.path ?? ""
  3943. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  3944. } else if index == 5 {
  3945. self.rightSideViewController.isHidden = false
  3946. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3947. self.openRightPane()
  3948. return
  3949. }
  3950. }
  3951. }
  3952. }
  3953. // func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  3954. // let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3955. //// batchWindowController.window?.makeKeyAndOrderFront("")
  3956. //
  3957. // var array: [KMBatchOperateFile] = []
  3958. // for file in files ?? [] {
  3959. // let batchOperateFile = KMBatchOperateFile(filePath: file.filePath, type: type)
  3960. // array.append(batchOperateFile)
  3961. // }
  3962. // batchWindowController.switchToOperateType(type, files: array)
  3963. // batchWindowController.window?.makeKeyAndOrderFront("")
  3964. // }
  3965. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  3966. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3967. var array: [KMBatchOperateFile] = []
  3968. for fpath in filepaths ?? [] {
  3969. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  3970. array.append(batchOperateFile)
  3971. }
  3972. batchWindowController.switchToOperateType(type, files: array)
  3973. batchWindowController.window?.makeKeyAndOrderFront("")
  3974. }
  3975. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  3976. self.toolbarItemClickForExitMode(toolbarItem)
  3977. if let itemID = toolbarItem.itemIdentifier {
  3978. if isMainToolItem(itemID) {
  3979. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  3980. openNewWindowAlertWindow()
  3981. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  3982. self.changePDFViewGoToPreviousPageAction()
  3983. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  3984. self.changePDFViewGotoNextPageAction()
  3985. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3986. let isSelected = toolbarItem.isSelected
  3987. self.toolbarController.toolbarType = isSelected ? .None : .viewSetting
  3988. toolbarItem.isSelected = !isSelected
  3989. if toolbarItem.isSelected {
  3990. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  3991. self.rightSideViewController.isHidden = false
  3992. self.rightSideViewController.mainController = self
  3993. self.rightSideViewController.subViewType = .ViewSettings
  3994. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  3995. self.openRightPane()
  3996. }else{
  3997. self.rightSideViewController.isHidden = true
  3998. self.rightSideViewController.subViewType = .AnnotationProperts
  3999. closeRightPane()
  4000. }
  4001. if toolbarItem.isSelected {
  4002. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  4003. }
  4004. let rightItem = self.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  4005. if isSelected {
  4006. rightItem?.isSelected = false
  4007. } else {
  4008. rightItem?.isSelected = true
  4009. }
  4010. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  4011. toolbarItem.isSelected = !toolbarItem.isSelected
  4012. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  4013. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4014. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  4015. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  4016. }
  4017. toolbarItem.isSelected = !toolbarItem.isSelected
  4018. self.toggleRightPane()
  4019. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  4020. self.listView.toolMode = .redactToolMode
  4021. self.enterRedact()
  4022. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  4023. showOCRWindow()
  4024. } else if itemID == KMDocumentAIToolsToolbarItemIdentifier {
  4025. self.showAITypeChooseView(aiConfigType: .none)
  4026. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  4027. if self.canEnterDigitalSign() == false {
  4028. Task {
  4029. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4030. }
  4031. return
  4032. }
  4033. toolbarItem.isSelected = !toolbarItem.isSelected
  4034. self.toolbarController.lastItemBox = toolbarItem
  4035. if toolbarItem.isSelected {
  4036. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4037. }
  4038. self.enterDigitalSign()
  4039. }
  4040. } else {
  4041. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  4042. let windowC = KMToolbarCustomWindowController()
  4043. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  4044. self.km_beginSheet(windowC: windowC)
  4045. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  4046. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  4047. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  4048. self.trackEvent_print()
  4049. self.showPrintWindow()
  4050. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  4051. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  4052. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  4053. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  4054. windowC.callBack = { [weak self] string in
  4055. if (string.isEmpty == false) {
  4056. self?.listView.addTextField(subType: .profile, string: string)
  4057. }
  4058. self?.km_endSheet()
  4059. }
  4060. self.km_beginSheet(windowC: windowC)
  4061. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  4062. toolbarItem.isSelected = !toolbarItem.isSelected
  4063. rightSideViewController.mainController = self
  4064. self.rightSideViewController.isHidden = toolbarItem.isSelected ? false : true
  4065. self.rightSideViewController.subViewType = .ViewSettings
  4066. // self.toggleRightPane()
  4067. self.listView.annotationType = .unkown
  4068. if toolbarItem.isSelected {
  4069. self.rightSideViewController.isHidden = false
  4070. self.rightSideViewController.mainController = self
  4071. self.rightSideViewController.subViewType = .ViewSettings
  4072. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  4073. self.openRightPane()
  4074. }else{
  4075. self.rightSideViewController.isHidden = true
  4076. self.rightSideViewController.subViewType = .AnnotationProperts
  4077. closeRightPane()
  4078. }
  4079. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  4080. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  4081. self.listView.takeSnapshot(nil)
  4082. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  4083. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  4084. self.listView.annotationType = .unkown
  4085. self.showTTSWindow()
  4086. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4087. self.showOCRWindow()
  4088. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  4089. toolbarItem.isSelected = false
  4090. self.imageAnnotation(toolbarItem)
  4091. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  4092. self.tableAnnotation(toolbarItem)
  4093. } else if toolbarItem.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { // 插入
  4094. self.leftSideViewController.insertPDF(nil)
  4095. } else if toolbarItem.itemIdentifier == KMToolbarPageEditSplitItemIdentifier { // 拆分
  4096. let windowC = SplitWindowController(document: self.listView.document)
  4097. self.km_beginSheet(windowC: windowC)
  4098. }
  4099. }
  4100. }
  4101. }
  4102. func openNewWindowAlertWindow() {
  4103. var needShowChooseWindow = false
  4104. //#if VERSION_FREE
  4105. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  4106. needShowChooseWindow = true
  4107. }
  4108. //#endif
  4109. if needShowChooseWindow {
  4110. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  4111. if preferenceNoteShow {
  4112. menuItemAction_newTagPageToNewWindow("")
  4113. } else {
  4114. if !KMDataManager.default.isTabbingWin{
  4115. KMDataManager.default.isTabbingWin = true
  4116. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  4117. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  4118. KMDataManager.default.isTabbingWin = false
  4119. if continueOrNot {
  4120. self?.reopenDocument(forPaths: [])
  4121. } else {
  4122. }
  4123. }
  4124. self.km_beginSheet(windowC: tabbingWin)
  4125. }
  4126. }
  4127. }else{
  4128. handleTabbingLogic()
  4129. }
  4130. }
  4131. func reopenDocument(forPaths paths: [String]) -> Void {
  4132. let browser = KMBrowser.init() as KMBrowser
  4133. browser.windowController = KMBrowserWindowController.init(browser: browser)
  4134. browser.addHomeTabContents()
  4135. browser.windowController.showWindow(self)
  4136. }
  4137. func handleTabbingLogic() {
  4138. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  4139. self.toolbarController.findItem(KMDocumentHomeToolbarItemIdentifier)?.isSelected = false
  4140. }
  4141. func showTTSWindow() {
  4142. var lastPDFView: CPDFView?
  4143. let ttsView = KMTTSWindowController.share
  4144. if (ttsView.window?.isVisible ?? false) {
  4145. lastPDFView = ttsView.pdfView
  4146. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  4147. lastPDFView = nil
  4148. ttsView.window?.orderOut(nil)
  4149. } else {
  4150. ttsView.pdfView = self.listView
  4151. ttsView.showWindow(nil)
  4152. }
  4153. } else {
  4154. ttsView.pdfView = self.listView
  4155. ttsView.showWindow(nil)
  4156. }
  4157. // weak var blockSelf = self
  4158. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  4159. if isCloseWindow {
  4160. // for item in blockSelf?.toolbar.items ?? [] {
  4161. // if item.itemIdentifier == KMToolbarTTSViewItemIdentifier {
  4162. // item.isSelected = false
  4163. // }
  4164. // }
  4165. }
  4166. }
  4167. if let currentSelection = self.listView.currentSelection {
  4168. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  4169. ttsView.startSpeakingPDFSelection(currentSelection)
  4170. }
  4171. }
  4172. if let lastPDFView = lastPDFView {
  4173. lastPDFView.setHighlightedSelections([])
  4174. ttsView.stopSpeaking()
  4175. }
  4176. }
  4177. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4178. self.toolbarItemClickForExitMode(toolbarItem)
  4179. let itemId = toolbarItem.itemIdentifier
  4180. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  4181. self.clickChildTool(type: .watermark, index: index)
  4182. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  4183. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  4184. self.clickChildTool(type: .background, index: index)
  4185. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  4186. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  4187. self.clickChildTool(type: .headerAndFooter, index: index)
  4188. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  4189. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  4190. self.clickChildTool(type: .bates, index: index)
  4191. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  4192. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  4193. self.clickChildTool(type: .comparison, index: index)
  4194. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  4195. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  4196. convertToImg(index: index)
  4197. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  4198. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  4199. extractImageAction(num: index)
  4200. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  4201. self.createPdf(index: index)
  4202. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  4203. if index == 2 { // 裁剪当前页面
  4204. self.cropCurrentPage()
  4205. } else if index == 3 { // Auto Crop – Separate
  4206. self.smart_cropAllPage()
  4207. } else if index == 4 { // Auto Crop – Combined
  4208. self.auto_cropAllPage()
  4209. } else if index == 5 { // Select Area
  4210. self.toolbarController.clickItem(KMToolbarSelectToolModeItemIdentifier)
  4211. }
  4212. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Crop"])
  4213. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  4214. self.clickChildTool(type: .secure, index: index)
  4215. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  4216. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  4217. self.toolbarController.showFindBar()
  4218. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4219. toolbarItem.isSelected = !toolbarItem.isSelected
  4220. self.toggleRightPane()
  4221. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4222. self.toolbarController.toolbarType = .viewSetting
  4223. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4224. self.showOCRWindow()
  4225. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  4226. if index == 1 {
  4227. self.showAITypeChooseView(aiConfigType: .summarize)
  4228. } else if index == 2 {
  4229. self.showAITypeChooseView(aiConfigType: .reWriting)
  4230. } else if index == 3 {
  4231. self.showAITypeChooseView(aiConfigType: .proofreading)
  4232. } else if index == 4 {
  4233. self.showAITypeChooseView(aiConfigType: .translate)
  4234. }
  4235. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  4236. self.showOCRWindow()
  4237. } else if toolbarItem.itemIdentifier == KMDocumentEditToolbarItemIdentifier {
  4238. self.toolbarController.toolbarType = .editPDF
  4239. self.enterEditPDF()
  4240. } else if toolbarItem.itemIdentifier == KMDocumentFillSginToolbarItemIdentifier {
  4241. self.toolbarController.toolbarType = .FillSign
  4242. } else if toolbarItem.itemIdentifier == KMDocumentFormToolbarItemIdentifier {
  4243. self.toolbarController.toolbarType = .Form
  4244. } else if itemId == KMDocumentDigitalSignToolbarItemIdentifier {
  4245. if self.canEnterDigitalSign() == false {
  4246. Task {
  4247. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4248. }
  4249. return
  4250. }
  4251. toolbarItem.isSelected = !toolbarItem.isSelected
  4252. self.toolbarController.lastItemBox = toolbarItem
  4253. if toolbarItem.isSelected {
  4254. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4255. }
  4256. self.enterDigitalSign()
  4257. }
  4258. }
  4259. func convertToImg(index: Int) {
  4260. var convertT: KMConvertType = .JPEG
  4261. switch index {
  4262. case 7:
  4263. convertT = .JPEG
  4264. case 8:
  4265. convertT = .JPG
  4266. case 9:
  4267. convertT = .PNG
  4268. case 10:
  4269. convertT = .GIF
  4270. case 11:
  4271. convertT = .TIFF
  4272. case 12:
  4273. convertT = .TGA
  4274. case 13:
  4275. convertT = .BMP
  4276. default:
  4277. convertT = .JPEG
  4278. }
  4279. showAllConvertWindow(convertT: convertT)
  4280. }
  4281. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  4282. // if self.searchResults.count == 0 {
  4283. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4284. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4285. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  4286. // }
  4287. var row = max(searchIndex - 1, 0)
  4288. if forward {
  4289. row = searchIndex + 1
  4290. }
  4291. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4292. let model = self.searchResults[row]
  4293. if model.selection != nil {
  4294. self.listView.setHighlightedSelections([])
  4295. self.listView.go(to: model.selection, animated: true)
  4296. self.listView.setHighlightedSelection(model.selection, animated: true)
  4297. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4298. searchIndex = row
  4299. }
  4300. }
  4301. self.leftSideViewController.showSearchMode(searchString)
  4302. }
  4303. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAction searchString: String, forward: Bool) {
  4304. // if self.searchResults.count == 0 {
  4305. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4306. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4307. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  4308. // }
  4309. var row = max(searchIndex - 1, 0)
  4310. if forward {
  4311. row = searchIndex + 1
  4312. }
  4313. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4314. let model = self.searchResults[row]
  4315. if model.selection != nil {
  4316. self.listView.setHighlightedSelections([])
  4317. self.listView.go(to: model.selection, animated: true)
  4318. self.listView.setHighlightedSelection(model.selection, animated: true)
  4319. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4320. searchIndex = row
  4321. }
  4322. }
  4323. }
  4324. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAllAction searchString: String, forward: Bool) {
  4325. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4326. self.search(searchString: searchString, isCase: !caseInsensitive, display: false, needShowAll: true)
  4327. self.leftSideViewController.showSearchMode(searchString)
  4328. }
  4329. }
  4330. // MARK: -
  4331. // MARK: - Mouse
  4332. extension KMMainViewController {
  4333. override func mouseDown(with event: NSEvent) {
  4334. super.mouseDown(with: event)
  4335. // KMPrint("KMMainViewController mouseDown")
  4336. self.leftSideViewCancelSelect()
  4337. self.pageNumberDisplayView.isEdit = false
  4338. }
  4339. }
  4340. //MARK: LeftSideViewController
  4341. extension KMMainViewController {
  4342. func leftSideViewCancelSelect() {
  4343. // switch self.leftSideViewController.type.methodType {
  4344. // case .Thumbnail:
  4345. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  4346. // break
  4347. // case .Outline:
  4348. //// self.leftSideViewController.outlineViewController.cancelSelect()
  4349. // break
  4350. // case .BookMark:
  4351. //// self.leftSideViewController.bookViewController.cancelSelect()
  4352. // break
  4353. // case .Search:
  4354. //// self.leftSideViewController.searchViewController.cancelSelect()
  4355. // break
  4356. // case .Annotation:
  4357. //// self.leftSideViewController.annotationViewController.cancelSelect()
  4358. // break
  4359. // default:
  4360. if self.listView.isEditing() {
  4361. if self.listView.editingAreas() != nil &&
  4362. self.listView.editingAreas().count != 0 {
  4363. let areas = self.listView.editingAreas().first
  4364. if areas is CPDFEditTextArea {
  4365. self.listView.clearEditingSelectCharItem()
  4366. self.listView.updateEditing([])
  4367. KMPrint("取消选中")
  4368. }
  4369. }
  4370. }
  4371. // KMPrint("其他")
  4372. // }
  4373. }
  4374. }
  4375. extension KMMainViewController: KMReadModelViewDelegate {
  4376. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4377. self.listView.goToFirstPage(nil)
  4378. }
  4379. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  4380. self.listView.goToPreviousPage(nil)
  4381. }
  4382. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4383. self.listView.goToNextPage(nil)
  4384. }
  4385. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4386. self.listView.goToLastPage(nil)
  4387. }
  4388. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  4389. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  4390. }
  4391. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  4392. var scale: Double = 1.0
  4393. switch type {
  4394. case .fitWidth:
  4395. self.listView.autoScales = !self.listView.autoScales
  4396. scale = self.listView.scaleFactor
  4397. break
  4398. case .actualSize:
  4399. if self.listView.scaleFactor != 1.0 {
  4400. self.listView.scaleFactor = 1.0
  4401. self.listView.autoScales = false
  4402. }
  4403. scale = self.listView.scaleFactor
  4404. break
  4405. case .autoSize:
  4406. self.listView.autoScales = true
  4407. self.listView.autoScales = false
  4408. scale = self.listView.scaleFactor
  4409. break
  4410. case ._10:
  4411. scale = 0.1
  4412. break
  4413. case ._25:
  4414. scale = 0.25
  4415. break
  4416. case ._50:
  4417. scale = 0.5
  4418. break
  4419. case ._100:
  4420. scale = 1.0
  4421. break
  4422. case ._150:
  4423. scale = 1.5
  4424. break
  4425. case ._200:
  4426. scale = 2.0
  4427. break
  4428. case ._400:
  4429. scale = 4.0
  4430. break
  4431. case ._800:
  4432. scale = 8.0
  4433. break
  4434. default:
  4435. break
  4436. }
  4437. self.listView.scaleFactor = scale
  4438. self.toolbarController.mainViewController?.childToolbarController.zoomTextField?.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  4439. }
  4440. func cancelReadModel(view: KMReadModelView, sender: Any) {
  4441. if self.isReadMode {
  4442. self.closeReadModel()
  4443. }
  4444. }
  4445. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  4446. // if self.readModelViewWidthConstraint.constant != width {
  4447. self.readModelViewWidthConstraint.constant = width
  4448. // }
  4449. }
  4450. }
  4451. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  4452. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  4453. self.listView.go(toPageIndex: pageIndex, animated: true)
  4454. }
  4455. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  4456. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  4457. self.tipCurrentPageBoxWidthConstraint.constant = width
  4458. }
  4459. }
  4460. func commitEditingIfNeed() {
  4461. let isEdited = self.listView?.isEdited() ?? false
  4462. if isEdited || self.model.isPDFTextImageEdited {
  4463. self.listView.commitEditing()
  4464. }
  4465. }
  4466. }
  4467. extension KMMainViewController: KMInteractionProviderProtocol {
  4468. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  4469. let view = self.listView
  4470. view?.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  4471. if let v = view {
  4472. fullScreenWindow.contentView?.addSubview(v)
  4473. }
  4474. return view
  4475. }
  4476. }
  4477. // MARK: - Analytics (埋点)
  4478. extension KMMainViewController {
  4479. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  4480. if (type == .Annatiton) {
  4481. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  4482. } else if (type == .editPDF) {
  4483. } else if (type == .Page) {
  4484. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  4485. } else if (type == .Conversion) {
  4486. } else if (type == .Tool) {
  4487. }
  4488. }
  4489. func trackEvent_aiTranslate() -> Void {
  4490. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  4491. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4492. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4493. }
  4494. func trackEvent_print() -> Void {
  4495. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  4496. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4497. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4498. }
  4499. func trackEvent_share() -> Void {
  4500. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  4501. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4502. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4503. }
  4504. func trackEvent_upgrade() -> Void {
  4505. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  4506. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4507. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4508. }
  4509. func trackEvent(annotationType type: CAnnotationType) -> Void {
  4510. if (type == .highlight) {
  4511. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  4512. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  4513. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4514. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4515. } else if (type == .underline) {
  4516. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  4517. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  4518. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4519. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4520. } else if (type == .strikeOut) {
  4521. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  4522. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  4523. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4524. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4525. } else if (type == .ink) {
  4526. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  4527. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  4528. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4529. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4530. } else if (type == .freeText) {
  4531. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  4532. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  4533. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4534. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4535. } else if (type == .anchored) {
  4536. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  4537. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  4538. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4539. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4540. } else if (type == .square) {
  4541. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  4542. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  4543. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4544. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4545. } else if (type == .link) {
  4546. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  4547. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  4548. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4549. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4550. } else if (type == .stamp) {
  4551. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  4552. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  4553. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4554. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4555. } else if (type == .signSignature) {
  4556. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  4557. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  4558. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4559. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4560. } else if (type == .circle) {
  4561. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  4562. } else if (type == .arrow) {
  4563. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  4564. } else if (type == .line) {
  4565. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  4566. } else if (type == .addText) {
  4567. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  4568. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4569. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4570. } else if (type == .addImage) {
  4571. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  4572. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  4573. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4574. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4575. } else if (type == .textField) {
  4576. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  4577. } else if (type == .checkBox) {
  4578. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  4579. } else if (type == .radioButton) {
  4580. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  4581. } else if (type == .listMenu) {
  4582. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  4583. } else if (type == .comboBox) {
  4584. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  4585. } else if (type == .actionButton) {
  4586. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4587. } else if (type == .actionButton) {
  4588. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4589. } else if (type == .signature) {
  4590. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  4591. } else {
  4592. }
  4593. }
  4594. func trackEvent(toolMode mode: CToolMode) -> Void {
  4595. if (mode == .selectToolMode) {
  4596. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  4597. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4598. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4599. } else if (mode == .moveToolMode) {
  4600. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  4601. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4602. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4603. }
  4604. }
  4605. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  4606. if (type == .word) {
  4607. } else if (type == .excel) {
  4608. } else if (type == .ppt) {
  4609. } else if (type == .rtf) {
  4610. } else if (type == .csv) {
  4611. } else if (type == .html) {
  4612. } else if (type == .conversion_text) {
  4613. } else if (type == .conversion_image) {
  4614. } else if (type == .compress) {
  4615. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  4616. } else if (type == .merge) {
  4617. } else if (type == .secure) {
  4618. } else if (type == .crop) {
  4619. }
  4620. }
  4621. func trackEvent_setPassword() -> Void {
  4622. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  4623. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4624. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4625. }
  4626. func trackEvent_removePassword() -> Void {
  4627. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  4628. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4629. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4630. }
  4631. }
  4632. extension KMMainViewController {
  4633. //文件对比
  4634. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  4635. self.isCompareModel = true
  4636. let compareContentView = KMCompareContentView()
  4637. compareContentView.oldDocument = oldDocument
  4638. compareContentView.document = document
  4639. compareContentView.compareResults = results
  4640. compareContentView.saveHandle = { [unowned self] view in
  4641. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  4642. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  4643. self.currentWindowController = saveController
  4644. saveController.cancelHandle = { [unowned self] controller in
  4645. self.view.window!.endSheet(controller.window!)
  4646. self.currentWindowController = nil
  4647. }
  4648. saveController.saveHandle = { [unowned self] controller, saveType in
  4649. let folderPath = controller.fileSaveFolderPath
  4650. if folderPath != nil {
  4651. if !FileManager.default.fileExists(atPath: folderPath) {
  4652. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  4653. }
  4654. #if VERSION_DMG
  4655. #else
  4656. let url = URL(fileURLWithPath: folderPath)
  4657. let fileAccess = AppSandboxFileAccess()
  4658. fileAccess?.persistPermissionURL(url)
  4659. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  4660. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  4661. let urlString = url.path
  4662. let _url = URL(fileURLWithPath: urlString)
  4663. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  4664. }
  4665. #endif
  4666. var savePath: String
  4667. switch saveType {
  4668. case 0:
  4669. let filePath = oldDocument.documentURL.path
  4670. let fileName = filePath.deletingPathExtension.lastPathComponent
  4671. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4672. savePath = self.getValidFilePath(savePath)
  4673. oldDocument.write(to: URL(fileURLWithPath: savePath))
  4674. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4675. case 1:
  4676. let filePath = document.documentURL.path
  4677. let fileName = filePath.deletingPathExtension.lastPathComponent
  4678. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4679. savePath = self.getValidFilePath(savePath)
  4680. document.write(to: URL(fileURLWithPath: savePath))
  4681. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4682. case 2:
  4683. let filePath = oldDocument.documentURL.path
  4684. let fileName = filePath.deletingPathExtension.lastPathComponent
  4685. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  4686. savePath = self.getValidFilePath(savePath)
  4687. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  4688. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4689. default:
  4690. break
  4691. }
  4692. }
  4693. self.view.window!.endSheet(controller.window!)
  4694. self.currentWindowController = nil
  4695. }
  4696. NSWindow.currentWindow().beginSheet(saveController.window!)
  4697. }
  4698. }
  4699. compareContentView.closeHandle = { [unowned self] view in
  4700. // self.view.window!.endSheet(controller.window!)
  4701. self.isCompareModel = false
  4702. view.removeFromSuperview()
  4703. }
  4704. self.PDFContendView.addSubview(compareContentView)
  4705. compareContentView.frame = self.PDFContendView.bounds
  4706. compareContentView.autoresizingMask = [.width,.height]
  4707. }
  4708. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  4709. self.isCompareModel = true
  4710. let coveringView = KMCompareCoveringView()
  4711. coveringView.pdfDocument = pdfDocument
  4712. coveringView.closeHandle = { [unowned self] view in
  4713. self.isCompareModel = false
  4714. view.removeFromSuperview()
  4715. }
  4716. coveringView.saveHandle = { [unowned self] view in
  4717. let savePanel = NSSavePanel()
  4718. savePanel.nameFieldStringValue = "untitled"
  4719. savePanel.allowedFileTypes = ["pdf"]
  4720. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  4721. if result == .OK {
  4722. pdfDocument.write(to: savePanel.url!)
  4723. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  4724. }
  4725. }
  4726. }
  4727. self.PDFContendView.addSubview(coveringView)
  4728. coveringView.frame = self.PDFContendView.bounds
  4729. coveringView.autoresizingMask = [.width,.height]
  4730. }
  4731. func getValidFilePath(_ oldPath: String) -> String {
  4732. let fileManager = FileManager.default
  4733. do {
  4734. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  4735. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  4736. return oldPath
  4737. }
  4738. var i = 1
  4739. var newPath = oldPath
  4740. while fileManager.fileExists(atPath: newPath) {
  4741. if fileType == FileAttributeType.typeDirectory.rawValue {
  4742. newPath = oldPath + "(\(i))"
  4743. } else {
  4744. let fileExtension = (oldPath as NSString).pathExtension
  4745. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  4746. }
  4747. i += 1
  4748. }
  4749. return newPath
  4750. } catch {
  4751. print("Error getting file attributes: \(error)")
  4752. return oldPath
  4753. }
  4754. }
  4755. }
  4756. extension KMMainViewController {
  4757. func documentAllowsEdit() -> Bool {
  4758. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  4759. let alert = NSAlert()
  4760. alert.alertStyle = .critical
  4761. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  4762. alert.runModal()
  4763. return false
  4764. } else {
  4765. return true
  4766. }
  4767. }
  4768. }