KMMainViewController+Action.swift 214 KB

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