KMMainViewController+Action.swift 181 KB

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