KMMainViewController+Action.swift 194 KB

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