KMMainViewController+Action.swift 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool) {
  10. let document = self.listView.document
  11. if ((document?.isFinding) != nil) {
  12. document?.cancelFindString()
  13. }
  14. if searchString == "" {
  15. self.searchResults = []
  16. // self.leftSideViewController.searchViewController.searchResults = self.searchResults
  17. self.leftSideViewController.searchResults = self.searchResults
  18. // self.leftSideViewController.searchViewController.reloadData()
  19. } else {
  20. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  21. var findArray : [[CPDFSelection]]
  22. if isCase {
  23. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  24. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  25. } else {
  26. findArray = self.listView.document.findString(searchString) ?? []
  27. }
  28. } else {
  29. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  30. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  31. } else {
  32. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  33. }
  34. }
  35. self.searchResults.removeAll()
  36. for selections in findArray {
  37. for selection in selections {
  38. let mode : KMSearchMode = KMSearchMode()
  39. mode.selection = selection
  40. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  41. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  42. self.searchResults.insert(mode, at: self.searchResults.count)
  43. }
  44. }
  45. // self.leftSideViewController.searchViewController.searchResults = self.searchResults
  46. // self.leftSideViewController.searchViewController.reloadData()
  47. self.leftSideViewController.searchResults = self.searchResults
  48. }
  49. if self.leftSideViewController.findPaneState == .singular {
  50. self.leftSideViewController.displayFindViewAnimating(true)
  51. } else {
  52. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  53. }
  54. }
  55. func removeSignatures(signatures:[CPDFSignature]) {
  56. for signature in signatures {
  57. self.listView.document.removeSignature(signature)
  58. }
  59. for i in 0..<self.listView.document.pageCount {
  60. let page : CPDFPage = self.listView.document.page(at: i)
  61. let annotations : [CPDFAnnotation] = page.annotations
  62. for j in 0..<annotations.count {
  63. let annotation = annotations[j]
  64. if annotation is CPDFSignatureWidgetAnnotation {
  65. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  66. }
  67. }
  68. }
  69. self.listView.setNeedsDisplayForVisiblePages()
  70. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  71. var mSignatures : [CPDFSignature] = []
  72. for sign in tSignatures {
  73. if sign.signers.count > 0 {
  74. mSignatures.append(sign)
  75. }
  76. }
  77. // self.leftSideViewController.signatureViewController.signatures = signatures
  78. // self.leftSideViewController.signatureViewController.reloadData()
  79. }
  80. //MARK: menu菜单
  81. func fontColorMenuItem()->NSMenuItem {
  82. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  83. return fontColorItem;
  84. }
  85. func fontSizeMenuItem()->NSMenuItem {
  86. let currentFontSize = self.listView.editingTextFontSize()
  87. let fontSizes = self.fontSizes()
  88. let submenu = NSMenu(title: "")
  89. for i in 0 ... fontSizes.count - 1 {
  90. let fontSize : String = fontSizes.object(at: i) as! String
  91. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  92. item.target = self
  93. item.tag = i
  94. submenu.addItem(item)
  95. if (Int(currentFontSize) == Int(fontSize)) {
  96. item.state = .on
  97. }
  98. }
  99. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  100. fontSizeItem.submenu = submenu
  101. return fontSizeItem;
  102. }
  103. func corpImageMenuItem()->NSMenuItem {
  104. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm Crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  105. return corpImageItem
  106. }
  107. func cancelCorpImageMenuItem()->NSMenuItem {
  108. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel Crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  109. return cancelCorpImageItem
  110. }
  111. func restoreCorpImageMenuItem()->NSMenuItem {
  112. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore Crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  113. return cancelCorpImageItem
  114. }
  115. func cutImageArea()->NSMenuItem {
  116. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  117. return deleteItem
  118. }
  119. func editAddBlanMenu(menu:NSMenu){
  120. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  121. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  122. }
  123. func addText() -> NSMenuItem {
  124. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  125. return addTextItem
  126. }
  127. func addImage() -> NSMenuItem {
  128. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  129. return addImageItem
  130. }
  131. func replaceImageArea()->NSMenuItem {
  132. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  133. return replaceItem
  134. }
  135. func exportImageArea()->NSMenuItem {
  136. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  137. return exportItem
  138. }
  139. func exportImageStampItem()->NSMenuItem {
  140. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  141. let menu = NSMenu()
  142. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  143. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  144. exportItem.submenu = menu
  145. return exportItem
  146. }
  147. func exportMenu() -> NSMenu {
  148. let menu = NSMenu()
  149. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  150. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  151. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  152. return menu
  153. }
  154. func cropMenu() -> NSMenu {
  155. let menu = NSMenu()
  156. let item1 = menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  157. let item2 = menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  158. let item3 = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  159. let item4 = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  160. return menu
  161. }
  162. func zoomSelectionMenuItem() -> NSMenuItem {
  163. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  164. return item
  165. }
  166. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  167. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  168. return item
  169. }
  170. func enterAnnotationStype() -> NSMenuItem {
  171. let stypItem = NSMenuItem(title: NSLocalizedString("Annotation", comment: ""), action: nil, target: self)
  172. let stypeMenu = NSMenu()
  173. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  174. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 0)
  175. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 1)
  176. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 2)
  177. stypeMenu.addItem(NSMenuItem.separator())
  178. }
  179. // stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  180. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Box", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  181. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  182. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  183. stypeMenu.addItem(NSMenuItem.separator())
  184. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  185. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  186. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  187. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  188. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  189. if self.isReadMode {
  190. } else {
  191. stypeMenu.addItem(NSMenuItem.separator())
  192. // _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  193. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  194. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  195. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  196. }
  197. stypItem.submenu = stypeMenu
  198. if self.listView.annotationType == .ink {
  199. stypeMenu.item(at: 0)?.state = .on
  200. } else if self.listView.annotationType == .freeText {
  201. stypeMenu.item(at: 1)?.state = .on
  202. } else if self.listView.annotationType == .anchored {
  203. stypeMenu.item(at: 2)?.state = .on
  204. } else if self.listView.annotationType == .square {
  205. stypeMenu.item(at: 3)?.state = .on
  206. } else if self.listView.annotationType == .circle {
  207. stypeMenu.item(at: 4)?.state = .on
  208. } else if self.listView.annotationType == .arrow {
  209. stypeMenu.item(at: 5)?.state = .on
  210. } else if self.listView.annotationType == .line {
  211. stypeMenu.item(at: 6)?.state = .on
  212. } else if self.listView.annotationType == .link {
  213. stypeMenu.item(at: 7)?.state = .on
  214. } else if self.listView.annotationType == .stamp {
  215. stypeMenu.item(at: 8)?.state = .on
  216. } else if self.listView.annotationType == .signSignature {
  217. stypeMenu.item(at: 9)?.state = .on
  218. }
  219. return stypItem
  220. }
  221. func setAnnotationToolStype() -> NSMenuItem {
  222. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  223. let stypeMenu = NSMenu()
  224. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.noteToolMode.rawValue)
  225. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  226. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  227. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  228. // stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  229. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  230. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  231. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  232. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  233. let item8 = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  234. let item9 = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  235. let item10 = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  236. let item11 = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  237. let item12 = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  238. let item13 = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  239. let item14 = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  240. let item15 = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  241. stypItem.submenu = stypeMenu
  242. if self.toolbarController.toolbarType == .Annatiton {
  243. stypeMenu.item(at: 0)?.state = .on
  244. } else if self.toolbarController.toolbarType == .Move {
  245. stypeMenu.item(at: 1)?.state = .on
  246. } else if self.toolbarController.toolbarType == .Magnify {
  247. stypeMenu.item(at: 2)?.state = .on
  248. } else if self.toolbarController.toolbarType == .Select {
  249. stypeMenu.item(at: 3)?.state = .on
  250. } else if self.toolbarController.toolbarType == .SelectZoom {
  251. stypeMenu.item(at: 4)?.state = .on
  252. }
  253. return stypItem
  254. }
  255. func addReadModelStype() -> NSMenuItem {
  256. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)
  257. if self.isReadMode {
  258. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)
  259. }
  260. return stypItem
  261. }
  262. func addOutlineStype() -> NSMenuItem {
  263. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  264. return stypItem
  265. }
  266. func setTTSStype() -> NSMenuItem {
  267. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  268. return stypItem
  269. }
  270. func setShareStype() -> NSMenuItem {
  271. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: #selector(showShareAction), target: self)
  272. var string = ""
  273. if listView.activeAnnotation != nil {
  274. string = listView.activeAnnotation.contents
  275. }
  276. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  277. return stypItem
  278. }
  279. func setLookUpStype() -> NSMenuItem {
  280. let str = String(format: "Look Up %@", listView?.currentSelection?.string() ?? "")
  281. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(lookUpAction), target: self)
  282. return stypItem
  283. }
  284. func setSearchBaiduStype() -> NSMenuItem {
  285. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  286. return stypItem
  287. }
  288. func setCutStype() -> NSMenuItem {
  289. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  290. return stypItem
  291. }
  292. func setDeleteStype() -> NSMenuItem {
  293. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  294. return stypItem
  295. }
  296. func setColorsStype() -> NSMenuItem {
  297. let stypItem = NSMenuItem(title: NSLocalizedString("Colors...", comment: ""), action: #selector(ColorsItemAction), target: self)
  298. return stypItem
  299. }
  300. func setLinesStype() -> NSMenuItem {
  301. let stypItem = NSMenuItem(title: NSLocalizedString("Lines...", comment: ""), action: #selector(LinesItemAction), target: self)
  302. return stypItem
  303. }
  304. func setEditNoteStype() -> NSMenuItem {
  305. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  306. return stypItem
  307. }
  308. func setRotateStype() -> NSMenuItem {
  309. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  310. let stypeMenu = NSMenu()
  311. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  312. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  313. stypItem.submenu = stypeMenu
  314. if self.toolbarController.toolbarType == .Annatiton {
  315. stypeMenu.item(at: 0)?.state = .on
  316. } else if self.toolbarController.toolbarType == .Move {
  317. stypeMenu.item(at: 1)?.state = .on
  318. }
  319. return stypItem
  320. }
  321. func setNextPageStype() -> NSMenuItem {
  322. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  323. stypItem.isEnabled = false
  324. if listView.canGoToNextPage() {
  325. stypItem.isEnabled = true
  326. }
  327. return stypItem
  328. }
  329. func setPreviousPageStype() -> NSMenuItem {
  330. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  331. stypItem.isEnabled = false
  332. if listView.canGoToPreviousPage() {
  333. stypItem.isEnabled = true
  334. }
  335. return stypItem
  336. }
  337. func setTranslateStype() -> NSMenuItem {
  338. let str = String(format: "Translate %@", listView?.currentSelection?.string() ?? "")
  339. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(TranslateItemAction), target: self)
  340. return stypItem
  341. }
  342. func setAutoScrollStype() -> NSMenuItem {
  343. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  344. return stypItem
  345. }
  346. func setSnapshotStype() -> NSMenuItem {
  347. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  348. let stypeMenu = NSMenu()
  349. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  350. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  351. stypItem.submenu = stypeMenu
  352. // if self.toolbarController.toolbarType == .Annatiton {
  353. // stypeMenu.item(at: 0)?.state = .on
  354. // } else if self.toolbarController.toolbarType == .Move {
  355. // stypeMenu.item(at: 1)?.state = .on
  356. // }
  357. return stypItem
  358. }
  359. func setServicesStype() -> NSMenuItem {
  360. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  361. let stypeMenu = NSMenu()
  362. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  363. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  364. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  365. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  366. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  367. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  368. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  369. stypItem.submenu = stypeMenu
  370. // if self.toolbarController.toolbarType == .Annatiton {
  371. // stypeMenu.item(at: 0)?.state = .on
  372. // } else if self.toolbarController.toolbarType == .Move {
  373. // stypeMenu.item(at: 1)?.state = .on
  374. // }
  375. return stypItem
  376. }
  377. func setCropStype() -> NSMenuItem {
  378. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  379. let stypeMenu = NSMenu()
  380. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  381. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  382. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  383. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  384. // if(NSIsEmptyRect(selectionRect)) {
  385. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  386. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  387. //
  388. // }
  389. stypItem.submenu = stypeMenu
  390. // if self.toolbarController.toolbarType == .Annatiton {
  391. // stypeMenu.item(at: 0)?.state = .on
  392. // } else if self.toolbarController.toolbarType == .Move {
  393. // stypeMenu.item(at: 1)?.state = .on
  394. // } else if self.toolbarController.toolbarType == .Magnify {
  395. // stypeMenu.item(at: 2)?.state = .on
  396. // } else if self.toolbarController.toolbarType == .Select {
  397. // stypeMenu.item(at: 3)?.state = .on
  398. // } else if self.toolbarController.toolbarType == .SelectZoom {
  399. // stypeMenu.item(at: 4)?.state = .on
  400. // }
  401. return stypItem
  402. }
  403. func addHighlightLinksStype() -> NSMenuItem {
  404. let highlightLink = KMPreferenceManager.shared.highlightLinks
  405. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  406. if highlightLink {
  407. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  408. }
  409. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  410. return highlightLinksItem
  411. }
  412. func addAnnotationForStyleMenu(menu:NSMenu) {
  413. if menu == nil {
  414. return
  415. }
  416. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  417. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  418. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  419. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  420. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  421. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  422. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  423. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  424. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  425. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  426. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)
  427. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  428. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  429. if listView.currentSelection.selectionType() != .image {
  430. menu.insertItem(height, at: menu.items.count)
  431. menu.insertItem(underline, at: menu.items.count)
  432. menu.insertItem(strickout, at: menu.items.count)
  433. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  434. }
  435. if self.isReadMode {
  436. } else {
  437. if listView.currentSelection.selectionType() != .image &&
  438. listView.currentSelection.selectionType() != .text {
  439. menu.insertItem(text, at: menu.items.count)
  440. menu.insertItem(note, at: menu.items.count)
  441. }
  442. }
  443. if self.isReadMode {
  444. } else {
  445. if listView.currentSelection.selectionType() != .image {
  446. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  447. menu.insertItem(rectangle, at: menu.items.count)
  448. menu.insertItem(oval, at: menu.items.count)
  449. }
  450. }
  451. if self.isReadMode {
  452. } else {
  453. if listView.currentSelection.selectionType() != .image &&
  454. listView.currentSelection.selectionType() != .text {
  455. menu.insertItem(line, at: menu.items.count)
  456. }
  457. }
  458. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  459. if self.isReadMode {
  460. } else {
  461. menu.insertItem(link, at: menu.items.count)
  462. }
  463. if self.isReadMode {
  464. } else {
  465. if listView.currentSelection.selectionType() != .image {
  466. menu.insertItem(outline, at: menu.items.count)
  467. }
  468. }
  469. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  470. if self.isReadMode {
  471. } else {
  472. if (listView.currentSelection.selectionType() != .image) {
  473. menu.insertItem(aiTranslation, at: menu.items.count)
  474. }
  475. }
  476. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  477. }
  478. func addBookmarkMenu() -> NSMenuItem {
  479. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  480. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  481. return bookMarkItem
  482. } else {
  483. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  484. return bookMarkItem
  485. }
  486. }
  487. func findStringMenu() -> NSMenuItem {
  488. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  489. menuItem.keyEquivalent = "f"
  490. return menuItem
  491. }
  492. func printingMenu() -> NSMenuItem {
  493. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  494. return menuItem
  495. }
  496. func fontSizes()->NSArray {
  497. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  498. }
  499. //MARK: menuItem Action
  500. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  501. let color = listView.editingSelectionFontColor()
  502. let panel = NSColorPanel.shared
  503. panel.setTarget(self)
  504. panel.setAction(#selector(fontColorChangeAction))
  505. panel.orderFront(nil)
  506. panel.showsAlpha = false
  507. panel.color = color ?? NSColor.black
  508. }
  509. @objc func fontColorChangeAction(sender: NSColorPanel) {
  510. self.listView.setEditingSelectionFontColor(sender.color)
  511. }
  512. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  513. let fontSize = self.fontSizes().object(at: sender.tag)
  514. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  515. }
  516. @objc func addImageText(sender: NSMenuItem) {
  517. let event = NSApp.currentEvent
  518. let clickLocation = event?.locationInWindow
  519. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  520. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  521. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  522. point = point2
  523. if sender.tag == 0 {
  524. KMPrint("添加文字")
  525. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  526. if !isSelect {
  527. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  528. }
  529. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  530. } else if sender.tag == 1 {
  531. KMPrint("添加图片")
  532. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  533. if !isSelect {
  534. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  535. }
  536. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  537. } else if sender.tag == 2 {
  538. KMPrint("粘贴")
  539. }
  540. }
  541. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  542. if self.rightSideViewController.eidtPDFImageProperty != nil {
  543. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  544. } else {
  545. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  546. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  547. }
  548. }
  549. }
  550. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  551. if self.rightSideViewController.eidtPDFImageProperty != nil {
  552. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  553. } else {
  554. self.listView.exitCrop(with: self.listView.selectImageAreas)
  555. self.listView.cropAreas = nil
  556. self.listView.isEditImage = false
  557. }
  558. }
  559. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  560. if self.rightSideViewController.eidtPDFImageProperty != nil {
  561. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  562. } else {
  563. self.listView.resetCrop(with: self.listView.selectImageAreas)
  564. }
  565. }
  566. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  567. if self.listView.selectImageAreas != nil {
  568. self.listView.isEditImage = true
  569. self.listView.enterCrop(with: self.listView.selectImageAreas)
  570. self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  571. }
  572. }
  573. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  574. if self.listView.selectImageAreas == nil {
  575. return
  576. }
  577. let panel = NSOpenPanel()
  578. panel.allowsMultipleSelection = false
  579. panel.allowedFileTypes = ["png","jpg"]
  580. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  581. if response == .OK {
  582. let openPath = panel.url?.path
  583. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  584. if s {
  585. }
  586. }
  587. }
  588. }
  589. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  590. if self.listView.selectImageAreas == nil {
  591. return
  592. }
  593. let panel = NSSavePanel()
  594. // panel.nameFieldStringValue = "[新文件].png"
  595. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  596. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  597. // button.state = .on
  598. // panel.accessoryView = button
  599. panel.isExtensionHidden = true
  600. let response = panel.runModal()
  601. if response == .OK {
  602. let url = panel.url
  603. if FileManager.default.fileExists(atPath: url!.path) {
  604. try?FileManager.default.removeItem(atPath: url!.path)
  605. }
  606. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  607. if result {
  608. NSWorkspace.shared.activateFileViewerSelecting([url!])
  609. // if button.state == .on { /// 开启文档
  610. // NSWorkspace.shared.openFile(url!.path)
  611. // } else {
  612. //
  613. // }
  614. }
  615. }
  616. }
  617. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  618. }
  619. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  620. }
  621. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  622. }
  623. @objc func OpenItemAction(sender: NSMenuItem) {
  624. }
  625. @objc func cropAllPageItem(sender: NSMenuItem) {
  626. self.cropAll(nil)
  627. }
  628. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  629. self.crop(nil)
  630. }
  631. @objc func autoCropAllItem(sender: NSMenuItem) {
  632. self.autoCropAll(nil)
  633. }
  634. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  635. self.smartAutoCropAll(nil)
  636. }
  637. @objc func customCropModel(sender: NSMenuItem) {
  638. KMPrint("customCropModel ...")
  639. }
  640. @objc func rotateRightAction(sender: NSMenuItem) {
  641. }
  642. @objc func rotateLeftAction(sender: NSMenuItem) {
  643. }
  644. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  645. self.listView.toolMode = .noteToolMode
  646. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  647. var model : KMToolbarViewType = .None
  648. switch sender.tag {
  649. case 0:
  650. identifier = KMDocumentAnnotationToolbarItemIdentifier
  651. model = .Annatiton
  652. case 1:
  653. identifier = KMToolbarMoveToolModeItemIdentifier
  654. model = .Move
  655. case 2:
  656. identifier = KMToolbarMagnifyToolModeItemIdentifier
  657. model = .Magnify
  658. case 3:
  659. identifier = KMToolbarSelectToolModeItemIdentifier
  660. model = .Select
  661. case 4:
  662. identifier = KMToolbarZoomToSelectionItemIdentifier
  663. model = .SelectZoom
  664. default:
  665. break
  666. }
  667. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  668. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  669. }
  670. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  671. var itemId: String?
  672. if sender.tag == CAnnotationType.highlight.rawValue {
  673. itemId = KMToolbarHighlightAnnotationItemIdentifier
  674. } else if sender.tag == CAnnotationType.underline.rawValue {
  675. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  676. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  677. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  678. } else if sender.tag == CAnnotationType.ink.rawValue {
  679. itemId = KMToolbarInkAnnotationItemIdentifier
  680. } else if sender.tag == CAnnotationType.freeText.rawValue {
  681. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  682. } else if sender.tag == CAnnotationType.anchored.rawValue {
  683. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  684. } else if sender.tag == CAnnotationType.square.rawValue {
  685. itemId = KMToolbarSquareAnnotationItemIdentifier
  686. } else if sender.tag == CAnnotationType.circle.rawValue {
  687. itemId = KMToolbarCircleAnnotationItemIdentifier
  688. } else if sender.tag == CAnnotationType.arrow.rawValue {
  689. itemId = KMToolbarArrowAnnotationItemIdentifier
  690. } else if sender.tag == CAnnotationType.line.rawValue {
  691. itemId = KMToolbarLineAnnotationItemIdentifier
  692. } else if sender.tag == CAnnotationType.link.rawValue {
  693. itemId = KMToolbarLinkAnnotationItemIdentifier
  694. }
  695. if let data = itemId {
  696. self.toolbarController.clickItem(data)
  697. }
  698. }
  699. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  700. var annotationType : CAnnotationType = .unkown
  701. switch sender.tag {
  702. case 0:
  703. annotationType = .highlight
  704. case 1:
  705. annotationType = .underline
  706. case 2:
  707. annotationType = .strikeOut
  708. case 3:
  709. annotationType = .freeText
  710. case 4:
  711. annotationType = .anchored
  712. case 5:
  713. annotationType = .square
  714. case 6:
  715. annotationType = .circle
  716. case 7:
  717. annotationType = .line
  718. case 8:
  719. annotationType = .link
  720. case 9:
  721. // var newOutline : CPDFOutline = CPDFOutline()
  722. // newOutline.label = "11111111"
  723. // let des = self.listView.currentDestination
  724. // if "\(des?.point.x ?? 0)" != "nan" {
  725. // newOutline.destination = self.listView.currentDestination
  726. // } else {
  727. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  728. // newOutline.destination = destination
  729. // }
  730. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  731. // let parent = current.parent ?? CPDFOutline()
  732. // let index = current.index + 1
  733. // parent.insertChild(newOutline, at: index)
  734. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  735. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  736. }
  737. // self.leftSideViewController.outlineViewController.addItemAction()
  738. return
  739. case 10:
  740. annotationType = .unkown
  741. default:
  742. break
  743. }
  744. if (annotationType != .link) {
  745. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  746. self.listView.currentSelection = nil;
  747. return
  748. }
  749. // link
  750. let selection = self.listView.currentSelection
  751. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  752. DispatchQueue.main.async {
  753. Task { @MainActor in
  754. #if VERSION_DMG
  755. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  756. return
  757. }
  758. #endif
  759. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  760. self.listView.currentSelection = nil;
  761. if (annotation != nil) {
  762. self.listView.updateActiveAnnotations([annotation!])
  763. }
  764. }
  765. }
  766. }
  767. @objc func aiTranslationAction(sender: NSMenuItem) {
  768. let content = self.listView.currentSelection.string() ?? ""
  769. let origin = self.listView.currentSelection.bounds.origin
  770. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  771. self.aiTranslationWindow?.content = content
  772. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  773. self.aiTranslationWindow!.window?.center()
  774. }
  775. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  776. Task { @MainActor in
  777. #if VERSION_DMG
  778. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) {
  779. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  780. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  781. return
  782. }
  783. }
  784. #endif
  785. var point = mouseRightMenuEvent?.locationInWindow
  786. if (point == nil) {
  787. point = NSZeroPoint
  788. }
  789. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  790. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  791. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  792. var annotation: CPDFAnnotation?
  793. if self.isReadMode {
  794. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  795. self.listView.toolMode = .noteToolMode
  796. }
  797. switch sender.tag {
  798. case 0:
  799. self.listView.annotationType = CAnnotationType.ink
  800. case 1:
  801. // self.listView.annotationType = CAnnotationType.freeText
  802. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  803. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  804. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  805. if ((annotation) != nil) {
  806. self.listView.updateActiveAnnotations([annotation!])
  807. self.listView.edit(annotation)
  808. }
  809. case 2:
  810. // self.listView.annotationType = CAnnotationType.anchored
  811. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  812. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  813. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  814. self.listView.edit(annotation)
  815. case 3:
  816. // self.listView.annotationType = CAnnotationType.square
  817. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  818. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  819. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  820. case 4:
  821. // self.listView.annotationType = CAnnotationType.circle
  822. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  823. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  824. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  825. case 5:
  826. // self.listView.annotationType = CAnnotationType.arrow
  827. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  828. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  829. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  830. case 6:
  831. // self.listView.annotationType = CAnnotationType.line
  832. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  833. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  834. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  835. case 7:
  836. self.listView.annotationType = CAnnotationType.link
  837. self.openRightPane()
  838. case 8:
  839. self.listView.annotationType = CAnnotationType.stamp
  840. self.openRightPane()
  841. case 9:
  842. self.listView.annotationType = CAnnotationType.signSignature
  843. self.openRightPane()
  844. default:
  845. break
  846. }
  847. self.rightSideViewController.isHidden = true
  848. self.rightSideViewController.subViewType = .AnnotationProperts
  849. } else {
  850. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  851. if(self.toolbarController.toolbarType == .None) {
  852. self.toolbarController.toolbarType = .Annatiton
  853. }
  854. self.listView.toolMode = .noteToolMode
  855. }
  856. switch sender.tag {
  857. case 0:
  858. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  859. self.rightMouseEventing = true
  860. if(self.toolbarController.toolbarType == .None) {
  861. self.toolbarController.toolbarType = .Annatiton
  862. }
  863. self.listView.toolMode = .noteToolMode
  864. self.listView.annotationType = CAnnotationType.ink
  865. case 1:
  866. // self.listView.annotationType = CAnnotationType.freeText
  867. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  868. if (pagePoint.x - defaultSize.width > 0){
  869. pagePoint.x -= defaultSize.width;
  870. }else{
  871. pagePoint.x = 0;
  872. }
  873. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  874. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  875. // self.view.window?.makeFirstResponder()
  876. if ((annotation) != nil) {
  877. // self.listView.updateActiveAnnotations([annotation!])
  878. self.listView.edit(annotation)
  879. }
  880. case 2:
  881. // self.listView.annotationType = CAnnotationType.anchored
  882. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  883. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  884. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  885. self.listView.edit(annotation)
  886. case 3:
  887. // self.listView.annotationType = CAnnotationType.square
  888. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  889. if (pagePoint.x - defaultSize.width > 0){
  890. pagePoint.x -= defaultSize.width;
  891. }else{
  892. pagePoint.x = 0;
  893. }
  894. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  895. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  896. case 4:
  897. // self.listView.annotationType = CAnnotationType.circle
  898. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  899. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  900. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  901. case 5:
  902. // self.listView.annotationType = CAnnotationType.arrow
  903. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  904. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  905. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  906. case 6:
  907. // self.listView.annotationType = CAnnotationType.line
  908. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  909. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  910. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  911. case 7:
  912. self.listView.annotationType = CAnnotationType.link
  913. self.openRightPane()
  914. case 8:
  915. self.listView.annotationType = CAnnotationType.stamp
  916. self.openRightPane()
  917. case 9:
  918. self.listView.annotationType = CAnnotationType.signSignature
  919. self.openRightPane()
  920. case 10:
  921. self.addImgAnnotationToView(center: pagePoint)
  922. default:
  923. break
  924. }
  925. // self.rightSideViewController.view.isHidden = false
  926. self.rightSideViewController.isHidden = false
  927. // self.openRightPane()
  928. self.rightSideViewController.subViewType = .AnnotationProperts
  929. }
  930. if (annotation != nil) {
  931. self.listView.updateIsRightActiveAnnotations([annotation!])
  932. }
  933. }
  934. }
  935. func addImgAnnotationToView(center: NSPoint) {
  936. let accessoryCtr = KMImageAccessoryController()
  937. let openPanel = NSOpenPanel()
  938. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  939. openPanel.allowsMultipleSelection = false
  940. openPanel.accessoryView = accessoryCtr.view
  941. openPanel.isAccessoryViewDisclosed = true
  942. openPanel.beginSheetModal(for: self.view.window!) { result in
  943. if result == .OK {
  944. let fileURL = openPanel.urls.first
  945. let filePath = fileURL!.path
  946. if filePath.pathExtension == "pdf" {
  947. let pdf = CPDFDocument(url: fileURL)
  948. if pdf!.isEncrypted {
  949. NSSound.beep()
  950. return
  951. }
  952. }
  953. let img = NSImage(contentsOfFile: filePath)
  954. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  955. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  956. }
  957. }
  958. }
  959. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  960. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  961. let index = self.listView.currentPageIndex
  962. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  963. self.listView.setNeedsDisplayForVisiblePages()
  964. } else {
  965. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  966. self.listView.setNeedsDisplayForVisiblePages()
  967. }
  968. if self.isReadMode {
  969. } else {
  970. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  971. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  972. }
  973. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  974. if bookMark != nil {
  975. let item = KMBookMarkItem()
  976. item.bookMark = bookMark!
  977. item.label = (bookMark?.label)!
  978. item.index = UInt(bookMark!.pageIndex)
  979. // self.leftSideViewController.bookViewController.reloadData()
  980. // self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  981. } else {
  982. // self.leftSideViewController.bookViewController.reloadData()
  983. }
  984. }
  985. }
  986. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  987. self.leftSideViewController.refreshMethodType(methodType: .Search)
  988. }
  989. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  990. let rect = listView.currentSelectionRect()
  991. let page = listView.currentPage()
  992. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  993. copyPage.setBounds(rect, for: .cropBox)
  994. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  995. // let pdfDocument : PDFDocument = PDFDocument()
  996. // let newpage : PDFPage = PDFPage(image: image)!
  997. // pdfDocument.insert(newpage, at: 0)
  998. // 执行右键操作后,需要取消框选区域
  999. if self.listView.toolMode == .selectToolMode {
  1000. objc_sync_enter(self)
  1001. self.listView.selectionRect = NSZeroRect
  1002. self.listView.selectionPageIndex = UInt(NSNotFound)
  1003. objc_sync_exit(self)
  1004. }
  1005. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1006. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1007. if (result == .cancel) {
  1008. return
  1009. }
  1010. // 解除权限
  1011. self?.isSaveKeyChain = false
  1012. self?.listView.document.unlock(withPassword: password)
  1013. // 隐藏提示
  1014. self?.hiddenSecureLimitTip()
  1015. // 去打印
  1016. KMPrintWindowController.printImage(image: image)
  1017. }
  1018. return
  1019. }
  1020. KMPrintWindowController.printImage(image: image)
  1021. }
  1022. // MARK: Redact 【密文标记】
  1023. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1024. self.listView.remove(self.listView.activeAnnotation)
  1025. }
  1026. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1027. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1028. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1029. self.view.window?.beginSheet(windowController.window!)
  1030. self.currentWindowController = windowController
  1031. windowController.itemClick = { [weak self] index, value in
  1032. if (index == 1) { /// 取消
  1033. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1034. self?.currentWindowController = nil
  1035. return
  1036. }
  1037. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1038. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1039. annotaton.setBorderColor(windowController_redact.outsideColor)
  1040. annotaton.setInteriorColor(windowController_redact.fillColor)
  1041. if (windowController_redact.isOver) {
  1042. annotaton.setFontColor(windowController_redact.fontColor)
  1043. annotaton.setAlignment(windowController_redact.aligement)
  1044. annotaton.setFont(windowController_redact.font)
  1045. annotaton.setOverlayText(windowController_redact.overText)
  1046. }
  1047. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1048. self?.currentWindowController = nil
  1049. }
  1050. }
  1051. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1052. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1053. return
  1054. }
  1055. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1056. let model = CPDFAnnotationModel(annotationType: .redact)
  1057. model?.setColor(annotation.borderColor())
  1058. model?.setInteriorColor(annotation.interiorColor())
  1059. let overlayText: String = annotation.overlayText()
  1060. if (overlayText.isEmpty) {
  1061. model?.setIsOverlayText(false)
  1062. } else {
  1063. model?.setIsOverlayText(true)
  1064. model?.setOverlayText(overlayText)
  1065. model?.setFontColor(annotation.fontColor())
  1066. model?.setAlignment(annotation.alignment())
  1067. model?.setFontName(annotation.font().fontName)
  1068. model?.setFontSize(annotation.font().pointSize)
  1069. }
  1070. }
  1071. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1072. let anno = self.listView.activeAnnotation
  1073. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1074. return
  1075. }
  1076. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1077. windowController.pageCount = Int(self.listView.document.pageCount)
  1078. self.currentWindowController = windowController
  1079. self.view.window?.beginSheet(windowController.window!)
  1080. windowController.itemClick = { [weak self] index, value in
  1081. if (index == 1) {
  1082. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1083. self!.currentWindowController = nil
  1084. return
  1085. }
  1086. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1087. let pageType = windowController_mutilPageFlag.pageType
  1088. let pageString = windowController_mutilPageFlag.pageString
  1089. if (pageType == 4) { /// 自定义页面
  1090. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  1091. if (array.count == 0) {
  1092. let alert = NSAlert()
  1093. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1094. alert.runModal()
  1095. return
  1096. }
  1097. }
  1098. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1099. self!.currentWindowController = nil
  1100. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  1101. if (indexs.count == 0) {
  1102. return
  1103. }
  1104. for i in indexs {
  1105. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1106. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1107. self?.listView.add(redactAnno, to: page)
  1108. }
  1109. }
  1110. }
  1111. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1112. self.exeRedactConfirm(.redactOne) {}
  1113. }
  1114. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1115. self.exeRedactConfirm(.eraserOne) {}
  1116. }
  1117. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1118. }
  1119. @objc func exportStampImage(sender:NSMenuItem) {
  1120. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1121. var image : NSImage = NSImage()
  1122. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1123. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1124. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1125. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1126. }
  1127. let data = image.tiffRepresentation
  1128. if sender.tag == 0 {
  1129. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1130. imageRep.size = image.size
  1131. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1132. let savePanel = NSSavePanel()
  1133. savePanel.allowedFileTypes = ["png"]
  1134. savePanel.beginSheetModal(for: self.view.window!) { response in
  1135. if (response != .OK) {
  1136. return
  1137. }
  1138. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1139. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1140. }
  1141. }
  1142. } else {
  1143. let pdfdocument = CPDFDocument()
  1144. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1145. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1146. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1147. let savePanel = NSSavePanel()
  1148. savePanel.allowedFileTypes = ["pdf"]
  1149. savePanel.beginSheetModal(for: self.view.window!) { response in
  1150. if (response != .OK) {
  1151. return
  1152. }
  1153. if pdfdocument!.write(to: savePanel.url!) {
  1154. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1155. }
  1156. }
  1157. }
  1158. }
  1159. }
  1160. }
  1161. @objc func exportCorpImage(sender:NSMenuItem) {
  1162. let rect = NSIntegralRect(listView.currentSelectionRect())
  1163. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1164. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1165. page.setBounds(rect, for: .cropBox)
  1166. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1167. let data = image.tiffRepresentation
  1168. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1169. imageRep.size = rect.size
  1170. let savePanel = NSSavePanel()
  1171. switch sender.tag {
  1172. case 0:
  1173. savePanel.allowedFileTypes = ["png"]
  1174. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1175. savePanel.beginSheetModal(for: self.view.window!) { response in
  1176. if (response != .OK) {
  1177. return
  1178. }
  1179. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1180. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1181. }
  1182. }
  1183. case 1:
  1184. savePanel.allowedFileTypes = ["jpg"]
  1185. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1186. savePanel.beginSheetModal(for: self.view.window!) { response in
  1187. if (response != .OK) {
  1188. return
  1189. }
  1190. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1191. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1192. }
  1193. }
  1194. case 2:
  1195. savePanel.allowedFileTypes = ["pdf"]
  1196. let pdfdocument = CPDFDocument()
  1197. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1198. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1199. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1200. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1201. savePanel.beginSheetModal(for: self.view.window!) { response in
  1202. if (response != .OK) {
  1203. return
  1204. }
  1205. if pdfdocument!.write(to: savePanel.url!) {
  1206. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1207. }
  1208. }
  1209. }
  1210. default:
  1211. break
  1212. }
  1213. // 执行右键操作后,需要取消框选区域
  1214. if self.listView.toolMode == .selectToolMode {
  1215. objc_sync_enter(self)
  1216. self.listView.selectionRect = NSZeroRect
  1217. self.listView.selectionPageIndex = UInt(NSNotFound)
  1218. objc_sync_exit(self)
  1219. }
  1220. }
  1221. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1222. let rect = listView.currentSelectionRect()
  1223. let page = listView.currentPage()
  1224. if NSIsEmptyRect(rect) == false && page != nil {
  1225. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1226. var bounds = listView.bounds
  1227. var scale = 1.0
  1228. if isLegacy {
  1229. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1230. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1231. }
  1232. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1233. scale = NSHeight(bounds) / NSHeight(rect)
  1234. } else {
  1235. scale = NSWidth(bounds) / NSWidth(rect)
  1236. }
  1237. listView.setScaleFactor(scale, animated: false)
  1238. let scrollView = listView.scroll()
  1239. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1240. if ((scrollView?.hasVerticalScroller) != nil) {
  1241. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1242. }
  1243. if ((scrollView?.hasHorizontalScroller) != nil) {
  1244. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1245. }
  1246. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1247. scale = NSHeight(bounds) / NSHeight(rect)
  1248. } else {
  1249. scale = NSWidth(bounds) / NSWidth(rect)
  1250. }
  1251. listView.setScaleFactor(scale, animated: false)
  1252. }
  1253. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1254. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1255. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1256. };
  1257. }
  1258. // 执行右键操作后,需要取消框选区域
  1259. if self.listView.toolMode == .selectToolMode {
  1260. objc_sync_enter(self)
  1261. self.listView.selectionRect = NSZeroRect
  1262. self.listView.selectionPageIndex = UInt(NSNotFound)
  1263. objc_sync_exit(self)
  1264. }
  1265. }
  1266. // @IBAction func autoCropAll(sender:NSMenuItem) {
  1267. //
  1268. // }
  1269. private func cropPagesToRects(rects:NSPointerArray) {
  1270. }
  1271. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1272. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1273. switch sender.tag {
  1274. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1275. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1276. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1277. var red: CGFloat = 0.0
  1278. var green: CGFloat = 0.0
  1279. var blue: CGFloat = 0.0
  1280. var alpha: CGFloat = 0.0
  1281. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1282. if sender.tag == CAnnotationType.highlight.rawValue {
  1283. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1284. } else if sender.tag == CAnnotationType.underline.rawValue {
  1285. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1286. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1287. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1288. }
  1289. case CAnnotationType.ink.rawValue:
  1290. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1291. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1292. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1293. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1294. var red: CGFloat = 0.0
  1295. var green: CGFloat = 0.0
  1296. var blue: CGFloat = 0.0
  1297. var alpha: CGFloat = 0.0
  1298. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1299. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1300. case CAnnotationType.freeText.rawValue:
  1301. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1302. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1303. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1304. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1305. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1306. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1307. var red: CGFloat = 0.0
  1308. var green: CGFloat = 0.0
  1309. var blue: CGFloat = 0.0
  1310. var alpha: CGFloat = 0.0
  1311. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1312. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1313. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1314. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1315. UserDefaults.standard.synchronize()
  1316. }
  1317. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1318. if (alignment == .left || alignment == .center || alignment == .right) {
  1319. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1320. UserDefaults.standard.synchronize()
  1321. }
  1322. case CAnnotationType.anchored.rawValue:
  1323. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1324. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1325. var red: CGFloat = 0.0
  1326. var green: CGFloat = 0.0
  1327. var blue: CGFloat = 0.0
  1328. var alpha: CGFloat = 0.0
  1329. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1330. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1331. case CAnnotationType.square.rawValue:
  1332. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1333. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1334. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1335. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1336. var red: CGFloat = 0.0
  1337. var green: CGFloat = 0.0
  1338. var blue: CGFloat = 0.0
  1339. var alpha: CGFloat = 0.0
  1340. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1341. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1342. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1343. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1344. case CAnnotationType.circle.rawValue:
  1345. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1346. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1347. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1348. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1349. var red: CGFloat = 0.0
  1350. var green: CGFloat = 0.0
  1351. var blue: CGFloat = 0.0
  1352. var alpha: CGFloat = 0.0
  1353. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1354. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1355. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1356. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1357. default:
  1358. break
  1359. }
  1360. }
  1361. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1362. self.showOrHideNotes()
  1363. }
  1364. //MARK: action
  1365. @objc func cropCurrentPage() {
  1366. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1367. var page: CPDFPage?
  1368. if ((self.listView.currentSelectionPage()) != nil) {
  1369. page = self.listView.currentSelectionPage()
  1370. } else {
  1371. page = self.listView.currentPage()
  1372. }
  1373. if (NSIsEmptyRect(rect)) {
  1374. rect = KMCropTools.getPageForegroundBox(page!)
  1375. }
  1376. let index: UInt = (page?.pageIndex())!
  1377. cropPage(at: index, in: rect)
  1378. // 执行右键操作后,需要取消框选区域
  1379. if self.listView.toolMode == .selectToolMode {
  1380. objc_sync_enter(self)
  1381. self.listView.selectionRect = NSZeroRect
  1382. self.listView.selectionPageIndex = UInt(NSNotFound)
  1383. objc_sync_exit(self)
  1384. }
  1385. }
  1386. func cropPage(at index: UInt, in rect: NSRect) {
  1387. let oldRect = self.listView.document.page(at: index)?.bounds(for: .cropBox)
  1388. let undoManager = self.listView.undoManager
  1389. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)!.cropPage(at: index, in: oldRect!)
  1390. let page = self.listView.document.page(at: index)
  1391. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox))!)
  1392. page?.setBounds(newRect, for: .cropBox)
  1393. /// 刷新预览视图
  1394. self.listView.layoutDocumentView()
  1395. self.listView.displayBox = .cropBox
  1396. }
  1397. @objc func cropAllPage() {
  1398. var size = NSZeroSize
  1399. for i in 0 ..< self.listView.document.pageCount {
  1400. let page = self.listView.document.page(at: i)
  1401. var rect = KMCropTools.getPageForegroundBox(page!)
  1402. size.width = fmax(size.width, NSWidth(rect))
  1403. size.height = fmax(size.height, NSHeight(rect))
  1404. }
  1405. var rectArray: Array<NSRect> = []
  1406. for i in 0 ..< self.listView.document.pageCount {
  1407. let page = self.listView.document.page(at: i)
  1408. var rect = KMCropTools.getPageForegroundBox(page!)
  1409. var bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1410. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1411. rect.origin.x = rect.maxX-size.width
  1412. }
  1413. rect.origin.y = rect.maxY-size.height
  1414. rect.size = size
  1415. if (NSWidth(rect) > NSWidth(bounds)) {
  1416. rect.size.width = NSWidth(bounds)
  1417. }
  1418. if (NSHeight(rect) > NSHeight(bounds)) {
  1419. rect.size.height = NSHeight(bounds)
  1420. }
  1421. if (NSMinX(rect) < NSMinX(bounds)) {
  1422. rect.origin.x = NSMinX(bounds)
  1423. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1424. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1425. }
  1426. if (NSMinY(rect) < NSMinY(bounds)) {
  1427. rect.origin.y = NSMinY(bounds)
  1428. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1429. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1430. }
  1431. rectArray.append(rect)
  1432. }
  1433. cropPages(to: rectArray)
  1434. }
  1435. func cropPages(to rects: Array<NSRect>) {
  1436. let currentPage = self.listView.currentPage()
  1437. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1438. var oldRectArray: Array<NSRect> = []
  1439. for i in 0 ..< self.listView.document.pageCount {
  1440. let page = self.listView.document.page(at: i)
  1441. var rect = NSIntersectionRect(rects[Int(i)], (page?.bounds(for: .mediaBox))!)
  1442. let oldRect = page?.bounds(for: .cropBox)
  1443. oldRectArray.append(oldRect!)
  1444. page?.setBounds(rect, for: .cropBox)
  1445. }
  1446. let undoManager = self.listView.undoManager
  1447. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1448. /// 刷新预览视图
  1449. self.listView.layoutDocumentView()
  1450. self.listView.displayBox = .cropBox
  1451. self.listView.go(to: currentPage)
  1452. self.listView.go(to: visibleRect, on: currentPage)
  1453. }
  1454. private func cropCustomArea() {
  1455. self.listView.toolMode = .selectToolMode
  1456. self.listView.autoScales = true
  1457. self.listView.autoScales = false
  1458. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  1459. if (self.listView.displaysPageBreaks) {
  1460. pageHeight += 8
  1461. }
  1462. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  1463. // if (scaleFactor < self.preView.scaleFactor) {
  1464. self.listView.scaleFactor = scaleFactor
  1465. // }
  1466. let tipView = KMCropTipView()
  1467. tipView.setString(string: "请框选裁剪区域")
  1468. tipView.frame = self.topTipBox.contentView!.frame
  1469. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  1470. self.addTopTip(tipView)
  1471. tipView.enterAction = {
  1472. () in
  1473. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1474. if (NSIsEmptyRect(rect)) {
  1475. return
  1476. }
  1477. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  1478. self.view.window?.beginSheet(window.window!)
  1479. self.cropSettingWindowController = window
  1480. window.itemClick = { [self]
  1481. (index: Int) in
  1482. if (index == 1) { /// 取消
  1483. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1484. self.cropSettingWindowController = nil
  1485. return
  1486. }
  1487. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  1488. let pageCount: Int = Int(self.listView.document.pageCount)
  1489. var pages: Array<Int> = []
  1490. if (pageRangeType == 0) { /// 当前页面
  1491. pages.append(self.listView.currentPageIndex)
  1492. } else if (pageRangeType == 1) { /// 全部页面
  1493. for i in 0 ..< pageCount {
  1494. pages.append(i)
  1495. }
  1496. } else if (pageRangeType == 2) { /// 奇数页面
  1497. var string: String = ""
  1498. for i in 0 ..< pageCount {
  1499. if (i % 2 == 1) {
  1500. continue
  1501. }
  1502. pages.append(i)
  1503. }
  1504. } else if (pageRangeType == 3) { /// 偶数页面
  1505. var string: String = ""
  1506. for i in 0 ..< pageCount {
  1507. if (i % 2 == 0) {
  1508. continue
  1509. }
  1510. pages.append(i)
  1511. }
  1512. } else { /// 自定义
  1513. for i in self.cropSettingWindowController.pageRangePages {
  1514. pages.append(i)
  1515. }
  1516. }
  1517. if (pages.count < 0) {
  1518. let alert = NSAlert()
  1519. alert.messageText = "请选择页面"
  1520. alert.runModal()
  1521. return
  1522. }
  1523. var pageSize: NSSize = NSZeroSize
  1524. if (self.cropSettingWindowController.pageSize == "None") {
  1525. } else {
  1526. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  1527. }
  1528. for i in pages {
  1529. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  1530. var rect = NSIntegralRect(self.listView.selectionRect)
  1531. if (NSIsEmptyRect(rect)) {
  1532. rect = KMCropTools.getPageForegroundBox(page)
  1533. }
  1534. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  1535. page.setBounds(newRect, for: .cropBox)
  1536. if (pageSize.width == 0 && pageSize.height == 0) {
  1537. } else {
  1538. // let tiffData = page.pdfListViewTIFFData(for: rect)
  1539. let index: UInt = (page.pageIndex())
  1540. // let newPage: CPDFPage = nil
  1541. // self.listView.document.removePage(at: index)
  1542. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  1543. // let result = self.preView.document.insertPageObject(newPage, at: index)
  1544. let result = self.listView.document.insertPage(pageSize, at: index)
  1545. }
  1546. }
  1547. /// 保存到临时路径
  1548. let toPath: String = self.listView.document.documentURL.path
  1549. let documentPath = NSTemporaryDirectory()
  1550. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1551. if (FileManager.default.fileExists(atPath: tempPath)) {
  1552. try?FileManager.default.removeItem(atPath: tempPath)
  1553. }
  1554. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  1555. if (result) {
  1556. if (FileManager.default.fileExists(atPath: toPath)) {
  1557. try?FileManager.default.removeItem(atPath: toPath)
  1558. }
  1559. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1560. } else {
  1561. try?FileManager.default.removeItem(atPath: tempPath)
  1562. }
  1563. DispatchQueue.main.async {
  1564. self.listView.toolMode = .textToolMode
  1565. /// 刷新预览视图
  1566. self.listView.layoutDocumentView()
  1567. self.listView.displayBox = .cropBox
  1568. }
  1569. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1570. self.cropSettingWindowController = nil
  1571. self.addTopTip(nil)
  1572. }
  1573. }
  1574. }
  1575. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1576. if (limit) {
  1577. var doucumentURL : URL = self.listView.document.documentURL
  1578. if doucumentURL != nil {
  1579. let docDir = NSTemporaryDirectory()
  1580. let documentName : String = doucumentURL.path.lastPathComponent
  1581. let path = docDir.stringByAppendingPathComponent(documentName)
  1582. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1583. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1584. let writeSuccess = data != nil
  1585. if writeSuccess == false {
  1586. __NSBeep()
  1587. return;
  1588. }
  1589. doucumentURL = URL(fileURLWithPath: path)
  1590. }
  1591. let array = [doucumentURL]
  1592. let picker = NSSharingServicePicker.init(items: array)
  1593. if sender.shareButton.window != nil {
  1594. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1595. } else {
  1596. 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)
  1597. }
  1598. return
  1599. }
  1600. var doucumentURL : URL = self.listView.document.documentURL
  1601. if doucumentURL != nil {
  1602. let docDir = NSTemporaryDirectory()
  1603. let documentName : String = doucumentURL.path.lastPathComponent
  1604. let path = docDir.stringByAppendingPathComponent(documentName)
  1605. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1606. if writeSuccess == false {
  1607. __NSBeep()
  1608. return;
  1609. }
  1610. doucumentURL = URL(fileURLWithPath: path)
  1611. }
  1612. let array = [doucumentURL]
  1613. let picker = NSSharingServicePicker.init(items: array)
  1614. if sender.shareButton.window != nil {
  1615. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1616. } else {
  1617. 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)
  1618. }
  1619. }
  1620. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1621. if (limit) {
  1622. let document = self.listView.document ?? CPDFDocument()
  1623. var path = document!.documentURL.path
  1624. if path != nil {
  1625. let docDir = NSTemporaryDirectory()
  1626. let documentName : String = path.lastPathComponent
  1627. path = docDir.stringByAppendingPathComponent(documentName)
  1628. }
  1629. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1630. var tfileName = path.deletingPathExtension.lastPathComponent
  1631. let tStdFileSuffix = "_flatten"
  1632. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1633. path = pathFolder + "/" + tfileName
  1634. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path))
  1635. let success = data != nil
  1636. if success {
  1637. let url = URL(fileURLWithPath: path)
  1638. let picker = NSSharingServicePicker.init(items: [url])
  1639. if sender.shareButton.window != nil {
  1640. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1641. } else {
  1642. 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)
  1643. }
  1644. }
  1645. return
  1646. }
  1647. let document = self.listView.document ?? CPDFDocument()
  1648. var path = document!.documentURL.path
  1649. if path != nil {
  1650. let docDir = NSTemporaryDirectory()
  1651. let documentName : String = path.lastPathComponent
  1652. path = docDir.stringByAppendingPathComponent(documentName)
  1653. }
  1654. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1655. var tfileName = path.deletingPathExtension.lastPathComponent
  1656. let tStdFileSuffix = "_flatten"
  1657. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1658. path = pathFolder + "/" + tfileName
  1659. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  1660. if success {
  1661. let url = URL(fileURLWithPath: path)
  1662. let picker = NSSharingServicePicker.init(items: [url])
  1663. if sender.shareButton.window != nil {
  1664. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1665. } else {
  1666. 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)
  1667. }
  1668. }
  1669. }
  1670. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  1671. if (limit) {
  1672. let document = self.listView.document ?? CPDFDocument()
  1673. var path = document!.documentURL.path
  1674. if path != nil {
  1675. let docDir = NSTemporaryDirectory()
  1676. let documentName : String = path.lastPathComponent
  1677. path = docDir.stringByAppendingPathComponent(documentName)
  1678. }
  1679. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1680. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1681. var writeSuccess = data != nil
  1682. if writeSuccess == false {
  1683. __NSBeep()
  1684. return;
  1685. }
  1686. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1687. for i in 0 ... newDocument.pageCount-1 {
  1688. let page = newDocument.page(at: i)
  1689. var annotations : [CPDFAnnotation] = []
  1690. for annotation in page!.annotations {
  1691. annotations.append(annotation)
  1692. }
  1693. for annotation in annotations {
  1694. annotation.page.removeAnnotation(annotation)
  1695. }
  1696. }
  1697. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1698. if writeSuccess {
  1699. let url = URL(fileURLWithPath: path)
  1700. let picker = NSSharingServicePicker.init(items: [url])
  1701. if sender.shareButton.window != nil {
  1702. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1703. } else {
  1704. 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)
  1705. }
  1706. }
  1707. return
  1708. }
  1709. let document = self.listView.document ?? CPDFDocument()
  1710. var path = document!.documentURL.path
  1711. if path != nil {
  1712. let docDir = NSTemporaryDirectory()
  1713. let documentName : String = path.lastPathComponent
  1714. path = docDir.stringByAppendingPathComponent(documentName)
  1715. }
  1716. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1717. if writeSuccess == false {
  1718. __NSBeep()
  1719. return;
  1720. }
  1721. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1722. for i in 0 ... newDocument.pageCount-1 {
  1723. let page = newDocument.page(at: i)
  1724. var annotations : [CPDFAnnotation] = []
  1725. for annotation in page!.annotations {
  1726. annotations.append(annotation)
  1727. }
  1728. for annotation in annotations {
  1729. annotation.page.removeAnnotation(annotation)
  1730. }
  1731. }
  1732. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1733. if writeSuccess {
  1734. let url = URL(fileURLWithPath: path)
  1735. let picker = NSSharingServicePicker.init(items: [url])
  1736. if sender.shareButton.window != nil {
  1737. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1738. } else {
  1739. 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)
  1740. }
  1741. }
  1742. }
  1743. // 开启/关闭左边栏
  1744. @objc func toggleLeftPane() -> Void {
  1745. // if lastLeftPanWidth >= functionWidth {
  1746. leftPanelOpen = true
  1747. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1748. // } else {
  1749. // leftPanelOpen = false
  1750. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1751. // }
  1752. }
  1753. // 开启左边栏
  1754. @objc func openLeftPane() -> Void {
  1755. leftPanelOpen = true
  1756. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1757. }
  1758. // 关闭左边栏
  1759. @objc func closeLeftPane() -> Void {
  1760. leftPanelOpen = false
  1761. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1762. }
  1763. // 开启/关闭右边栏
  1764. @objc func toggleRightPane() -> Void {
  1765. if lastRightPanWidth > 5 {
  1766. self.rightPanelIsOpen = false
  1767. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1768. } else {
  1769. self.rightPanelIsOpen = true
  1770. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1771. }
  1772. }
  1773. @objc func openRightPane() -> Void {
  1774. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1775. if self.rightPanelIsOpen {
  1776. return
  1777. }
  1778. self.rightPanelIsOpen = true
  1779. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  1780. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1781. }
  1782. }
  1783. @objc func closeRightPane() -> Void {
  1784. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1785. self.rightPanelIsOpen = false
  1786. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  1787. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1788. }
  1789. }
  1790. func rename(_ sender: NSNotification) -> Void {
  1791. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1792. return
  1793. }
  1794. let tabController = sender.object as? CTTabController
  1795. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1796. let outputSavePanel = NSSavePanel()
  1797. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1798. outputSavePanel.allowedFileTypes = ["pdf"]
  1799. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1800. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1801. let result = outputSavePanel.runModal()
  1802. if result == .OK {
  1803. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1804. let fileURL = pdfDocument?.documentURL
  1805. let fileManager = FileManager.default
  1806. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1807. var result = true
  1808. do {
  1809. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1810. } catch {
  1811. result = false
  1812. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1813. }
  1814. if (result) {
  1815. tabController?.title = outputSavePanel.url!.lastPathComponent
  1816. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1817. self.isSaveKeyChain = false
  1818. newPdfDocument.unlock(withPassword: self.document?.password)
  1819. if (newPdfDocument.pageCount > 0) {
  1820. self.setDocument = newPdfDocument
  1821. }
  1822. }
  1823. }
  1824. } else {
  1825. outputSavePanel.close()
  1826. }
  1827. }
  1828. }
  1829. func showInFinder(_ sender: Any) -> Void {
  1830. if sender is NSNotification {
  1831. let tabController = (sender as! NSNotification).object as? CTTabController
  1832. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1833. let file: URL = (self.myDocument?.fileURL)!
  1834. if FileManager.default.fileExists(atPath: file.path) {
  1835. NSWorkspace.shared.activateFileViewerSelecting([file])
  1836. }
  1837. }
  1838. } else {
  1839. let file: URL = (self.myDocument?.fileURL)!
  1840. if FileManager.default.fileExists(atPath: file.path) {
  1841. NSWorkspace.shared.activateFileViewerSelecting([file])
  1842. }
  1843. }
  1844. }
  1845. func showOrHideNotes() {
  1846. self.listView.hideNotes = !self.listView.hideNotes
  1847. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  1848. //BOTA 注释列表显示隐藏
  1849. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1850. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1851. }
  1852. func closeTab(_ sender: NSNotification) -> Void {
  1853. let tabController = sender.object as? CTTabController
  1854. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1855. print("closeTab")
  1856. self.leftSideViewController.clearAnnotationFilterData()
  1857. self.leftSideViewController.clearNotification()
  1858. }
  1859. }
  1860. // MARK: -
  1861. // MARK: 显示窗口
  1862. internal func showCompressWindow(url: URL? = nil) {
  1863. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  1864. KMPrint("压缩窗口已显示")
  1865. return
  1866. }
  1867. let windowController = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  1868. self.view.window?.beginSheet(windowController.window!)
  1869. self.currentWindowController = windowController
  1870. windowController.password = self.listView?.document?.password ?? ""
  1871. // if let _url = url {
  1872. // windowController.oriDocumentUrl = self.listView.document.documentURL
  1873. // windowController.documentURL = _url
  1874. // } else {
  1875. windowController.documentURL = self.listView.document.documentURL
  1876. // }
  1877. windowController.itemClick = { [weak self] in
  1878. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1879. self?.currentWindowController = nil
  1880. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1881. }
  1882. windowController.batchAction = { [weak self] view, filePaths in
  1883. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1884. self?.currentWindowController = nil
  1885. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1886. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1887. batchWindowController.window?.makeKeyAndOrderFront("")
  1888. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path)
  1889. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1890. batchWindowController.window?.makeKeyAndOrderFront("")
  1891. }
  1892. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  1893. if (result) {
  1894. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1895. self?.currentWindowController = nil
  1896. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1897. if (openDocument) {
  1898. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1899. } else {
  1900. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1901. }
  1902. } else {
  1903. let alert = NSAlert()
  1904. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1905. alert.runModal()
  1906. }
  1907. }
  1908. }
  1909. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1910. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1911. KMPrint("转档窗口已显示")
  1912. return
  1913. }
  1914. var convertT: KMConvertType = .Word
  1915. var windowController: KMConvertBaseWindowController?
  1916. if (type == .word) { /// Word
  1917. convertT = .Word
  1918. } else if (type == .excel) {
  1919. convertT = .Excel
  1920. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1921. if (type == .ppt) {
  1922. convertT = .PPT
  1923. } else if (type == .rtf) {
  1924. convertT = .RTF
  1925. } else if (type == .html) {
  1926. convertT = .HTML
  1927. } else if (type == .conversion_text) {
  1928. convertT = .Text
  1929. }
  1930. } else if (type == .csv) {
  1931. convertT = .CSV
  1932. } else if (type == .conversion_image) {
  1933. windowController = KMConvertImageWindowController()
  1934. }
  1935. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  1936. var url: URL?
  1937. if (documentUrl != nil) {
  1938. url = documentUrl
  1939. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1940. } else {
  1941. url = self.listView.document.documentURL
  1942. }
  1943. self.showAllConvertWindow(convertT: convertT)
  1944. // let model = KMDocumentModel(url: url!)
  1945. // if (self.listView.document.password != nil) {
  1946. // let _ = model.unlock(self.listView.document.password)
  1947. // }
  1948. // model.currentIndex = self.listView.currentPageIndex
  1949. // windowController?.documentModel = model
  1950. //
  1951. // windowController?.itemClick = { [weak self] index in
  1952. // if (identifier != nil) {
  1953. // self?.toolbarController.cancelSelected(identifier!)
  1954. // }
  1955. //
  1956. // if (self?.currentWindowController == nil) {
  1957. // return
  1958. // }
  1959. // self?.view.window?.endSheet(self!.currentWindowController.window!)
  1960. // self?.currentWindowController = nil
  1961. // }
  1962. //
  1963. // self.view.window?.beginSheet((windowController?.window)!)
  1964. // self.currentWindowController = windowController
  1965. }
  1966. //MARK: 转档 -
  1967. func showAllConvertWindow(convertT: KMConvertType) {
  1968. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1969. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1970. var type: KMConvertWithPDFType = .WordAdvance
  1971. switch convertT {
  1972. case .Word:
  1973. break
  1974. case .Excel:
  1975. type = .Excel
  1976. case .PPT:
  1977. type = .PowerPoint
  1978. case .RTF:
  1979. type = .RTF
  1980. case .CSV:
  1981. type = .CSV
  1982. case .HTML:
  1983. type = .HTML
  1984. case .Text:
  1985. type = .Text
  1986. case .JPEG:
  1987. type = .JPEG
  1988. case .PNG:
  1989. type = .PNG
  1990. case .GIF:
  1991. type = .GIF
  1992. case .JPG:
  1993. type = .JPG
  1994. case .TIFF:
  1995. type = .TIFF
  1996. case .TGA:
  1997. type = .TGA
  1998. case .BMP:
  1999. type = .BMP
  2000. case .JP2:
  2001. type = .JPEG2000
  2002. case .AdvancedWord:
  2003. break
  2004. default:
  2005. break
  2006. }
  2007. // let document = self.document
  2008. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2009. var needShowHint = false
  2010. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2011. needShowHint = true
  2012. } else {
  2013. var needContinue = false
  2014. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2015. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2016. let ss = self.document?.documentURL.path
  2017. if arr.contains(ss!) {
  2018. needContinue = false
  2019. }else {
  2020. needContinue = true
  2021. }
  2022. }else {
  2023. needContinue = true
  2024. }
  2025. if needContinue {
  2026. let ss = self.document?.documentURL.path
  2027. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2028. file.password = document?.password ?? ""
  2029. KMBatchOperateManager.defaultManager.files?.append(file)
  2030. }
  2031. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2032. batchWindowController.switchToConvertType(convertType: type)
  2033. }
  2034. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2035. if needShowHint {
  2036. batchWindowController.showIsConvertingHint()
  2037. } else {
  2038. }
  2039. }
  2040. }
  2041. self.km_beginSheet(windowC: convertWC)
  2042. }
  2043. //MARK: 转档 - OCR
  2044. func showOCRWindow() {
  2045. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  2046. self.km_beginSheet(windowC: com)
  2047. }
  2048. //MARK: 数字签名
  2049. func showDigitalSignWindow(withFilePathURL fileURL: URL) {
  2050. var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
  2051. var password: String = ""
  2052. if digitalSignController == nil {
  2053. password = listView.document?.password ?? ""
  2054. digitalSignController = KMPDFDigitalSignViewController()
  2055. }
  2056. digitalSignController?.currentPageIndex = Int(currentPageIndex)
  2057. digitalSignController?.url = listView.document.documentURL
  2058. digitalSignController?.password = password
  2059. digitalSignController?.scaleFactor = listView.scaleFactor
  2060. digitalSignController?.titleChangeBlock = { [weak self] title, index in
  2061. currentPageIndex = UInt(index)
  2062. }
  2063. digitalSignController?.buttonActionBlock = { [unowned self] type, isChanged in
  2064. if type == .cancel {
  2065. // self.toolbarController?.digitalSignModeButtonAction(nil)
  2066. if let page = self.listView.document?.page(at: currentPageIndex) {
  2067. self.listView.go(to: page)
  2068. }
  2069. self.digitalSignController?.view.removeFromSuperview()
  2070. self.digitalSignController = nil
  2071. }
  2072. }
  2073. if let digitalSignView = digitalSignController?.view, let splitViewSuperview = mianSplitView.superview {
  2074. digitalSignView.frame = splitViewSuperview.bounds
  2075. digitalSignView.autoresizingMask = [.width, .height]
  2076. splitViewSuperview.addSubview(digitalSignView)
  2077. }
  2078. }
  2079. //MARK: 导出图片
  2080. func extractImageAction(num: Int) {
  2081. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2082. let alert = NSAlert()
  2083. alert.alertStyle = .critical
  2084. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2085. alert.runModal()
  2086. return
  2087. }
  2088. // if sender is KMToolbarItem {
  2089. // (sender as! KMToolbarItem).isSelected = false
  2090. // }
  2091. // if !IAPProductsManager.defaultManager.isAvailableAllFunction {
  2092. // KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2093. // return
  2094. // }
  2095. let document = self.listView.document
  2096. var fileURL = document?.documentURL
  2097. if num == 1 {
  2098. let pageCount = self.document?.pageCount ?? 0
  2099. var indeSet = NSMutableIndexSet()
  2100. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2101. if indeSet.count == 0 {
  2102. return
  2103. }
  2104. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2105. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2106. let outputSavePanel = NSSavePanel()
  2107. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2108. outputSavePanel.allowsOtherFileTypes = true
  2109. outputSavePanel.isExtensionHidden = true
  2110. outputSavePanel.canCreateDirectories = true
  2111. outputSavePanel.nameFieldStringValue = tFileName
  2112. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2113. if result == NSApplication.ModalResponse.OK {
  2114. DispatchQueue.main.async {
  2115. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2116. let tDestFile = outputSavePanel.url!.path
  2117. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2118. let pdfconverter = PDFConvertObject()
  2119. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2120. self.dismissProgressSheet()
  2121. let fileManager = FileManager.default
  2122. if fileManager.fileExists(atPath: tDestFile) {
  2123. let workspace = NSWorkspace.shared
  2124. let url = URL(fileURLWithPath: tDestFile)
  2125. workspace.activateFileViewerSelecting([url])
  2126. }
  2127. }
  2128. }
  2129. })
  2130. return
  2131. }
  2132. if fileURL != nil {
  2133. self.myDocument?.save(nil)
  2134. } else {
  2135. let myDocument = self.myDocument
  2136. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2137. let writeSuccess = self.document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2138. if writeSuccess {
  2139. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2140. fileURL = self.document?.documentURL
  2141. } else {
  2142. NSSound.beep()
  2143. return
  2144. }
  2145. }
  2146. let extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2147. extract.docPath = fileURL?.path ?? ""
  2148. extract.password = document?.password ?? ""
  2149. extract.currentPage = self.listView.currentPageIndex
  2150. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2151. self.km_beginSheet(windowC: extract)
  2152. extract.selectCurrentPageBtn()
  2153. // self.showCreateStamp()
  2154. // self.showAddSignature()
  2155. }
  2156. //MARK: 创建文字图章示例实际上不会在这里使用
  2157. func showCreateStamp() {
  2158. let stampCreaterWindowController = KMStampCreaterWindowController()
  2159. stampCreaterWindowController.window?.backgroundColor = .clear
  2160. self.km_beginSheet(windowC: stampCreaterWindowController)
  2161. stampCreaterWindowController.closeCallBack = { result in
  2162. if result == 1 {
  2163. }
  2164. }
  2165. }
  2166. //MARK: 添加签名示例实际上不会在这里使用
  2167. func showAddSignature() {
  2168. var signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")//[[KMSignatureWindowController alloc] initWithWindowNibName:@"KMSignatureWindowController"];
  2169. // signatureWindowController.window?.backgroundColor = .clear
  2170. signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2171. }
  2172. }
  2173. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2174. // if progressController == nil {
  2175. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2176. // }
  2177. let progress = SKProgressController()
  2178. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2179. progress.window?.contentView?.wantsLayer = true
  2180. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2181. progress.progressField.textColor = NSColor.white
  2182. progress.message = NSLocalizedString("Converting...", comment: "")
  2183. progressController = progress
  2184. progressController?.message = message
  2185. if maxValue > 0 {
  2186. progressController?.indeterminate = false
  2187. progressController?.maxValue = Double(maxValue)
  2188. } else {
  2189. progressController?.indeterminate = true
  2190. }
  2191. self.km_beginSheet(windowC: progressController!)
  2192. }
  2193. func dismissProgressSheet() {
  2194. progressController?.stopAnimation()
  2195. self.km_endSheet()
  2196. progressController = nil
  2197. }
  2198. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2199. let newArr = NSMutableArray()
  2200. for item in files {
  2201. newArr.add(item.filePath)
  2202. }
  2203. return newArr as! [String]
  2204. }
  2205. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2206. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2207. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2208. if (result == .cancel) {
  2209. return
  2210. }
  2211. // 解除权限
  2212. self?.listView.document.unlock(withPassword: password)
  2213. // 隐藏提示
  2214. self?.hiddenSecureLimitTip()
  2215. // 去打印
  2216. if let data = self?.saveWatermarkFlag, !data {
  2217. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  2218. return
  2219. }
  2220. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  2221. _ = CPDFDocument(url: _url)
  2222. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  2223. } else {
  2224. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2225. }
  2226. }
  2227. return
  2228. }
  2229. if (!self.saveWatermarkFlag) {
  2230. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2231. return
  2232. }
  2233. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  2234. let _document = CPDFDocument(url: _url)
  2235. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  2236. } else {
  2237. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2238. }
  2239. }
  2240. // MARK: - Split View
  2241. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2242. }
  2243. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2244. if !isSinglePage && isHorizontal {
  2245. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  2246. }
  2247. if (!isSinglePage && !isHorizontal) {
  2248. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2249. }
  2250. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  2251. }
  2252. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  2253. if isSinglePage {
  2254. pdfSplitView.dividerStyle = .thin
  2255. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  2256. } else {
  2257. pdfSplitView.dividerStyle = .paneSplitter
  2258. pdfSplitView.isVertical = !isHorizontal
  2259. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  2260. if secondaryPdfView.document != nil {
  2261. // secondaryPdfView.frame = pdfSplitSecondView.frame
  2262. // pdfSplitSecondView.contentView = secondaryPdfView
  2263. } else {
  2264. openSecondaryPdfView = KMSecondaryViewController.init()
  2265. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  2266. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  2267. openSecondaryPdfView?.delegate = self
  2268. }
  2269. }
  2270. }
  2271. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  2272. if (pdfSplitView.isVertical) {
  2273. return Float(NSWidth(rect))
  2274. } else {
  2275. return Float(NSHeight(rect))
  2276. }
  2277. }
  2278. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  2279. let document = CPDFDocument.init(url: url)
  2280. if document != nil {
  2281. secondaryPdfView.frame = pdfSplitSecondView.frame
  2282. pdfSplitSecondView.contentView = secondaryPdfView
  2283. secondaryPdfView.document = nil
  2284. secondaryPdfView.document = document
  2285. return true
  2286. } else {
  2287. return false
  2288. }
  2289. }
  2290. func updateNextAndPreViousButtonState() {
  2291. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2292. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2293. if self.listView.canGoToNextPage() {
  2294. item?.unEnabled = false
  2295. } else {
  2296. item?.unEnabled = true
  2297. }
  2298. if self.listView.canGoToPreviousPage() {
  2299. toItem?.unEnabled = false
  2300. } else {
  2301. toItem?.unEnabled = true
  2302. }
  2303. }
  2304. func updateBackAndForwardButtonState() {
  2305. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2306. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2307. if self.listView.km_canGoBack() {
  2308. item?.unEnabled = false
  2309. } else {
  2310. item?.unEnabled = true
  2311. }
  2312. if self.listView.km_canGoForward() {
  2313. toItem?.unEnabled = false
  2314. } else {
  2315. toItem?.unEnabled = true
  2316. }
  2317. }
  2318. func updateZoomInOutButtonState() {
  2319. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  2320. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  2321. if self.listView.canZoomIn {
  2322. item.unEnabled = false
  2323. } else {
  2324. item.unEnabled = true
  2325. }
  2326. if self.listView.canZoomOut {
  2327. toItem.unEnabled = false
  2328. } else {
  2329. toItem.unEnabled = true
  2330. }
  2331. }
  2332. }
  2333. // MARK: -
  2334. // MARK: - KMSecondaryViewControllerDelegate
  2335. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  2336. func receivedFileUrl(_ url: URL!) {
  2337. let state = self.displaySecondaryPDFView(withUrl: url)
  2338. if !state {
  2339. let alert = NSAlert()
  2340. alert.alertStyle = .critical
  2341. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  2342. alert.runModal()
  2343. return
  2344. }
  2345. }
  2346. }
  2347. // MARK: -
  2348. // MARK: - KMMainToolbarControllerDelegate
  2349. extension KMMainViewController : KMMainToolbarControllerDelegate {
  2350. func changeModelAction(mode: CToolMode) {
  2351. self.listView.toolMode = mode
  2352. if mode == .editPDFToolMode {
  2353. self.childToolbarController.updateType(newType: .editPDF)
  2354. }
  2355. }
  2356. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  2357. switch selectedTag {
  2358. case 2:
  2359. if self.listView.scaleFactor != 1.0 {
  2360. self.listView.scaleFactor = 1.0
  2361. self.listView.autoScales = false
  2362. }
  2363. break
  2364. case 1:
  2365. let pageHeight = self.listView.currentPage()!.size.height
  2366. let pdfviewHeight = self.listView.bounds.size.height
  2367. self.listView.scaleFactor = pdfviewHeight/pageHeight
  2368. self.listView.autoScales = false
  2369. break
  2370. case 0:
  2371. // self.listView.autoScales = !self.listView.autoScales
  2372. self.listView.autoScales = true
  2373. break
  2374. case 3:
  2375. self.listView.scaleFactor = 0.1
  2376. break
  2377. case 4:
  2378. self.listView.scaleFactor = 0.25
  2379. break
  2380. case 5:
  2381. self.listView.scaleFactor = 0.5
  2382. break
  2383. case 6:
  2384. self.listView.scaleFactor = 0.75
  2385. break
  2386. case 7:
  2387. self.listView.scaleFactor = 1.0
  2388. break
  2389. case 8:
  2390. self.listView.scaleFactor = 1.5
  2391. break
  2392. case 9:
  2393. self.listView.scaleFactor = 2.0
  2394. break
  2395. case 10:
  2396. self.listView.scaleFactor = 4.0
  2397. break
  2398. case 11:
  2399. self.listView.scaleFactor = 8.0
  2400. break
  2401. case 12:
  2402. self.listView.scaleFactor = 10.0
  2403. break
  2404. default:
  2405. break
  2406. }
  2407. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2408. }
  2409. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  2410. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2411. if scale > 100 {
  2412. scale = 100
  2413. }
  2414. if (scale <= 0.101) {
  2415. self.listView.scaleFactor = self.listView.minScaleFactor()
  2416. } else {
  2417. self.listView.scaleFactor = scale
  2418. }
  2419. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2420. DispatchQueue.main.async {
  2421. self.updateZoomInOutButtonState()
  2422. }
  2423. }
  2424. func changePDFViewZoomInAction() {
  2425. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2426. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2427. switch scale {
  2428. case 0...0.25:
  2429. scale += 0.25
  2430. case 0.25...3:
  2431. scale += 0.25
  2432. case 3.1...10:
  2433. scale += 0.4
  2434. case 10.1...100:
  2435. scale += 1
  2436. default:
  2437. scale += 1
  2438. }
  2439. self.listView.scaleFactor = scale
  2440. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2441. // self.listView.zoomIn(nil)
  2442. }
  2443. func changePDFViewZoomOutAction() {
  2444. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2445. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2446. switch scale {
  2447. case 0...0.25:
  2448. scale = 0
  2449. case 0.25...3:
  2450. scale -= 0.25
  2451. case 3.1...10:
  2452. scale -= 0.4
  2453. case 10.1...100:
  2454. scale -= 1
  2455. default:
  2456. scale -= 1
  2457. }
  2458. self.listView.scaleFactor = scale
  2459. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2460. // self.listView.zoomOut(nil)
  2461. // self.updateZoomInOutButtonState()
  2462. }
  2463. func changePDFViewGotoNextPageAction() {
  2464. self.listView.km_goBack(nil)
  2465. if (self.listView.canGoToNextPage()) {
  2466. self.listView.goToNextPage(nil)
  2467. }
  2468. self.updateNextAndPreViousButtonState()
  2469. }
  2470. func changePDFViewGoToPreviousPageAction() {
  2471. if (self.listView.canGoToPreviousPage()) {
  2472. self.listView.goToPreviousPage(nil)
  2473. }
  2474. self.updateNextAndPreViousButtonState()
  2475. }
  2476. func changePDFViewGotoBackAction() {
  2477. self.listView.km_goBack(nil)
  2478. self.updateBackAndForwardButtonState()
  2479. }
  2480. func changePDFViewGoToForwardAction() {
  2481. self.listView.km_goForward(nil)
  2482. self.updateBackAndForwardButtonState()
  2483. }
  2484. func aiTranslationPDFFileAction() {
  2485. #if VERSION_DMG
  2486. #else
  2487. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  2488. KMLoginWindowController.show(window: NSApp.mainWindow!)
  2489. return
  2490. }
  2491. #endif
  2492. self.trackEvent_aiTranslate()
  2493. self._aiTranslationPDFFileAction()
  2494. // Task { @MainActor in
  2495. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2496. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  2497. // if (isClose) {
  2498. // return
  2499. // }
  2500. // if (isSub) {
  2501. // self._aiTranslationPDFFileAction()
  2502. // return
  2503. // }
  2504. // }
  2505. // return
  2506. // }
  2507. //
  2508. // self._aiTranslationPDFFileAction()
  2509. // }
  2510. }
  2511. private func _aiTranslationPDFFileAction() {
  2512. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2513. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2514. let alert = NSAlert()
  2515. alert.alertStyle = .critical
  2516. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2517. alert.runModal()
  2518. return
  2519. } else if isExceedsLimit {
  2520. let alert = NSAlert()
  2521. alert.alertStyle = .critical
  2522. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2523. alert.runModal()
  2524. return
  2525. }
  2526. let alert = NSAlert()
  2527. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2528. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2529. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2530. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2531. if (result == .alertFirstButtonReturn) {
  2532. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  2533. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  2534. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  2535. } else if result == .alertSecondButtonReturn {
  2536. return
  2537. }
  2538. }
  2539. }
  2540. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2541. self.trackEvent_share()
  2542. }
  2543. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2544. if (!self.saveWatermarkFlag) {
  2545. self.shareDocument(sender: viewController)
  2546. return
  2547. }
  2548. Task { @MainActor in
  2549. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2550. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2551. if (isClose) {
  2552. return
  2553. }
  2554. if (isSubscribeSuccess) {
  2555. self.shareDocument(sender: viewController)
  2556. return
  2557. }
  2558. if (isWaterMarkExport) {
  2559. self.shareDocument(sender: viewController, limit: true)
  2560. return
  2561. }
  2562. }
  2563. return
  2564. }
  2565. self.shareDocument(sender: viewController)
  2566. }
  2567. }
  2568. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2569. // if (!self.saveWatermarkFlag) {
  2570. // self.shareFlatten(sender: viewController)
  2571. // return
  2572. // }
  2573. Task { @MainActor in
  2574. #if VERSION_DMG
  2575. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2576. let _ = KMComparativeTableViewController.show(window: self.view.window!, .shareFlatten)
  2577. return
  2578. }
  2579. #endif
  2580. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2581. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2582. if (isClose) {
  2583. return
  2584. }
  2585. if (isSubscribeSuccess) {
  2586. self.shareFlatten(sender: viewController)
  2587. return
  2588. }
  2589. if (isWaterMarkExport) {
  2590. self.shareFlatten(sender: viewController, limit: true)
  2591. return
  2592. }
  2593. }
  2594. return
  2595. }
  2596. self.shareFlatten(sender: viewController)
  2597. }
  2598. }
  2599. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2600. if (!self.saveWatermarkFlag) {
  2601. self.shareOriginalPDF(sender: viewController)
  2602. return
  2603. }
  2604. Task { @MainActor in
  2605. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2606. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2607. if (isClose) {
  2608. return
  2609. }
  2610. if (isSubscribeSuccess) {
  2611. self.shareOriginalPDF(sender: viewController)
  2612. return
  2613. }
  2614. if (isWaterMarkExport) {
  2615. self.shareOriginalPDF(sender: viewController, limit: true)
  2616. return
  2617. }
  2618. }
  2619. return
  2620. }
  2621. self.shareOriginalPDF(sender: viewController)
  2622. }
  2623. }
  2624. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2625. if(0 == selectedTag) {
  2626. // self.documentAIViewController?.enteredIncreaseAllPage()
  2627. // self.documentAIViewController?.updateToolState(false)
  2628. } else {
  2629. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  2630. // self.documentAIViewController?.recognitionPartModel(with: .english)
  2631. // self.documentAIViewController?.updateToolState(true)
  2632. }
  2633. // 0 : Scan 1:OCR Text
  2634. }
  2635. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2636. if beforeType == .editPDF {
  2637. // self.asyncSaveDocument { params in
  2638. //
  2639. // }
  2640. }
  2641. // 埋点
  2642. self.trackEvent(toolType: type)
  2643. if(type != .Page) {
  2644. if (hasEnterPageEdit()) {
  2645. self.exitPageEdit()
  2646. }
  2647. }
  2648. if(type != .ScanOCR) {
  2649. // if ((self.documentAIViewController?.view.superview) != nil) {
  2650. // self.listView.isHidden = false
  2651. // self.documentAIViewController?.creatRecognitionDocument()
  2652. // self.documentAIViewController?.view .removeFromSuperview()
  2653. // self.documentAIViewController = nil;
  2654. // self.listView.layoutDocumentView()
  2655. // }
  2656. }
  2657. if (type == .Page) {
  2658. if (hasEnterPageEdit()) {
  2659. self.exitPageEdit()
  2660. } else {
  2661. self.enterPageEdit(pages)
  2662. }
  2663. } else if(type == .ScanOCR) {
  2664. // if((self.documentAIViewController?.view.superview) != nil) {
  2665. // let alert = NSAlert()
  2666. // alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  2667. // alert.addButton(withTitle: "YES")
  2668. // alert.addButton(withTitle: "NO")
  2669. // let result = alert.runModal()
  2670. // if (result == .alertFirstButtonReturn) { /// 取消
  2671. // self.listView.isHidden = false
  2672. // self.documentAIViewController?.creatRecognitionDocument()
  2673. // self.documentAIViewController?.view .removeFromSuperview()
  2674. // self.documentAIViewController = nil;
  2675. // self.listView.layoutDocumentView()
  2676. // } else {
  2677. // self.toolbarController.toolbarType = .ScanOCR
  2678. // }
  2679. // } else {
  2680. // self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  2681. // self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  2682. // self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  2683. // self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  2684. // self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  2685. // }
  2686. } else if type == .editPDF {
  2687. self.listView.annotationType = .editTextImage
  2688. } else if type == .Annatiton {
  2689. self.rightSideViewController.subViewType = .AnnotationProperts
  2690. } else if type == .redact {
  2691. self.enterRedact()
  2692. }
  2693. }
  2694. func clickChildTool(type: KMToolbarType, index: Int) {
  2695. if (type == .secure) {
  2696. if (index == 1) {
  2697. self.trackEvent_setPassword()
  2698. } else if (index == 2) {
  2699. self.trackEvent_removePassword()
  2700. }
  2701. } else {
  2702. self.trackEvent(toolBarType: type)
  2703. }
  2704. Task { @MainActor in
  2705. if (type == .compress) { /// 压缩
  2706. // #if VERSION_DMG
  2707. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2708. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  2709. // self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2710. // return
  2711. // }
  2712. // #endif
  2713. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2714. // self.view.window?.contentView?.superview?.beginLoading()
  2715. let document = self.listView.document
  2716. let secureOptions = self.secureOptions
  2717. let removeSecureFlag = self.removeSecureFlag
  2718. // DispatchQueue.global().async { [unowned self] in
  2719. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  2720. // DispatchQueue.main.async {
  2721. // self.view.window?.contentView?.superview?.endLoading()
  2722. // }
  2723. return
  2724. }
  2725. // DispatchQueue.main.async {
  2726. // self.view.window?.contentView?.superview?.endLoading()
  2727. self.showCompressWindow(url: _url)
  2728. // }
  2729. // }
  2730. return
  2731. }
  2732. if (self.needSaveDocument()) {
  2733. self.saveDocumentWithProgressAlert { [unowned self] params in
  2734. self.showCompressWindow()
  2735. }
  2736. return
  2737. }
  2738. self.showCompressWindow()
  2739. return
  2740. }
  2741. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  2742. var identifier: String?
  2743. if (type == .word) { /// Word
  2744. identifier = KMToolbarConversionWordItemIdentifier
  2745. } else if (type == .excel) {
  2746. identifier = KMToolbarConversionExcelItemIdentifier
  2747. } else if (type == .ppt) {
  2748. identifier = KMToolbarConversionPPTItemIdentifier
  2749. } else if (type == .rtf) {
  2750. identifier = KMToolbarConversionRTFItemIdentifier
  2751. } else if (type == .html) {
  2752. identifier = KMToolbarConversionHTMLItemIdentifier
  2753. } else if (type == .conversion_text) {
  2754. identifier = KMToolbarConversionTextItemIdentifier
  2755. } else if (type == .csv) {
  2756. identifier = KMToolbarConversionCSVItemIdentifier
  2757. } else if (type == .conversion_image) {
  2758. identifier = KMToolbarConversionImageItemIdentifier
  2759. }
  2760. #if VERSION_DMG
  2761. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2762. // if (identifier != nil) {
  2763. // self.toolbarController.cancelSelected(identifier!)
  2764. // }
  2765. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .convert)
  2766. // return
  2767. // }
  2768. #endif
  2769. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2770. // guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2771. // return
  2772. // }
  2773. // self.showConvertWindow(type: type, documentUrl: _url, identifier: identifier)
  2774. // return
  2775. // }
  2776. if (self.needSaveDocument()) {
  2777. self.saveDocumentWithProgressAlert { [unowned self] params in
  2778. self.showConvertWindow(type: type, identifier: identifier)
  2779. }
  2780. return
  2781. }
  2782. self.showConvertWindow(type: type, identifier: identifier)
  2783. return
  2784. }
  2785. if (type == .merge) { /// 合并
  2786. // #if VERSION_DMG
  2787. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2788. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  2789. //
  2790. // self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  2791. // return
  2792. // }
  2793. // #endif
  2794. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  2795. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2796. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2797. if (result == .cancel) {
  2798. return
  2799. }
  2800. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2801. return
  2802. }
  2803. self.showMergeWindow(url: _url, password)
  2804. }
  2805. return
  2806. }
  2807. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2808. if (result == .cancel) {
  2809. return
  2810. }
  2811. if (self.needSaveDocument()) {
  2812. self.saveDocumentWithProgressAlert { [unowned self] params in
  2813. self.showMergeWindow(password)
  2814. }
  2815. return
  2816. }
  2817. self.showMergeWindow(password)
  2818. }
  2819. return
  2820. }
  2821. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2822. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2823. return
  2824. }
  2825. self.showMergeWindow(url: _url, password)
  2826. return
  2827. }
  2828. if (self.needSaveDocument()) {
  2829. self.saveDocumentWithProgressAlert { [unowned self] params in
  2830. self.showMergeWindow(self.listView.document.password)
  2831. }
  2832. return
  2833. }
  2834. self.showMergeWindow(self.listView.document.password)
  2835. return
  2836. }
  2837. if (type == .crop) {
  2838. #if VERSION_DMG
  2839. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2840. let _ = KMComparativeTableViewController.show(window: self.view.window!, .crop)
  2841. return
  2842. }
  2843. #endif
  2844. self.recordSaveWatermarkFlag(type: .crop)
  2845. if (index == 1) {
  2846. self.cropCurrentPage()
  2847. return
  2848. }
  2849. if (index == 2) {
  2850. self.cropAllPage()
  2851. return
  2852. }
  2853. //// 自定义裁剪区域
  2854. // self.cropCustomArea()
  2855. } else if (type == .bates || type == .headerAndFooter) {
  2856. if (index == 1) {
  2857. var windowController: KMBaseWindowController = KMBaseWindowController()
  2858. if (type == .bates) {
  2859. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2860. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2861. let file = KMFileAttribute()
  2862. file.filePath = (self.document?.documentURL.path)!
  2863. self.showBatchWindow(type: .AddBates, files: [file])
  2864. }
  2865. windowController.isBates = true
  2866. } else if (type == .headerAndFooter) {
  2867. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2868. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2869. let file = KMFileAttribute()
  2870. file.filePath = (self.document?.documentURL.path)!
  2871. self.showBatchWindow(type: .AddHeaderFooter, files: [file])
  2872. }
  2873. } else if (type == .background) {
  2874. // controller = KMBackgroundController()
  2875. } else if (type == .watermark) {
  2876. // controller = KMWatermarkViewController()
  2877. }
  2878. windowController.pdfDocument = self.listView.document
  2879. windowController.cancelAction = { [unowned self] controller in
  2880. self.view.window?.endSheet((self.currentWindowController.window)!)
  2881. self.currentWindowController = nil
  2882. }
  2883. self.currentWindowController = windowController
  2884. await self.view.window?.beginSheet(windowController.window!)
  2885. return
  2886. }
  2887. if (index == 1) { /// 取消
  2888. self.toolbarController.exitWatermarkAdjective()
  2889. // self.rightSideViewController.view.isHidden = true
  2890. self.rightSideViewController.isHidden = true
  2891. self.rightSideViewController.subViewType = .None
  2892. self.closeRightPane()
  2893. return
  2894. } else if index == 3 {
  2895. let file = KMFileAttribute()
  2896. file.filePath = (self.document?.documentURL.path)!
  2897. if type == .bates {
  2898. self.showBatchWindow(type: .AddBates, files: [file])
  2899. } else {
  2900. self.showBatchWindow(type: .AddHeaderFooter, files: [file])
  2901. }
  2902. } else if index == 4 {
  2903. let file = KMFileAttribute()
  2904. file.filePath = (self.document?.documentURL.path)!
  2905. if type == .bates {
  2906. self.showBatchWindow(type: .RemoveBates, files: [file])
  2907. } else {
  2908. self.showBatchWindow(type: .RemoveHeaderFooter, files: [file])
  2909. }
  2910. } else if (index == 2) { //// 移除
  2911. if type == .headerAndFooter {
  2912. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2913. let savePanel = NSSavePanel()
  2914. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2915. savePanel.allowedFileTypes = ["pdf"]
  2916. savePanel.accessoryView = savePanelAccessoryViewController.view
  2917. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2918. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2919. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2920. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2921. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2922. }
  2923. } else {
  2924. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2925. }
  2926. }
  2927. }
  2928. }
  2929. } else if type == .bates {
  2930. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2931. let savePanel = NSSavePanel()
  2932. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2933. savePanel.allowedFileTypes = ["pdf"]
  2934. savePanel.accessoryView = savePanelAccessoryViewController.view
  2935. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2936. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2937. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2938. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2939. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2940. }
  2941. } else {
  2942. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2943. }
  2944. }
  2945. }
  2946. }
  2947. }
  2948. return
  2949. } else if (index == 2) { /// 应用
  2950. let model = self.rightSideViewController.model
  2951. if (type == .bates || type == .headerAndFooter) {
  2952. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2953. let alert = NSAlert()
  2954. alert.alertStyle = .critical
  2955. alert.messageText = "没有找到模型"
  2956. alert.runModal()
  2957. return
  2958. }
  2959. if ((model as! KMBatesModel).hasVaild == false) {
  2960. let alert = NSAlert()
  2961. alert.alertStyle = .critical
  2962. alert.messageText = "没有找到内容"
  2963. alert.runModal()
  2964. return
  2965. }
  2966. }
  2967. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2968. result in
  2969. DispatchQueue.main.async {
  2970. self.listView.layoutDocumentView()
  2971. self.listView.setNeedsDisplayForVisiblePages()
  2972. }
  2973. if (result) {
  2974. let alert = NSAlert()
  2975. alert.alertStyle = .warning
  2976. alert.messageText = "成功"
  2977. alert.runModal()
  2978. } else {
  2979. let alert = NSAlert()
  2980. alert.alertStyle = .critical
  2981. alert.messageText = "失败"
  2982. alert.runModal()
  2983. }
  2984. }
  2985. return
  2986. } else if index == 5 {
  2987. self.rightSideViewController.isHidden = false
  2988. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2989. self.openRightPane()
  2990. }
  2991. } else if (type == .redact) { /// 标记密文
  2992. if (index == 1) { /// 取消
  2993. if (self.hasAddRedact) {
  2994. let alert = NSAlert()
  2995. 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: "")
  2996. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2997. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2998. let result = alert.runModal()
  2999. if (result == .alertFirstButtonReturn) {
  3000. self.listView.toolMode = .moveToolMode
  3001. self.toolbarController.exitRedact()
  3002. }
  3003. return
  3004. }
  3005. self.listView.toolMode = .moveToolMode
  3006. self.toolbarController.exitRedact()
  3007. return
  3008. }
  3009. if (index == 2) { /// 擦除
  3010. self.exeRedactConfirm(.eraserAll) {}
  3011. return
  3012. }
  3013. if (index == 3) { /// 应用
  3014. self.exeRedactConfirm(.redactAll) {}
  3015. return
  3016. }
  3017. if (index == 4) { /// 文本&图像
  3018. self.listView.toolMode = .redactToolMode
  3019. return
  3020. }
  3021. if (index == 5) { /// 页面
  3022. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3023. await self.view.window?.beginSheet(windowController.window!)
  3024. self.currentWindowController = windowController
  3025. windowController.itemClick = { [weak self] index, value in
  3026. if (index == 1) {
  3027. let topBarView = self?.toolbarController.fetchTopBarView()
  3028. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  3029. return
  3030. }
  3031. (topBarView as! KMRedactTopToolBar).selectItem(0)
  3032. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3033. self?.currentWindowController = nil
  3034. return
  3035. }
  3036. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3037. let pageType = windowController_pageRange.pageType
  3038. let pageString = windowController_pageRange.pageString
  3039. if (pageType == 5) { /// 自定义页面
  3040. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  3041. if (array.count == 0) {
  3042. let alert = NSAlert()
  3043. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3044. alert.runModal()
  3045. return
  3046. }
  3047. }
  3048. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3049. self!.currentWindowController = nil
  3050. var indexs: IndexSet = []
  3051. if (pageType == 1) { /// 当前页面
  3052. indexs.insert((self?.listView.currentPageIndex)!)
  3053. } else {
  3054. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  3055. }
  3056. if (indexs.count == 0) {
  3057. return
  3058. }
  3059. for i in indexs {
  3060. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3061. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3062. redactAnno.bounds = page.bounds
  3063. self?.listView.add(redactAnno, to: page)
  3064. }
  3065. }
  3066. return
  3067. }
  3068. } else if (type == .secure) { /// 安全
  3069. #if VERSION_DMG
  3070. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  3071. let _ = KMComparativeTableViewController.show(window: self.view.window!, .secure)
  3072. return
  3073. }
  3074. #endif
  3075. if (index == 1) { /// 设置密码
  3076. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3077. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  3078. if (result == .cancel) {
  3079. return
  3080. }
  3081. self?.isSaveKeyChain = false
  3082. self?.listView.document.unlock(withPassword: password)
  3083. self?.hiddenSecureLimitTip()
  3084. self?.showSecureWindow((self?.listView.document.documentURL)!)
  3085. }
  3086. return
  3087. }
  3088. self.showSecureWindow(self.listView.document.documentURL)
  3089. return
  3090. } else if index == 2 {
  3091. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3092. let alert = NSAlert()
  3093. alert.alertStyle = .warning
  3094. alert.messageText = NSLocalizedString("Warning", comment: "")
  3095. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3096. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3097. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3098. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3099. if returnCode == .alertSecondButtonReturn {
  3100. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3101. KMBaseWindowController.checkPassword(url: self.document!.documentURL!) { [unowned self] success, resultPassword in
  3102. if success {
  3103. self.document?.unlock(withPassword: resultPassword)
  3104. self.clickChildTool(type: .secure, index: 2)
  3105. }
  3106. }
  3107. }
  3108. }
  3109. }
  3110. } else {
  3111. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3112. controller.pdfDocument = self.document
  3113. self.currentWindowController = controller
  3114. controller.batchAction = { [unowned self] controller, files in
  3115. self.view.window?.endSheet((self.currentWindowController.window)!)
  3116. self.currentWindowController = nil
  3117. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3118. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3119. batchWindowController.window?.makeKeyAndOrderFront("")
  3120. let batchOperateFile = KMBatchOperateFile(filePath: files.first?.filePath ?? "")
  3121. batchWindowController.switchToOperateType(.RemovePassword, files: [batchOperateFile])
  3122. batchWindowController.window?.makeKeyAndOrderFront("")
  3123. }
  3124. controller.cancelAction = { [unowned self] controller in
  3125. self.view.window?.endSheet((self.currentWindowController.window)!)
  3126. self.currentWindowController = nil
  3127. }
  3128. controller.doneAction = { [unowned self] controller in
  3129. self.view.window?.endSheet((self.currentWindowController.window)!)
  3130. self.currentWindowController = nil
  3131. KMBaseWindowController.checkPassword(url: self.document!.documentURL!) { [unowned self] success, resultPassword in
  3132. if success {
  3133. /// 删除安全性设置
  3134. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3135. self.isSaveKeyChain = false
  3136. self.listView.document.unlock(withPassword: password)
  3137. self.hiddenSecureLimitTip()
  3138. self.recordRemoveSecureFlag()
  3139. self.recordSaveWatermarkFlag(type: .removePassword)
  3140. let tip = KMRemovePasswordResultTipView()
  3141. tip.result = .success
  3142. tip.showInView(superView: (self.listView.superview)!)
  3143. } else {
  3144. self.recordRemoveSecureFlag()
  3145. self.recordSaveWatermarkFlag(type: .removePassword)
  3146. let tip = KMRemovePasswordResultTipView()
  3147. tip.result = .success
  3148. self.hiddenSecureLimitTip()
  3149. tip.showInView(superView: self.listView.superview!)
  3150. }
  3151. }
  3152. }
  3153. }
  3154. await NSWindow.currentWindow().beginSheet(controller.window!)
  3155. }
  3156. return
  3157. }
  3158. } else if type == .comparison {
  3159. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3160. self.currentWindowController = controller
  3161. controller.filePath = (self.document?.documentURL.path)!
  3162. controller.cancelAction = { [unowned self] controller in
  3163. self.view.window?.endSheet((self.currentWindowController.window)!)
  3164. self.currentWindowController = nil
  3165. }
  3166. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3167. DispatchQueue.main.async {
  3168. self.view.window?.endSheet((controller.window)!)
  3169. self.currentWindowController = nil
  3170. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3171. }
  3172. }
  3173. controller.coveringComplete = { [unowned self] controller, document in
  3174. self.view.window?.endSheet((controller.window)!)
  3175. self.currentWindowController = nil
  3176. self.openCoveringCompareVC(with: document)
  3177. }
  3178. if index == 1 {
  3179. controller.fileType = .content
  3180. } else {
  3181. controller.fileType = .coverting
  3182. }
  3183. await NSWindow.currentWindow().beginSheet(controller.window!)
  3184. } else if type == .watermark {
  3185. if index == 1 {
  3186. let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  3187. self.currentWindowController = controller
  3188. controller.pdfDocument = self.document
  3189. controller.cancelAction = { [unowned self] controller in
  3190. self.view.window?.endSheet((self.currentWindowController.window)!)
  3191. self.currentWindowController = nil
  3192. }
  3193. controller.operateCallBack = { [unowned self] controller, watermark, countType in
  3194. let file = KMFileAttribute()
  3195. file.filePath = (self.document?.documentURL.path)!
  3196. self.showBatchWindow(type: .AddWatermark, files: [file])
  3197. }
  3198. await NSWindow.currentWindow().beginSheet(controller.window!)
  3199. } else if index == 2 {
  3200. let watermarks = self.listView.document.watermarks()
  3201. if (watermarks == nil || watermarks!.count <= 0) {
  3202. let alert = NSAlert()
  3203. alert.alertStyle = .warning
  3204. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  3205. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  3206. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  3207. alert.runModal()
  3208. return
  3209. }
  3210. let alert = NSAlert()
  3211. alert.alertStyle = .warning
  3212. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  3213. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  3214. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  3215. let result = alert.runModal()
  3216. if (result != .alertFirstButtonReturn) {
  3217. return
  3218. }
  3219. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  3220. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  3221. result in
  3222. DispatchQueue.main.async {
  3223. self.listView.layoutDocumentView()
  3224. self.listView.setNeedsDisplayForVisiblePages()
  3225. }
  3226. if (result) {
  3227. let alert = NSAlert()
  3228. alert.alertStyle = .warning
  3229. alert.messageText = "成功"
  3230. alert.runModal()
  3231. } else {
  3232. let alert = NSAlert()
  3233. alert.alertStyle = .critical
  3234. alert.messageText = "失败"
  3235. alert.runModal()
  3236. }
  3237. }
  3238. } else if index == 3 {
  3239. let file = KMFileAttribute()
  3240. file.filePath = (self.document?.documentURL.path)!
  3241. self.showBatchWindow(type: .AddWatermark, files: [file])
  3242. } else if index == 4 {
  3243. let file = KMFileAttribute()
  3244. file.filePath = (self.document?.documentURL.path)!
  3245. self.showBatchWindow(type: .RemoveWatermark, files: [file])
  3246. } else if index == 5 {
  3247. self.rightSideViewController.isHidden = false
  3248. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3249. self.openRightPane()
  3250. return
  3251. }
  3252. } else if type == .background {
  3253. if index == 1 {
  3254. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  3255. self.currentWindowController = controller
  3256. controller.pdfDocument = self.document
  3257. controller.cancelAction = { [unowned self] controller in
  3258. self.view.window?.endSheet((self.currentWindowController.window)!)
  3259. self.currentWindowController = nil
  3260. }
  3261. controller.operateCallBack = { [unowned self] controller, background, countType in
  3262. let file = KMFileAttribute()
  3263. file.filePath = (self.document?.documentURL.path)!
  3264. self.showBatchWindow(type: .AddBackground, files: [file])
  3265. }
  3266. await NSWindow.currentWindow().beginSheet(controller.window!)
  3267. } else if index == 2 {
  3268. guard let document = self.document else { return }
  3269. if !document.allowsPrinting || !document.allowsCopying {
  3270. let alert = NSAlert()
  3271. alert.alertStyle = .critical
  3272. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3273. alert.runModal()
  3274. return
  3275. }
  3276. guard let documentURL = document.documentURL else { return }
  3277. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3278. let savePanel = NSSavePanel()
  3279. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  3280. savePanel.allowedFileTypes = ["pdf"]
  3281. savePanel.accessoryView = savePanelAccessoryViewController.view
  3282. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3283. guard result == .OK else { return }
  3284. KMAddBackgroundView.saveAsPDFRemoveAllBackground(PDFDocument: document, password: document.password, toPath: savePanel.url!.path, completionHandler: { [unowned self] success in
  3285. if success == 1 {
  3286. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3287. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { _, _, _ in }
  3288. } else {
  3289. NSWorkspace.shared.selectFile(savePanel.url!.path, inFileViewerRootedAtPath: "")
  3290. }
  3291. }
  3292. })
  3293. }
  3294. } else if index == 3 {
  3295. let file = KMFileAttribute()
  3296. file.filePath = (self.document?.documentURL.path)!
  3297. self.showBatchWindow(type: .AddBackground, files: [file])
  3298. } else if index == 4 {
  3299. let file = KMFileAttribute()
  3300. file.filePath = (self.document?.documentURL.path)!
  3301. self.showBatchWindow(type: .RemoveBackground, files: [file])
  3302. } else if index == 5 {
  3303. self.rightSideViewController.isHidden = false
  3304. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3305. self.openRightPane()
  3306. return
  3307. }
  3308. }
  3309. }
  3310. }
  3311. func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  3312. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3313. batchWindowController.window?.makeKeyAndOrderFront("")
  3314. var array: [KMBatchOperateFile] = []
  3315. for file in files! {
  3316. let batchOperateFile = KMBatchOperateFile(filePath: file.filePath)
  3317. array.append(batchOperateFile)
  3318. }
  3319. batchWindowController.switchToOperateType(type, files: array)
  3320. batchWindowController.window?.makeKeyAndOrderFront("")
  3321. }
  3322. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  3323. if let itemID = toolbarItem.itemIdentifier {
  3324. if isMainToolItem(itemID) {
  3325. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  3326. self.browserWindowController?.browser.selectTabContents(at: 0, userGesture: true)
  3327. self.toolbarController.findItem(KMDocumentHomeToolbarItemIdentifier)?.isSelected = false
  3328. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  3329. self.changePDFViewGoToPreviousPageAction()
  3330. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  3331. self.changePDFViewGotoNextPageAction()
  3332. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3333. Swift.debugPrint("KMDocumentViewDisplayToolbarItemIdentifier ...")
  3334. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  3335. toolbarItem.isSelected = !toolbarItem.isSelected
  3336. self.toggleLeftPane()
  3337. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  3338. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3339. toolbarItem.isSelected = !toolbarItem.isSelected
  3340. self.toggleRightPane()
  3341. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  3342. self.listView.toolMode = .redactToolMode
  3343. self.enterRedact()
  3344. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  3345. showOCRWindow()
  3346. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  3347. Swift.debugPrint("KMDocumentDigitalSignToolbarItemIdentifier ...")
  3348. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  3349. }
  3350. } else {
  3351. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  3352. let windowC = KMToolbarCustomWindowController()
  3353. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  3354. self.km_beginSheet(windowC: windowC)
  3355. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  3356. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  3357. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  3358. self.trackEvent_print()
  3359. self.showPrintWindow()
  3360. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  3361. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  3362. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  3363. windowC.callBack = { [weak self] string in
  3364. // if (string.length > 0) {
  3365. // [blockSelf.pdfView addTextFieldWithSubType:KMSelfSignAnnotationFreeTextSubType_Profile string:string];
  3366. // }
  3367. self?.km_endSheet()
  3368. }
  3369. self.km_beginSheet(windowC: windowC)
  3370. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  3371. Swift.debugPrint("KMToolbarViewSettingIdentifier ...")
  3372. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  3373. self.listView.takeSnapshot(nil)
  3374. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  3375. Swift.debugPrint("KMToolbarTTSIdentifier ...")
  3376. self.showTTSWindow()
  3377. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  3378. self.showOCRWindow()
  3379. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  3380. Swift.debugPrint("KMAnnotationImageToolbarItemIdentifier ...")
  3381. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  3382. Swift.debugPrint("KMAnnotationTableToolbarItemIdentifier ...")
  3383. }
  3384. }
  3385. }
  3386. }
  3387. func showTTSWindow() {
  3388. var lastPDFView: CPDFView?
  3389. let ttsView = KMTTSWindowController.share
  3390. if (ttsView.window?.isVisible ?? false) {
  3391. lastPDFView = ttsView.pdfView
  3392. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  3393. lastPDFView = nil
  3394. ttsView.window?.orderOut(nil)
  3395. } else {
  3396. ttsView.pdfView = self.listView
  3397. ttsView.showWindow(nil)
  3398. }
  3399. } else {
  3400. ttsView.pdfView = self.listView
  3401. ttsView.showWindow(nil)
  3402. }
  3403. // weak var blockSelf = self
  3404. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  3405. if isCloseWindow {
  3406. // for item in blockSelf?.toolbar.items ?? [] {
  3407. // if item.itemIdentifier == KMToolbarTTSViewItemIdentifier {
  3408. // item.isSelected = false
  3409. // }
  3410. // }
  3411. }
  3412. }
  3413. if let currentSelection = self.listView.currentSelection {
  3414. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  3415. ttsView.startSpeakingPDFSelection(currentSelection)
  3416. }
  3417. }
  3418. if let lastPDFView = lastPDFView {
  3419. lastPDFView.setHighlightedSelections([])
  3420. ttsView.stopSpeaking()
  3421. }
  3422. }
  3423. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3424. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  3425. KMPrint("KMToolbarToolWatermarkItemIdentifier \(index)")
  3426. self.clickChildTool(type: .watermark, index: index)
  3427. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  3428. self.clickChildTool(type: .background, index: index)
  3429. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  3430. KMPrint("KMToolbarToolHeaderFooterItemIdentifier \(index)")
  3431. self.clickChildTool(type: .headerAndFooter, index: index)
  3432. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  3433. KMPrint("KMToolbarToolBatesItemIdentifier \(index)")
  3434. self.clickChildTool(type: .bates, index: index)
  3435. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  3436. KMPrint("KMToolbarComparisonItemIdentifier \(index)")
  3437. self.clickChildTool(type: .comparison, index: index)
  3438. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  3439. KMPrint("KMToolbarToolFormAlignIdentifier \(index)")
  3440. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  3441. KMPrint("KMToolbarConversionImageItemIdentifier \(index)")
  3442. convertToImg(index: index)
  3443. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  3444. extractImageAction(num: index)
  3445. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  3446. self.createPdf(index: index)
  3447. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  3448. if index == 2 { // 裁剪当前页面
  3449. self.cropCurrentPage()
  3450. } else if index == 3 { // Auto Crop – Separate
  3451. self.cropAllPage()
  3452. } else if index == 4 { // Auto Crop – Combined
  3453. self.cropAllPage()
  3454. } else if index == 5 { // Select Area
  3455. self.toolbarController.clickItem(KMToolbarSelectToolModeItemIdentifier)
  3456. }
  3457. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  3458. KMPrint("KMToolbarToolSecureItemIdentifier \(index)")
  3459. self.clickChildTool(type: .secure, index: index)
  3460. }
  3461. }
  3462. func convertToImg(index: Int) {
  3463. var convertT: KMConvertType = .JPEG
  3464. switch index {
  3465. case 7:
  3466. convertT = .JPEG
  3467. case 8:
  3468. convertT = .JPG
  3469. case 9:
  3470. convertT = .PNG
  3471. case 10:
  3472. convertT = .GIF
  3473. case 11:
  3474. convertT = .TIFF
  3475. case 12:
  3476. convertT = .TGA
  3477. case 13:
  3478. convertT = .BMP
  3479. default:
  3480. convertT = .JPEG
  3481. }
  3482. showAllConvertWindow(convertT: convertT)
  3483. }
  3484. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String) {
  3485. Swift.debugPrint("Search Result " + searchString)
  3486. }
  3487. }
  3488. // MARK: -
  3489. // MARK: - Mouse
  3490. extension KMMainViewController {
  3491. override func mouseDown(with event: NSEvent) {
  3492. super.mouseDown(with: event)
  3493. KMPrint("KMMainViewController mouseDown")
  3494. self.leftSideViewCancelSelect()
  3495. self.pageNumberDisplayView.isEdit = false
  3496. }
  3497. }
  3498. //MARK: LeftSideViewController
  3499. extension KMMainViewController {
  3500. func leftSideViewCancelSelect() {
  3501. // switch self.leftSideViewController.type.methodType {
  3502. // case .Thumbnail:
  3503. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  3504. // break
  3505. // case .Outline:
  3506. //// self.leftSideViewController.outlineViewController.cancelSelect()
  3507. // break
  3508. // case .BookMark:
  3509. //// self.leftSideViewController.bookViewController.cancelSelect()
  3510. // break
  3511. // case .Search:
  3512. //// self.leftSideViewController.searchViewController.cancelSelect()
  3513. // break
  3514. // case .Annotation:
  3515. //// self.leftSideViewController.annotationViewController.cancelSelect()
  3516. // break
  3517. // default:
  3518. if self.listView.isEditing() {
  3519. if self.listView.editingAreas() != nil &&
  3520. self.listView.editingAreas().count != 0 {
  3521. let areas = self.listView.editingAreas().first
  3522. if areas is CPDFEditTextArea {
  3523. self.listView.clearEditingSelectCharItem()
  3524. self.listView.updateEditing([])
  3525. KMPrint("取消选中")
  3526. }
  3527. }
  3528. }
  3529. KMPrint("其他")
  3530. // }
  3531. }
  3532. }
  3533. extension KMMainViewController: KMReadModelViewDelegate {
  3534. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3535. self.listView.goToFirstPage(nil)
  3536. }
  3537. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  3538. self.listView.goToPreviousPage(nil)
  3539. }
  3540. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3541. self.listView.goToNextPage(nil)
  3542. }
  3543. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3544. self.listView.goToLastPage(nil)
  3545. }
  3546. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  3547. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  3548. }
  3549. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  3550. var scale: Double = 1.0
  3551. switch type {
  3552. case .fitWidth:
  3553. self.listView.autoScales = !self.listView.autoScales
  3554. scale = self.listView.scaleFactor
  3555. break
  3556. case .actualSize:
  3557. if self.listView.scaleFactor != 1.0 {
  3558. self.listView.scaleFactor = 1.0
  3559. self.listView.autoScales = false
  3560. }
  3561. scale = self.listView.scaleFactor
  3562. break
  3563. case .autoSize:
  3564. self.listView.autoScales = true
  3565. self.listView.autoScales = false
  3566. scale = self.listView.scaleFactor
  3567. break
  3568. case ._10:
  3569. scale = 0.1
  3570. break
  3571. case ._25:
  3572. scale = 0.25
  3573. break
  3574. case ._50:
  3575. scale = 0.5
  3576. break
  3577. case ._100:
  3578. scale = 1.0
  3579. break
  3580. case ._150:
  3581. scale = 1.5
  3582. break
  3583. case ._200:
  3584. scale = 2.0
  3585. break
  3586. case ._400:
  3587. scale = 4.0
  3588. break
  3589. case ._800:
  3590. scale = 8.0
  3591. break
  3592. default:
  3593. break
  3594. }
  3595. self.listView.scaleFactor = scale
  3596. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3597. }
  3598. func cancelReadModel(view: KMReadModelView, sender: Any) {
  3599. if self.isReadMode {
  3600. self.closeReadModel()
  3601. }
  3602. }
  3603. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  3604. // if self.readModelViewWidthConstraint.constant != width {
  3605. self.readModelViewWidthConstraint.constant = width
  3606. // }
  3607. }
  3608. }
  3609. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  3610. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  3611. self.listView.go(toPageIndex: pageIndex, animated: true)
  3612. }
  3613. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  3614. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  3615. self.tipCurrentPageBoxWidthConstraint.constant = width
  3616. }
  3617. }
  3618. func commitEditingIfNeed() {
  3619. let isEdited = self.listView?.isEdited() ?? false
  3620. if isEdited || self.isPDFTextImageEdited {
  3621. self.listView.commitEditing()
  3622. }
  3623. }
  3624. }
  3625. // MARK: - Analytics (埋点)
  3626. extension KMMainViewController {
  3627. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  3628. if (type == .Annatiton) {
  3629. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Annotation", parameters: [
  3630. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3631. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3632. } else if (type == .editPDF) {
  3633. KMAnalytics.trackEvent(eventName: "Btn_Tbr_EditPDF", parameters: [
  3634. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3635. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3636. } else if (type == .Page) {
  3637. KMAnalytics.trackEvent(eventName: "Btn_Tbr_PageEdit", parameters: [
  3638. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3639. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3640. } else if (type == .Conversion) {
  3641. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Converter", parameters: [
  3642. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3643. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3644. } else if (type == .Tool) {
  3645. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Tools", parameters: [
  3646. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3647. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3648. }
  3649. }
  3650. func trackEvent_aiTranslate() -> Void {
  3651. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  3652. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3653. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3654. }
  3655. func trackEvent_print() -> Void {
  3656. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  3657. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3658. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3659. }
  3660. func trackEvent_share() -> Void {
  3661. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  3662. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3663. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3664. }
  3665. func trackEvent_upgrade() -> Void {
  3666. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  3667. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3668. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3669. }
  3670. func trackEvent(annotationType type: CAnnotationType) -> Void {
  3671. if (type == .highlight) {
  3672. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  3673. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3674. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3675. } else if (type == .underline) {
  3676. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  3677. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3678. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3679. } else if (type == .strikeOut) {
  3680. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  3681. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3682. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3683. } else if (type == .ink) {
  3684. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  3685. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3686. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3687. } else if (type == .freeText) {
  3688. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  3689. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3690. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3691. } else if (type == .anchored) {
  3692. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  3693. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3694. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3695. } else if (type == .square) {
  3696. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  3697. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3698. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3699. } else if (type == .link) {
  3700. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  3701. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3702. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3703. } else if (type == .stamp) {
  3704. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  3705. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3706. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3707. } else if (type == .signSignature) {
  3708. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  3709. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3710. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3711. } else if (type == .addText) {
  3712. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  3713. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3714. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3715. } else if (type == .addImage) {
  3716. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  3717. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3718. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3719. } else {
  3720. }
  3721. }
  3722. func trackEvent(toolMode mode: CToolMode) -> Void {
  3723. if (mode == .selectToolMode) {
  3724. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3725. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3726. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3727. } else if (mode == .moveToolMode) {
  3728. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3729. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3730. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3731. }
  3732. }
  3733. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3734. if (type == .word) {
  3735. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toWord", parameters: [
  3736. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3737. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3738. } else if (type == .excel) {
  3739. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toExcel", parameters: [
  3740. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3741. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3742. } else if (type == .ppt) {
  3743. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toPPT", parameters: [
  3744. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3745. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3746. } else if (type == .rtf) {
  3747. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toRTF", parameters: [
  3748. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3749. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3750. } else if (type == .csv) {
  3751. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toCSV", parameters: [
  3752. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3753. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3754. } else if (type == .html) {
  3755. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toHTML", parameters: [
  3756. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3757. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3758. } else if (type == .conversion_text) {
  3759. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toText", parameters: [
  3760. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3761. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3762. } else if (type == .conversion_image) {
  3763. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toImage", parameters: [
  3764. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3765. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3766. } else if (type == .compress) {
  3767. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Compress", parameters: [
  3768. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3769. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3770. } else if (type == .merge) {
  3771. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Merge", parameters: [
  3772. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3773. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3774. } else if (type == .secure) {
  3775. } else if (type == .crop) {
  3776. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Crop", parameters: [
  3777. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3778. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3779. }
  3780. }
  3781. func trackEvent_setPassword() -> Void {
  3782. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3783. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3784. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3785. }
  3786. func trackEvent_removePassword() -> Void {
  3787. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3788. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3789. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3790. }
  3791. }
  3792. extension KMMainViewController {
  3793. //文件对比
  3794. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  3795. let compareContentView = KMCompareContentView()
  3796. compareContentView.oldDocument = oldDocument
  3797. compareContentView.document = document
  3798. compareContentView.compareResults = results
  3799. compareContentView.saveHandle = { [unowned self] view in
  3800. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3801. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  3802. self.currentWindowController = saveController
  3803. saveController.cancelHandle = { [unowned self] controller in
  3804. self.view.window!.endSheet(controller.window!)
  3805. self.currentWindowController = nil
  3806. }
  3807. saveController.saveHandle = { [unowned self] controller, saveType in
  3808. let folderPath = controller.fileSaveFolderPath
  3809. if folderPath != nil {
  3810. if !FileManager.default.fileExists(atPath: folderPath) {
  3811. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  3812. }
  3813. var savePath: String
  3814. switch saveType {
  3815. case 0:
  3816. let filePath = oldDocument.documentURL.path
  3817. let fileName = filePath.deletingPathExtension.lastPathComponent
  3818. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3819. savePath = self.getValidFilePath(savePath)
  3820. oldDocument.write(to: URL(fileURLWithPath: savePath))
  3821. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3822. case 1:
  3823. let filePath = document.documentURL.path
  3824. let fileName = filePath.deletingPathExtension.lastPathComponent
  3825. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3826. savePath = self.getValidFilePath(savePath)
  3827. document.write(to: URL(fileURLWithPath: savePath))
  3828. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3829. case 2:
  3830. let filePath = oldDocument.documentURL.path
  3831. let fileName = filePath.deletingPathExtension.lastPathComponent
  3832. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  3833. savePath = self.getValidFilePath(savePath)
  3834. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  3835. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3836. default:
  3837. break
  3838. }
  3839. }
  3840. self.view.window!.endSheet(controller.window!)
  3841. self.currentWindowController = nil
  3842. }
  3843. NSWindow.currentWindow().beginSheet(saveController.window!)
  3844. }
  3845. }
  3846. compareContentView.closeHandle = { [unowned self] view in
  3847. // self.view.window!.endSheet(controller.window!)
  3848. view.removeFromSuperview()
  3849. }
  3850. self.PDFContendView.addSubview(compareContentView)
  3851. compareContentView.frame = self.PDFContendView.bounds
  3852. compareContentView.autoresizingMask = [.width,.height]
  3853. }
  3854. func getValidFilePath(_ oldPath: String) -> String {
  3855. let fileManager = FileManager.default
  3856. do {
  3857. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  3858. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  3859. return oldPath
  3860. }
  3861. var i = 1
  3862. var newPath = oldPath
  3863. while fileManager.fileExists(atPath: newPath) {
  3864. if fileType == FileAttributeType.typeDirectory.rawValue {
  3865. newPath = oldPath + "(\(i))"
  3866. } else {
  3867. let fileExtension = (oldPath as NSString).pathExtension
  3868. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3869. }
  3870. i += 1
  3871. }
  3872. return newPath
  3873. } catch {
  3874. print("Error getting file attributes: \(error)")
  3875. return oldPath
  3876. }
  3877. }
  3878. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  3879. let coveringView = KMCompareCoveringView()
  3880. coveringView.pdfDocument = pdfDocument
  3881. coveringView.closeHandle = { [unowned self] view in
  3882. view.removeFromSuperview()
  3883. }
  3884. coveringView.saveHandle = { [unowned self] view in
  3885. let savePanel = NSSavePanel()
  3886. savePanel.nameFieldStringValue = "untitled"
  3887. savePanel.allowedFileTypes = ["pdf"]
  3888. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  3889. if result == .OK {
  3890. pdfDocument.write(to: savePanel.url!)
  3891. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3892. }
  3893. }
  3894. }
  3895. self.PDFContendView.addSubview(coveringView)
  3896. coveringView.frame = self.PDFContendView.bounds
  3897. coveringView.autoresizingMask = [.width,.height]
  3898. }
  3899. }