KMMainViewController+Action.swift 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. }
  11. func removeSignatures(signatures:[CPDFSignature]) {
  12. for signature in signatures {
  13. self.listView.document.removeSignature(signature)
  14. }
  15. for i in 0..<self.listView.document.pageCount {
  16. guard let page = self.listView.document.page(at: i) else {
  17. continue
  18. }
  19. let annotations : [CPDFAnnotation] = page.annotations
  20. for j in 0..<annotations.count {
  21. let annotation = annotations[j]
  22. if annotation is CPDFSignatureWidgetAnnotation {
  23. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  24. }
  25. }
  26. }
  27. self.listView.setNeedsDisplayForVisiblePages()
  28. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  29. var mSignatures : [CPDFSignature] = []
  30. for sign in tSignatures {
  31. if sign.signers.count > 0 {
  32. mSignatures.append(sign)
  33. }
  34. }
  35. }
  36. //MARK: menu菜单
  37. func addText() -> NSMenuItem {
  38. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  39. return addTextItem
  40. }
  41. func addImage() -> NSMenuItem {
  42. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  43. return addImageItem
  44. }
  45. func replaceImageArea()->NSMenuItem {
  46. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  47. return replaceItem
  48. }
  49. func exportImageArea()->NSMenuItem {
  50. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  51. let menu = NSMenu()
  52. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  53. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(menuItemEditingClick_ExportImage), target: self, tag:1, at: 1)
  54. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 2)
  55. exportItem.submenu = menu
  56. return exportItem
  57. }
  58. func exportImageStampItem()->NSMenuItem {
  59. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  60. let menu = NSMenu()
  61. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  62. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  63. exportItem.submenu = menu
  64. return exportItem
  65. }
  66. func exportMenu() -> NSMenu {
  67. let menu = NSMenu()
  68. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  69. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  70. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  71. return menu
  72. }
  73. func cropMenu() -> NSMenu {
  74. let menu = NSMenu()
  75. return menu
  76. }
  77. func zoomSelectionMenuItem() -> NSMenuItem {
  78. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  79. return item
  80. }
  81. func enterAnnotationStype() -> NSMenuItem {
  82. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  83. let stypeMenu = NSMenu()
  84. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  85. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  86. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  87. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  88. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  89. stypeMenu.addItem(NSMenuItem.separator())
  90. }
  91. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  92. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  93. stypeMenu.addItem(NSMenuItem.separator())
  94. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  95. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  96. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  97. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  98. if viewManager.isPDFReadMode {
  99. } else {
  100. stypeMenu.addItem(NSMenuItem.separator())
  101. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  102. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  103. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  104. }
  105. stypItem.submenu = stypeMenu
  106. if self.listView.annotationType == .ink {
  107. stypeMenu.item(withTitle: NSLocalizedString("Freehand", comment: ""))?.state = .on
  108. } else if self.listView.annotationType == .freeText {
  109. stypeMenu.item(withTitle: NSLocalizedString("Text Note", comment: ""))?.state = .on
  110. } else if self.listView.annotationType == .anchored {
  111. stypeMenu.item(withTitle: NSLocalizedString("Anchored Note", comment: ""))?.state = .on
  112. } else if self.listView.annotationType == .square {
  113. stypeMenu.item(withTitle: NSLocalizedString("Rectangle", comment: ""))?.state = .on
  114. } else if self.listView.annotationType == .circle {
  115. stypeMenu.item(withTitle: NSLocalizedString("Circle", comment: ""))?.state = .on
  116. } else if self.listView.annotationType == .arrow {
  117. stypeMenu.item(withTitle: NSLocalizedString("Arrow", comment: ""))?.state = .on
  118. } else if self.listView.annotationType == .line {
  119. stypeMenu.item(withTitle: NSLocalizedString("Line", comment: ""))?.state = .on
  120. } else if self.listView.annotationType == .link {
  121. stypeMenu.item(at: 7)?.state = .on
  122. } else if self.listView.annotationType == .stamp {
  123. stypeMenu.item(withTitle: NSLocalizedString("Stamp", comment: ""))?.state = .on
  124. } else if self.listView.annotationType == .signSignature {
  125. stypeMenu.item(withTitle: NSLocalizedString("Signature", comment: ""))?.state = .on
  126. }
  127. return stypItem
  128. }
  129. func setAnnotationToolStype() -> NSMenuItem {
  130. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  131. let stypeMenu = NSMenu()
  132. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CTextToolMode.rawValue)
  133. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CMoveToolMode.rawValue)
  134. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CMagnifyToolMode.rawValue)
  135. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CSelectToolMode.rawValue)
  136. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  137. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  138. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  139. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  140. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.squiggly.rawValue)
  141. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  142. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  143. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  144. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  145. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  146. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  147. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  148. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  149. stypItem.submenu = stypeMenu
  150. return stypItem
  151. }
  152. func addReadModelStype() -> NSMenuItem {
  153. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openPDFReadMode), target: self)
  154. if viewManager.isPDFReadMode {
  155. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(exitPDFReadMode), target: self)
  156. }
  157. return stypItem
  158. }
  159. func addOutlineStype() -> NSMenuItem {
  160. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  161. return stypItem
  162. }
  163. func setTTSStype() -> NSMenuItem {
  164. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: nil , target: self)
  165. return stypItem
  166. }
  167. func setShareStype() -> NSMenuItem {
  168. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  169. var string = ""
  170. if listView.activeAnnotation != nil {
  171. string = self.listView.activeAnnotation?.contents ?? ""
  172. }
  173. if string.count < 1{
  174. string = self.listView.currentSelection?.string() ?? ""
  175. }
  176. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  177. return stypItem
  178. }
  179. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  180. var number = 0
  181. var indexN = 0
  182. guard str.count > 0 else {return (0, 0)}
  183. for i in 0...str.count - 1 {
  184. let c: unichar = (str as NSString).character(at: i)
  185. if (c >= 0x4E00) {
  186. number += 2
  187. }else {
  188. number += 1
  189. }
  190. if number > 56{
  191. indexN = i
  192. number = 100
  193. break
  194. }
  195. }
  196. return (number, indexN)
  197. }
  198. func setLookUpStype() -> NSMenuItem {
  199. guard let str = listView.currentSelection?.string() else {
  200. return NSMenuItem.separator()
  201. }//String(format: "Look Up %@", listView.currentSelection?.string() ?? "")
  202. let dic = numberOfChars(str)
  203. var newStr = str
  204. if dic.num == 100{
  205. newStr = str.prefix(dic.indexN) + "..."
  206. }
  207. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  208. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  209. return stypItem
  210. }
  211. func setSearchBaiduStype() -> NSMenuItem {
  212. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  213. return stypItem
  214. }
  215. func setCutStype() -> NSMenuItem {
  216. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  217. return stypItem
  218. }
  219. func setDeleteStype() -> NSMenuItem {
  220. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  221. return stypItem
  222. }
  223. func setColorsStype() -> NSMenuItem {
  224. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  225. return stypItem
  226. }
  227. func setLinesStype() -> NSMenuItem {
  228. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  229. return stypItem
  230. }
  231. func setEditNoteStype() -> NSMenuItem {
  232. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  233. return stypItem
  234. }
  235. func setRotateStype() -> NSMenuItem {
  236. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  237. let stypeMenu = NSMenu()
  238. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  239. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  240. stypItem.submenu = stypeMenu
  241. return stypItem
  242. }
  243. func setNextPageStype() -> NSMenuItem {
  244. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  245. stypItem.isEnabled = false
  246. if listView.canGoToNextPage() {
  247. stypItem.isEnabled = true
  248. }
  249. return stypItem
  250. }
  251. func setPreviousPageStype() -> NSMenuItem {
  252. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  253. stypItem.isEnabled = false
  254. if listView.canGoToPreviousPage() {
  255. stypItem.isEnabled = true
  256. }
  257. return stypItem
  258. }
  259. func setTranslateStype() -> NSMenuItem {
  260. let str = listView.currentSelection?.string() ?? ""//String(format: "Translate %@", listView.currentSelection?.string() ?? "")
  261. let dic = numberOfChars(str)
  262. var newStr = str
  263. if dic.num == 100{
  264. newStr = str.prefix(dic.indexN) + "..."
  265. }
  266. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  267. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  268. return stypItem
  269. }
  270. func setAutoScrollStype() -> NSMenuItem {
  271. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  272. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  273. return stypItem
  274. }
  275. func setSnapshotStype() -> NSMenuItem {
  276. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  277. let stypeMenu = NSMenu()
  278. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  279. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  280. stypItem.submenu = stypeMenu
  281. return stypItem
  282. }
  283. func setServicesStype() -> NSMenuItem {
  284. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  285. let stypeMenu = NSMenu()
  286. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  287. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  288. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  289. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  290. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  291. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  292. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  293. stypItem.submenu = stypeMenu
  294. return stypItem
  295. }
  296. func setCropStype() -> NSMenuItem {
  297. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  298. let stypeMenu = NSMenu()
  299. if NSIsEmptyRect(listView.selectionRect){
  300. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  301. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  302. }
  303. stypItem.submenu = stypeMenu
  304. return stypItem
  305. }
  306. func setAITranslateStype() -> NSMenuItem {
  307. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  308. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  309. return stypItem
  310. }
  311. func setAIProofreadStype() -> NSMenuItem {
  312. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  313. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  314. return stypItem
  315. }
  316. func setAIRewriteStype() -> NSMenuItem {
  317. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  318. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  319. return stypItem
  320. }
  321. func addHighlightLinksStype() -> NSMenuItem {
  322. let highlightLink = KMPreferenceManager.shared.highlightLinks
  323. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  324. if highlightLink {
  325. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  326. }
  327. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  328. return highlightLinksItem
  329. }
  330. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  331. if item == nil {
  332. return
  333. }
  334. let menu = NSMenu()
  335. item?.submenu = menu
  336. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  337. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  338. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  339. let wavyLine = NSMenuItem(title: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  340. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  341. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  342. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  343. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  344. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  345. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  346. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  347. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  348. if listView.currentSelection.selectionType() != .image {
  349. menu.insertItem(height, at: menu.items.count)
  350. menu.insertItem(underline, at: menu.items.count)
  351. menu.insertItem(strickout, at: menu.items.count)
  352. menu.insertItem(wavyLine, at: menu.items.count)
  353. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  354. }
  355. if viewManager.isPDFReadMode {
  356. } else {
  357. if listView.currentSelection.selectionType() != .image &&
  358. listView.currentSelection.selectionType() != .text {
  359. menu.insertItem(text, at: menu.items.count)
  360. menu.insertItem(note, at: menu.items.count)
  361. }
  362. }
  363. if viewManager.isPDFReadMode {
  364. } else {
  365. if listView.currentSelection.selectionType() != .image {
  366. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  367. menu.insertItem(rectangle, at: menu.items.count)
  368. menu.insertItem(oval, at: menu.items.count)
  369. }
  370. }
  371. if viewManager.isPDFReadMode {
  372. } else {
  373. if listView.currentSelection.selectionType() != .image &&
  374. listView.currentSelection.selectionType() != .text {
  375. menu.insertItem(line, at: menu.items.count)
  376. }
  377. }
  378. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  379. if viewManager.isPDFReadMode {
  380. } else {
  381. menu.insertItem(link, at: menu.items.count)
  382. }
  383. if viewManager.isPDFReadMode {
  384. } else {
  385. if listView.currentSelection.selectionType() != .image {
  386. menu.insertItem(outline, at: menu.items.count)
  387. }
  388. }
  389. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  390. if viewManager.isPDFReadMode {
  391. } else {
  392. if (listView.currentSelection.selectionType() != .image) {
  393. }
  394. }
  395. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  396. }
  397. func addBookmarkMenu() -> NSMenuItem {
  398. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  399. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  400. return bookMarkItem
  401. } else {
  402. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  403. return bookMarkItem
  404. }
  405. }
  406. func findStringMenu() -> NSMenuItem {
  407. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  408. menuItem.keyEquivalent = "f"
  409. return menuItem
  410. }
  411. func printingMenu() -> NSMenuItem {
  412. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  413. return menuItem
  414. }
  415. func fontSizes()->NSArray {
  416. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  417. }
  418. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  419. if interactionMode == .presentation {
  420. listView.goToPreviousPage(nil)
  421. return true
  422. }
  423. return false
  424. }
  425. func useNativeFullScreen() -> Bool {
  426. var isFull = false
  427. let sel = NSSelectorFromString("toggleFullscreen:")
  428. if NSWindow.instancesRespond(to: sel) && UserDefaults.standard.bool(forKey: "SKUseLegacyFullScreenKey"){
  429. isFull = true
  430. }
  431. return isFull
  432. }
  433. func forceSubwindowsOnTop(_ flag: Bool) {
  434. }
  435. //MARK: menuItem Action
  436. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  437. let color = listView.editingSelectionFontColor()
  438. let panel = NSColorPanel.shared
  439. panel.setTarget(self)
  440. panel.setAction(#selector(fontColorChangeAction))
  441. panel.orderFront(nil)
  442. panel.showsAlpha = false
  443. panel.color = color ?? NSColor.black
  444. }
  445. @objc func fontColorChangeAction(sender: NSColorPanel) {
  446. self.listView.setEditingSelectionFontColor(sender.color)
  447. }
  448. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  449. let fontSize = self.fontSizes().object(at: sender.tag)
  450. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  451. }
  452. @objc func addImageText(sender: NSMenuItem) {
  453. let event = NSApp.currentEvent
  454. let clickLocation = event?.locationInWindow
  455. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  456. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  457. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  458. point = point2
  459. if sender.tag == 0 {
  460. KMPrint("添加文字")
  461. } else if sender.tag == 1 {
  462. } else if sender.tag == 2 {
  463. KMPrint("粘贴")
  464. }
  465. }
  466. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  467. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  468. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  469. }
  470. }
  471. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  472. self.listView.exitCrop(with: self.listView.selectImageAreas)
  473. self.listView.cropAreas = nil
  474. self.listView.isEditImage = false
  475. }
  476. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  477. self.listView.resetCrop(with: self.listView.selectImageAreas)
  478. }
  479. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  480. }
  481. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  482. if self.listView.selectImageAreas == nil {
  483. return
  484. }
  485. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  486. let panel = NSOpenPanel()
  487. panel.allowsMultipleSelection = false
  488. panel.allowedFileTypes = ["png","jpg"]
  489. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  490. if response == .OK {
  491. let openPath = panel.url?.path
  492. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  493. if s {
  494. }
  495. }
  496. }
  497. }
  498. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  499. if self.listView.selectImageAreas == nil {
  500. return
  501. }
  502. let panel = NSSavePanel()
  503. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  504. panel.isExtensionHidden = true
  505. let response = panel.runModal()
  506. if response == .OK {
  507. let url = panel.url
  508. if FileManager.default.fileExists(atPath: url!.path) {
  509. try?FileManager.default.removeItem(atPath: url!.path)
  510. }
  511. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  512. if result {
  513. NSWorkspace.shared.activateFileViewerSelecting([url!])
  514. }
  515. }
  516. }
  517. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  518. }
  519. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  520. }
  521. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  522. }
  523. @objc func OpenItemAction(sender: NSMenuItem) {
  524. }
  525. @objc func customCropModel(sender: NSMenuItem) {
  526. }
  527. @objc func rotateRightAction(sender: NSMenuItem) {
  528. }
  529. @objc func rotateLeftAction(sender: NSMenuItem) {
  530. }
  531. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  532. self.listView.toolMode = .CNoteToolMode
  533. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  534. var model : KMToolbarViewType = .None
  535. switch sender.tag {
  536. case 0:
  537. identifier = KMDocumentAnnotationToolbarItemIdentifier
  538. model = .Annatiton
  539. case 1:
  540. identifier = KMToolbarMoveToolModeItemIdentifier
  541. model = .Move
  542. case 2:
  543. identifier = KMToolbarMagnifyToolModeItemIdentifier
  544. model = .Magnify
  545. case 3:
  546. identifier = KMToolbarSelectToolModeItemIdentifier
  547. model = .Select
  548. case 4:
  549. identifier = KMToolbarZoomToSelectionItemIdentifier
  550. model = .SelectZoom
  551. default:
  552. break
  553. }
  554. }
  555. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  556. var itemId: String?
  557. if sender.tag == CAnnotationType.highlight.rawValue {
  558. itemId = KMToolbarHighlightAnnotationItemIdentifier
  559. } else if sender.tag == CAnnotationType.underline.rawValue {
  560. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  561. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  562. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  563. } else if sender.tag == CAnnotationType.squiggly.rawValue {
  564. itemId = KMToolbarSquigglyAnnotationItemIdentifier
  565. } else if sender.tag == CAnnotationType.ink.rawValue {
  566. itemId = KMToolbarInkAnnotationItemIdentifier
  567. } else if sender.tag == CAnnotationType.freeText.rawValue {
  568. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  569. } else if sender.tag == CAnnotationType.anchored.rawValue {
  570. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  571. } else if sender.tag == CAnnotationType.square.rawValue {
  572. itemId = KMToolbarSquareAnnotationItemIdentifier
  573. } else if sender.tag == CAnnotationType.circle.rawValue {
  574. itemId = KMToolbarCircleAnnotationItemIdentifier
  575. } else if sender.tag == CAnnotationType.arrow.rawValue {
  576. itemId = KMToolbarArrowAnnotationItemIdentifier
  577. } else if sender.tag == CAnnotationType.line.rawValue {
  578. itemId = KMToolbarLineAnnotationItemIdentifier
  579. } else if sender.tag == CAnnotationType.link.rawValue {
  580. itemId = KMToolbarLinkAnnotationItemIdentifier
  581. }
  582. }
  583. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  584. var annotationType : CAnnotationType = .unkown
  585. switch sender.tag {
  586. case 0:
  587. annotationType = .highlight
  588. case 1:
  589. annotationType = .underline
  590. case 2:
  591. if sender.title == NSLocalizedString("Squiggly", comment: "") {
  592. annotationType = .squiggly
  593. } else {
  594. annotationType = .strikeOut
  595. }
  596. case 3:
  597. annotationType = .freeText
  598. case 4:
  599. annotationType = .anchored
  600. case 5:
  601. annotationType = .square
  602. case 6:
  603. annotationType = .circle
  604. case 7:
  605. annotationType = .line
  606. case 8:
  607. annotationType = .link
  608. case 9:
  609. return
  610. case 10:
  611. annotationType = .unkown
  612. default:
  613. break
  614. }
  615. if (annotationType != .link) {
  616. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  617. self.listView.currentSelection = nil;
  618. return
  619. }
  620. // link
  621. let selection = self.listView.currentSelection
  622. DispatchQueue.main.async {
  623. Task { @MainActor in
  624. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  625. self.listView.currentSelection = nil;
  626. if (annotation != nil) {
  627. self.listView.updateActiveAnnotations([annotation!])
  628. }
  629. }
  630. }
  631. }
  632. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  633. Task { @MainActor in
  634. let idx = sender.tag
  635. if idx == 10 {
  636. if IAPProductsManager.default().isAvailableAllFunction() == false {
  637. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  638. return
  639. }
  640. }
  641. var point = mouseRightMenuEvent?.locationInWindow
  642. if (point == nil) {
  643. point = NSZeroPoint
  644. }
  645. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  646. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  647. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  648. var annotation: CPDFAnnotation?
  649. if viewManager.isPDFReadMode {
  650. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  651. self.listView.toolMode = .CNoteToolMode
  652. }
  653. switch sender.tag {
  654. case 0:
  655. self.listView.annotationType = CAnnotationType.ink
  656. case 1:
  657. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  658. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  659. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  660. if ((annotation) != nil) {
  661. self.listView.updateActiveAnnotations([annotation!])
  662. self.listView.edit(annotation)
  663. }
  664. case 2:
  665. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  666. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  667. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  668. self.listView.edit(annotation)
  669. case 3:
  670. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  671. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  672. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  673. case 4:
  674. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  675. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  676. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  677. case 5:
  678. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  679. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  680. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  681. case 6:
  682. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  683. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  684. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  685. case 7:
  686. self.listView.annotationType = CAnnotationType.link
  687. toggleOpenRightSide()
  688. case 8:
  689. self.listView.annotationType = CAnnotationType.stamp
  690. toggleOpenRightSide()
  691. case 9:
  692. self.listView.annotationType = CAnnotationType.signSignature
  693. toggleOpenRightSide()
  694. default:
  695. break
  696. }
  697. } else {
  698. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  699. self.listView.toolMode = .CNoteToolMode
  700. }
  701. switch sender.tag {
  702. case 0:
  703. self.listView.toolMode = .CNoteToolMode
  704. self.listView.annotationType = CAnnotationType.ink
  705. case 1:
  706. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  707. if (pagePoint.x - defaultSize.width > 0){
  708. pagePoint.x -= defaultSize.width;
  709. }else{
  710. pagePoint.x = 0;
  711. }
  712. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  713. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  714. if ((annotation) != nil) {
  715. self.listView.edit(annotation)
  716. }
  717. case 2:
  718. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  719. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  720. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  721. self.listView.edit(annotation)
  722. case 3:
  723. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  724. if (pagePoint.x - defaultSize.width > 0){
  725. pagePoint.x -= defaultSize.width;
  726. }else{
  727. pagePoint.x = 0;
  728. }
  729. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  730. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  731. case 4:
  732. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  733. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  734. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  735. case 5:
  736. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  737. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  738. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  739. case 6:
  740. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  741. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  742. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  743. case 7:
  744. self.listView.annotationType = CAnnotationType.link
  745. toggleOpenRightSide()
  746. case 8:
  747. self.listView.annotationType = CAnnotationType.stamp
  748. toggleOpenRightSide()
  749. case 9:
  750. self.listView.annotationType = CAnnotationType.signSignature
  751. toggleOpenRightSide()
  752. case 10:
  753. self.addImgAnnotationToView(center: pagePoint)
  754. default:
  755. break
  756. }
  757. if annotation != nil{
  758. self.listView.activeAnnotations.removeAllObjects()
  759. var newAnnonations : [CPDFAnnotation] = []
  760. newAnnonations.append(annotation!)
  761. self.listView.updateActiveAnnotations(newAnnonations)
  762. }
  763. }
  764. }
  765. }
  766. func addImgAnnotationToView(center: NSPoint) {
  767. let accessoryCtr = KMImageAccessoryController()
  768. let openPanel = NSOpenPanel()
  769. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  770. openPanel.allowsMultipleSelection = false
  771. openPanel.accessoryView = accessoryCtr.view
  772. openPanel.isAccessoryViewDisclosed = true
  773. openPanel.beginSheetModal(for: self.view.window!) { result in
  774. if result == .OK {
  775. let fileURL = openPanel.urls.first
  776. let filePath = fileURL!.path
  777. if filePath.pathExtension == "pdf" {
  778. let pdf = CPDFDocument(url: fileURL)
  779. if pdf!.isEncrypted {
  780. NSSound.beep()
  781. return
  782. }
  783. }
  784. let img = NSImage(contentsOfFile: filePath)
  785. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  786. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  787. }
  788. }
  789. }
  790. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  791. if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  792. let index = self.listView.currentPageIndex
  793. self.listView.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  794. self.listView.setNeedsDisplayForVisiblePages()
  795. } else {
  796. self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  797. self.listView.setNeedsDisplayForVisiblePages()
  798. }
  799. self.listView.undoManager?.setActionName("")//添加undo事件就可删除
  800. if viewManager.isPDFReadMode {
  801. } else {
  802. }
  803. }
  804. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  805. }
  806. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  807. let rect = listView.currentSelectionRect()
  808. let page = listView.currentPage()
  809. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  810. copyPage.setBounds(rect, for: .cropBox)
  811. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  812. // 执行右键操作后,需要取消框选区域
  813. if self.listView.toolMode == .CSelectToolMode {
  814. objc_sync_enter(self)
  815. self.listView.selectionRect = NSZeroRect
  816. self.listView.selectionPageIndex = UInt(NSNotFound)
  817. objc_sync_exit(self)
  818. }
  819. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  820. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  821. if (result == .cancel) {
  822. return
  823. }
  824. // 解除权限
  825. self?.model.isSaveKeyChain = false
  826. self?.listView.document.unlock(withPassword: password)
  827. // 隐藏提示
  828. self?.hiddenSecureLimitTip()
  829. // 去打印
  830. KMPrintWindowController.printImage(image: image)
  831. }
  832. return
  833. }
  834. KMPrintWindowController.printImage(image: image)
  835. }
  836. // MARK: - Measure
  837. @objc func menuItemActionMeasureProperty(sender: NSMenuItem) {
  838. guard let anno = sender.representedObject as? CPDFAnnotation else {
  839. return
  840. }
  841. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  842. distanceMeasureInfoWindowController?.hideFloatingWindow()
  843. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  844. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  845. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  846. areaMeasureInfoWindowController?.hideFloatingWindow()
  847. }
  848. self.listView.updateActiveAnnotations([anno])
  849. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  850. self.listView.setNeedsDisplayForVisiblePages()
  851. }
  852. @objc func menuItemActionMeasureEditNote(sender: NSMenuItem) {
  853. guard let anno = sender.representedObject as? CPDFAnnotation else {
  854. return
  855. }
  856. self.listView.edit(anno)
  857. }
  858. @objc func menuItemActionMeasureSetting(sender: NSMenuItem) {
  859. guard let anno = sender.representedObject as? CPDFAnnotation else {
  860. return
  861. }
  862. self.listView.updateActiveAnnotations([anno])
  863. self.listView.setNeedsDisplayForVisiblePages()
  864. if let data = anno as? CPDFLineAnnotation, data.isMeasure {
  865. self.showMeasureDistanceSettingWindow(measureInfo: data.measureInfo)
  866. } else if let data = anno as? CPDFPolylineAnnotation {
  867. self.showMeasurePerimeterSettingWindow(measureInfo: data.measureInfo)
  868. } else if let data = anno as? CPDFPolygonAnnotation {
  869. self.showMeasureAreaSettingWindow(measureInfo: data.measureInfo)
  870. }
  871. }
  872. @objc func menuItemActionMeasureDelete(sender: NSMenuItem) {
  873. guard let anno = sender.representedObject as? CPDFAnnotation else {
  874. return
  875. }
  876. self.listView.remove(anno)
  877. }
  878. func showMeasureDistanceSettingWindow(measureInfo: CPDFDistanceMeasureInfo?, hideInfoWindow: Bool = true) {
  879. guard let mInfo = measureInfo else {
  880. return
  881. }
  882. let winC = CDistanceSettingWindowController(distanceMeasureInfo: mInfo)
  883. if hideInfoWindow {
  884. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  885. }
  886. winC.delegate = self
  887. winC.startModal("")
  888. }
  889. func showMeasurePerimeterSettingWindow(measureInfo: CPDFPerimeterMeasureInfo?, hideInfoWindow: Bool = true) {
  890. guard let mInfo = measureInfo else {
  891. return
  892. }
  893. let winC = CDistanceSettingWindowController(perimeterMeasureInfo: mInfo)
  894. if hideInfoWindow {
  895. self.perimeterMeasureInfoWindowController?.hideFloatingWindow()
  896. }
  897. winC.delegate = self
  898. winC.startModal("")
  899. }
  900. func showMeasureAreaSettingWindow(measureInfo: CPDFAreaMeasureInfo?, hideInfoWindow: Bool = true) {
  901. guard let mInfo = measureInfo else {
  902. return
  903. }
  904. let winC = CAreaSettingWindowController(measureInfo: mInfo)
  905. if hideInfoWindow {
  906. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  907. }
  908. winC.delegate = self
  909. winC.startModal("")
  910. }
  911. // MARK: - 幻灯片
  912. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  913. let view: NSView = self.view.window!.firstResponder as! NSView
  914. if view.isDescendant(of: pdfSplitView){
  915. self.view.window?.makeFirstResponder(nil)
  916. }
  917. self.mainWindow = self.view.window
  918. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  919. fullScreenWindow.interactionParent = self.view.window
  920. self.mainWindow?.delegate = nil
  921. fullScreenWindow.fadeInBlocking()
  922. self.browserWindowController?.window = fullScreenWindow
  923. fullScreenWindow.makeKey()
  924. let sel = NSSelectorFromString("setAnimationBehavior:")
  925. if self.mainWindow?.responds(to: sel) ?? false{
  926. self.mainWindow?.animationBehavior = .none
  927. }
  928. self.mainWindow?.orderOut(nil)
  929. if self.mainWindow?.responds(to: sel) ?? false{
  930. self.mainWindow?.animationBehavior = .default
  931. }
  932. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  933. fullScreenWindow.orderFront(nil)
  934. }
  935. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  936. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  937. return
  938. }
  939. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  940. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  941. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  942. fullScreenWindow.contentView?.addSubview(view)
  943. self.listView.layoutDocumentView()
  944. self.listView.requiresDisplay()
  945. fullScreenWindow.makeFirstResponder(self.listView)
  946. fullScreenWindow.recalculateKeyViewLoop()
  947. fullScreenWindow.delegate = self.browserWindowController
  948. fullScreenWindow.display()
  949. fadeWindow.fadeOut()
  950. }
  951. // MARK: Redact 【密文标记】
  952. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  953. self.listView.remove(self.listView.activeAnnotation)
  954. }
  955. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  956. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  957. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  958. self.view.window?.beginSheet(windowController.window!)
  959. self.currentWindowController = windowController
  960. windowController.itemClick = { [weak self] index, value in
  961. if (index == 1) { /// 取消
  962. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  963. self?.currentWindowController = nil
  964. return
  965. }
  966. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  967. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  968. annotaton.setBorderColor(windowController_redact.outsideColor)
  969. annotaton.setInteriorColor(windowController_redact.fillColor)
  970. if (windowController_redact.isOver) {
  971. annotaton.setFontColor(windowController_redact.fontColor)
  972. annotaton.setAlignment(windowController_redact.aligement)
  973. annotaton.setFont(windowController_redact.font)
  974. annotaton.setOverlayText(windowController_redact.overText)
  975. }
  976. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  977. self?.currentWindowController = nil
  978. }
  979. }
  980. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  981. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  982. return
  983. }
  984. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  985. let model = CPDFAnnotationModel(annotationType: .redact)
  986. model?.setColor(annotation.borderColor())
  987. model?.setInteriorColor(annotation.interiorColor())
  988. let overlayText: String = annotation.overlayText()
  989. if (overlayText.isEmpty) {
  990. model?.setIsOverlayText(false)
  991. } else {
  992. model?.setIsOverlayText(true)
  993. model?.setOverlayText(overlayText)
  994. model?.setFontColor(annotation.fontColor())
  995. model?.setAlignment(annotation.alignment())
  996. model?.setFontName(annotation.font().fontName)
  997. model?.setFontSize(annotation.font().pointSize)
  998. }
  999. }
  1000. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1001. let anno = self.listView.activeAnnotation
  1002. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1003. return
  1004. }
  1005. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1006. windowController.pageCount = Int(self.listView.document?.pageCount ?? 0)
  1007. self.currentWindowController = windowController
  1008. self.view.window?.beginSheet(windowController.window!)
  1009. windowController.itemClick = { [weak self] index, value in
  1010. if (index == 1) {
  1011. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1012. self!.currentWindowController = nil
  1013. return
  1014. }
  1015. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1016. let pageType = windowController_mutilPageFlag.pageType
  1017. let pageString = windowController_mutilPageFlag.pageString
  1018. if (pageType == 4) { /// 自定义页面
  1019. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  1020. if (array.count == 0) {
  1021. let alert = NSAlert()
  1022. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1023. alert.runModal()
  1024. return
  1025. }
  1026. }
  1027. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1028. self!.currentWindowController = nil
  1029. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  1030. if (indexs.count == 0) {
  1031. return
  1032. }
  1033. for i in indexs {
  1034. let page: CPDFPage = (self?.listView.document?.page(at: UInt(i)))!
  1035. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1036. self?.listView.add(redactAnno, to: page)
  1037. }
  1038. }
  1039. }
  1040. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1041. self.exeRedactConfirm(.redactOne) {}
  1042. }
  1043. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1044. self.exeRedactConfirm(.eraserOne) {}
  1045. }
  1046. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1047. }
  1048. @objc func exportStampImage(sender:NSMenuItem) {
  1049. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) || (self.listView.selectImageAreas != nil) {
  1050. var image : NSImage = NSImage()
  1051. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1052. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1053. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1054. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1055. } else {
  1056. image = self.listView.selectImageAreas.thumbnailImage(with: CGSize(width: 1920, height: 1920)) ?? NSImage()
  1057. }
  1058. let data = image.tiffRepresentation
  1059. if sender.tag == 0 {
  1060. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1061. imageRep.size = image.size
  1062. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1063. let savePanel = NSSavePanel()
  1064. savePanel.allowedFileTypes = ["png"]
  1065. savePanel.beginSheetModal(for: self.view.window!) { response in
  1066. if (response != .OK) {
  1067. return
  1068. }
  1069. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1070. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1071. }
  1072. }
  1073. } else {
  1074. let pdfdocument = CPDFDocument()
  1075. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1076. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1077. pdfdocument?.km_insertPage(image.size, withImage: signatureImagePath!, at: 0)
  1078. let savePanel = NSSavePanel()
  1079. savePanel.allowedFileTypes = ["pdf"]
  1080. savePanel.beginSheetModal(for: self.view.window!) { response in
  1081. if (response != .OK) {
  1082. return
  1083. }
  1084. if pdfdocument!.write(to: savePanel.url!) {
  1085. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1086. }
  1087. }
  1088. }
  1089. }
  1090. }
  1091. }
  1092. @objc func exportCorpImage(sender:NSMenuItem) {
  1093. let rect = NSIntegralRect(listView.currentSelectionRect())
  1094. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1095. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1096. page.setBounds(rect, for: .cropBox)
  1097. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1098. let data = image.tiffRepresentation
  1099. guard let data = data else { return }
  1100. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1101. imageRep.size = rect.size
  1102. let savePanel = NSSavePanel()
  1103. switch sender.tag {
  1104. case 0:
  1105. savePanel.allowedFileTypes = ["png"]
  1106. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1107. savePanel.beginSheetModal(for: self.view.window!) { response in
  1108. if (response != .OK) {
  1109. return
  1110. }
  1111. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1112. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1113. }
  1114. }
  1115. case 1:
  1116. savePanel.allowedFileTypes = ["jpg"]
  1117. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1118. savePanel.beginSheetModal(for: self.view.window!) { response in
  1119. if (response != .OK) {
  1120. return
  1121. }
  1122. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1123. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1124. }
  1125. }
  1126. case 2:
  1127. savePanel.allowedFileTypes = ["pdf"]
  1128. let pdfdocument = CPDFDocument()
  1129. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1130. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1131. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1132. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1133. savePanel.beginSheetModal(for: self.view.window!) { response in
  1134. if (response != .OK) {
  1135. return
  1136. }
  1137. if pdfdocument!.write(to: savePanel.url!) {
  1138. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1139. }
  1140. }
  1141. }
  1142. default:
  1143. break
  1144. }
  1145. // 执行右键操作后,需要取消框选区域
  1146. if self.listView.toolMode == .CSelectToolMode {
  1147. objc_sync_enter(self)
  1148. self.listView.selectionRect = NSZeroRect
  1149. self.listView.selectionPageIndex = UInt(NSNotFound)
  1150. objc_sync_exit(self)
  1151. }
  1152. }
  1153. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1154. let rect = listView.currentSelectionRect()
  1155. let page = listView.currentPage()
  1156. if NSIsEmptyRect(rect) == false && page != nil {
  1157. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1158. var bounds = listView.bounds
  1159. var scale = 1.0
  1160. if isLegacy {
  1161. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1162. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1163. }
  1164. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1165. scale = NSHeight(bounds) / NSHeight(rect)
  1166. } else {
  1167. scale = NSWidth(bounds) / NSWidth(rect)
  1168. }
  1169. listView.setScaleFactor(scale, animated: false)
  1170. let scrollView = listView.scroll()
  1171. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1172. if ((scrollView?.hasVerticalScroller) != nil) {
  1173. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1174. }
  1175. if ((scrollView?.hasHorizontalScroller) != nil) {
  1176. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1177. }
  1178. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1179. scale = NSHeight(bounds) / NSHeight(rect)
  1180. } else {
  1181. scale = NSWidth(bounds) / NSWidth(rect)
  1182. }
  1183. listView.setScaleFactor(scale, animated: false)
  1184. }
  1185. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1186. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1187. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1188. };
  1189. }
  1190. // 执行右键操作后,需要取消框选区域
  1191. if self.listView.toolMode == .CSelectToolMode {
  1192. objc_sync_enter(self)
  1193. self.listView.selectionRect = NSZeroRect
  1194. self.listView.selectionPageIndex = UInt(NSNotFound)
  1195. objc_sync_exit(self)
  1196. }
  1197. }
  1198. private func cropPagesToRects(rects:NSPointerArray) {
  1199. }
  1200. //MARK: - action
  1201. // 开启/关闭左边栏
  1202. @objc func toggleLeftPane() -> Void {
  1203. self.model.leftPanelOpen = true
  1204. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1205. }
  1206. // 开启左边栏
  1207. @objc func openLeftPane() -> Void {
  1208. self.model.leftPanelOpen = true
  1209. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1210. }
  1211. // 关闭左边栏
  1212. @objc func closeLeftPane() -> Void {
  1213. self.model.leftPanelOpen = false
  1214. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1215. }
  1216. func rename(_ sender: NSNotification) -> Void {
  1217. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1218. return
  1219. }
  1220. let tabController = sender.object as? CTTabController
  1221. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  1222. if let doc = self.myDocument, doc.isDocumentEdited {
  1223. Task {
  1224. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  1225. if resp != .alertFirstButtonReturn { // 取消
  1226. return
  1227. }
  1228. doc.updateChangeCount(.changeCleared)
  1229. self.document?.write(to: doc.fileURL)
  1230. Task { @MainActor in
  1231. self._renameForSavePanel(tabController)
  1232. }
  1233. }
  1234. return
  1235. }
  1236. self._renameForSavePanel(tabController)
  1237. }
  1238. }
  1239. func savePdfAlertView() {
  1240. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  1241. return
  1242. }
  1243. AutoSaveManager.manager.isSaveNoti = true
  1244. var num = 0
  1245. if self.listView.document != nil{
  1246. num = Int(self.listView.document.pageCount)
  1247. }
  1248. if Thread.current.isMainThread {
  1249. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1250. } else {
  1251. DispatchQueue.main.async {
  1252. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1253. }
  1254. }
  1255. }
  1256. func savePdfFinishAlertView() {
  1257. if !AutoSaveManager.manager.isSaveNoti{
  1258. return
  1259. }
  1260. AutoSaveManager.manager.isSaveNoti = false
  1261. if Thread.current.isMainThread {
  1262. self.dismissProgressSheet()
  1263. } else {
  1264. DispatchQueue.main.async {
  1265. self.dismissProgressSheet()
  1266. }
  1267. }
  1268. }
  1269. private func _renameForSavePanel(_ tabC: CTTabController?) {
  1270. let outputSavePanel = NSSavePanel()
  1271. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1272. outputSavePanel.allowedFileTypes = ["pdf"]
  1273. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1274. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1275. let resp = outputSavePanel.runModal()
  1276. if resp == .OK {
  1277. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1278. let fileURL = pdfDocument?.documentURL
  1279. let fileManager = FileManager.default
  1280. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1281. var result = true
  1282. do {
  1283. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1284. } catch {
  1285. result = false
  1286. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1287. }
  1288. if (result) {
  1289. tabC?.title = outputSavePanel.url!.lastPathComponent
  1290. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1291. self.model.isSaveKeyChain = false
  1292. newPdfDocument.unlock(withPassword: self.document?.password)
  1293. if (newPdfDocument.pageCount > 0) {
  1294. self.setDocument = newPdfDocument
  1295. }
  1296. }
  1297. }
  1298. } else {
  1299. outputSavePanel.close()
  1300. }
  1301. }
  1302. func showInFinder(_ sender: Any) -> Void {
  1303. if sender is NSNotification {
  1304. let tabController = (sender as! NSNotification).object as? CTTabController
  1305. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  1306. if tabController?.title == path {
  1307. if let file = self.myDocument?.fileURL {
  1308. if FileManager.default.fileExists(atPath: file.path) {
  1309. NSWorkspace.shared.activateFileViewerSelecting([file])
  1310. }
  1311. }
  1312. }
  1313. } else {
  1314. guard let url = self.myDocument?.fileURL else { return }
  1315. let file: URL = url
  1316. if FileManager.default.fileExists(atPath: file.path) {
  1317. NSWorkspace.shared.activateFileViewerSelecting([file])
  1318. }
  1319. }
  1320. }
  1321. func closeTab(_ sender: NSNotification) -> Void {
  1322. }
  1323. @IBAction func toggleSplitPDF(_ sender: Any) {
  1324. }
  1325. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1326. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1327. KMPrint("转档窗口已显示")
  1328. return
  1329. }
  1330. var convertT: KMConvertType = .Word
  1331. var windowController: KMConvertBaseWindowController?
  1332. if (type == .word) { /// Word
  1333. convertT = .Word
  1334. windowController = KMConvertWordWindowController()
  1335. } else if (type == .excel) {
  1336. convertT = .Excel
  1337. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1338. if (type == .ppt) {
  1339. convertT = .PPT
  1340. } else if (type == .rtf) {
  1341. convertT = .RTF
  1342. } else if (type == .html) {
  1343. convertT = .HTML
  1344. } else if (type == .conversion_text) {
  1345. convertT = .Text
  1346. }
  1347. } else if (type == .csv) {
  1348. convertT = .CSV
  1349. } else if (type == .conversion_image) {
  1350. windowController = KMConvertImageWindowController()
  1351. convertT = .JPEG
  1352. } else if type == .json {
  1353. convertT = .Json
  1354. }
  1355. var url: URL?
  1356. if (documentUrl != nil) {
  1357. url = documentUrl
  1358. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1359. } else {
  1360. url = self.listView.document.documentURL
  1361. }
  1362. let model = KMDocumentModel(url: url!)
  1363. windowController?.documentModel = model
  1364. self.km_safe_beginSheet(windowC: windowController)
  1365. }
  1366. //MARK: 转档 -
  1367. func showAllConvertWindow(convertT: KMConvertType) {
  1368. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1369. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1370. var type: KMConvertWithPDFType = .WordAdvance
  1371. switch convertT {
  1372. case .Word:
  1373. break
  1374. case .Excel:
  1375. type = .Excel
  1376. case .PPT:
  1377. type = .PowerPoint
  1378. case .RTF:
  1379. type = .RTF
  1380. case .CSV:
  1381. type = .CSV
  1382. case .HTML:
  1383. type = .HTML
  1384. case .Text:
  1385. type = .Text
  1386. case .JPEG:
  1387. type = .JPEG
  1388. case .PNG:
  1389. type = .PNG
  1390. case .GIF:
  1391. type = .GIF
  1392. case .JPG:
  1393. type = .JPG
  1394. case .TIFF:
  1395. type = .TIFF
  1396. case .TGA:
  1397. type = .TGA
  1398. case .BMP:
  1399. type = .BMP
  1400. case .JP2:
  1401. type = .JPEG2000
  1402. case .AdvancedWord:
  1403. break
  1404. case .Json:
  1405. type = .Json
  1406. break
  1407. default:
  1408. break
  1409. }
  1410. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1411. var needShowHint = false
  1412. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  1413. needShowHint = true
  1414. } else {
  1415. var needContinue = false
  1416. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  1417. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  1418. let ss = self.document?.documentURL.path
  1419. if arr.contains(ss!) {
  1420. needContinue = false
  1421. }else {
  1422. needContinue = true
  1423. }
  1424. }else {
  1425. needContinue = true
  1426. }
  1427. if needContinue {
  1428. let ss = self.document?.documentURL.path
  1429. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  1430. file.password = document?.password ?? ""
  1431. KMBatchOperateManager.defaultManager.files?.append(file)
  1432. }
  1433. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  1434. batchWindowController.switchToConvertType(convertType: type)
  1435. }
  1436. batchWindowController.window?.makeKeyAndOrderFront(nil)
  1437. if needShowHint {
  1438. batchWindowController.showIsConvertingHint()
  1439. } else {
  1440. }
  1441. }
  1442. }
  1443. self.km_beginSheet(windowC: convertWC)
  1444. }
  1445. //MARK: 转档 - OCR
  1446. func showOCRWindow() {
  1447. if !IAPProductsManager.default().isAvailableAllFunction(){
  1448. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1449. winC?.showWindow(nil)
  1450. return
  1451. }
  1452. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  1453. com.currentIndexPage = self.listView.currentPageIndex
  1454. self.km_beginSheet(windowC: com)
  1455. }
  1456. // MARK: - 图片注释
  1457. @IBAction func imageAnnotation(_ sender: Any) {
  1458. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  1459. changeAnnotationMode(sender)
  1460. guard IAPProductsManager.default().isAvailableAllFunction() else {
  1461. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1462. return
  1463. }
  1464. let accessoryCtr = KMImageAccessoryController()
  1465. let openPanel = NSOpenPanel()
  1466. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1467. openPanel.allowsMultipleSelection = false
  1468. openPanel.accessoryView = accessoryCtr.view
  1469. openPanel.canSelectHiddenExtension = true
  1470. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  1471. if result == .OK {
  1472. guard let url = openPanel.url else {
  1473. return
  1474. }
  1475. let filePath = url.path
  1476. if filePath.pathExtension.lowercased() == "pdf" {
  1477. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  1478. NSSound.beep()
  1479. return
  1480. }
  1481. }
  1482. guard let image = NSImage(contentsOfFile: url.path) else {
  1483. let alert = NSAlert()
  1484. alert.alertStyle = .critical
  1485. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  1486. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  1487. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1488. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  1489. if response == .alertFirstButtonReturn {
  1490. // Handle cancel button clicked
  1491. }
  1492. }
  1493. return
  1494. }
  1495. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  1496. if isDamageImage {
  1497. let alert = NSAlert()
  1498. alert.alertStyle = .critical
  1499. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  1500. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  1501. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1502. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  1503. if response == .alertFirstButtonReturn {
  1504. // Handle cancel button clicked
  1505. }
  1506. }
  1507. return
  1508. }
  1509. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  1510. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  1511. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  1512. }
  1513. }
  1514. }
  1515. }
  1516. @IBAction func tableAnnotation(_ sender: Any) {
  1517. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  1518. changeAnnotationMode(sender)
  1519. guard IAPProductsManager.default().isAvailableAllFunction() else {
  1520. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1521. winC?.kEventName = "Reading_Table_BuyNow"
  1522. winC?.showWindow(nil)
  1523. return
  1524. }
  1525. listView.addAnnotationWithTable()
  1526. toggleOpenRightSide()
  1527. }
  1528. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  1529. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  1530. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  1531. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  1532. }
  1533. if let data = image.tiffRepresentation,
  1534. let imageRep = NSBitmapImageRep(data: data) {
  1535. imageRep.size = image.size
  1536. var imageData: Data?
  1537. if path.lowercased() == "png" {
  1538. imageData = imageRep.representation(using: .png, properties: [:])
  1539. } else {
  1540. imageData = imageRep.representation(using: .jpeg, properties: [:])
  1541. }
  1542. if let imageData = imageData {
  1543. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  1544. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  1545. return true
  1546. } else {
  1547. return false
  1548. }
  1549. }
  1550. }
  1551. return false
  1552. }
  1553. func tagString() -> String {
  1554. let dateFormatter = DateFormatter()
  1555. dateFormatter.dateFormat = "yyMMddHHmmss"
  1556. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  1557. }
  1558. func updateBackAndForwardButtonState() {
  1559. }
  1560. }
  1561. extension KMMainViewController {
  1562. func changeModelAction(mode: CToolMode) {
  1563. self.listView.toolMode = mode
  1564. if mode == .CEditPDFToolMode {
  1565. }
  1566. }
  1567. func changePDFViewZoomInAction() {
  1568. }
  1569. func changePDFViewZoomOutAction() {
  1570. }
  1571. func changePDFViewGotoNextPageAction() {
  1572. self.listView.km_goBack(nil)
  1573. if (self.listView.canGoToNextPage()) {
  1574. self.listView.goToNextPage(nil)
  1575. }
  1576. }
  1577. func changePDFViewGoToPreviousPageAction() {
  1578. if (self.listView.canGoToPreviousPage()) {
  1579. self.listView.goToPreviousPage(nil)
  1580. }
  1581. }
  1582. func changePDFViewGotoBackAction() {
  1583. self.listView.km_goBack(nil)
  1584. self.updateBackAndForwardButtonState()
  1585. }
  1586. func changePDFViewGoToForwardAction() {
  1587. self.listView.km_goForward(nil)
  1588. self.updateBackAndForwardButtonState()
  1589. }
  1590. func aiTranslationPDFFileAction() {
  1591. self.trackEvent_aiTranslate()
  1592. self._aiTranslationPDFFileAction()
  1593. }
  1594. private func _aiTranslationPDFFileAction() {
  1595. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  1596. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  1597. let alert = NSAlert()
  1598. alert.alertStyle = .critical
  1599. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  1600. alert.runModal()
  1601. return
  1602. } else if isExceedsLimit {
  1603. let alert = NSAlert()
  1604. alert.alertStyle = .critical
  1605. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  1606. alert.runModal()
  1607. return
  1608. }
  1609. let alert = NSAlert()
  1610. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  1611. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  1612. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1613. alert.beginSheetModal(for: view.window!) { [weak self] result in
  1614. if (result == .alertFirstButtonReturn) {
  1615. } else if result == .alertSecondButtonReturn {
  1616. return
  1617. }
  1618. }
  1619. }
  1620. func clickChildTool(type: KMToolbarType, index: Int) {
  1621. if (type == .secure) {
  1622. if (index == 1) {
  1623. self.trackEvent_setPassword()
  1624. } else if (index == 2) {
  1625. self.trackEvent_removePassword()
  1626. }
  1627. } else {
  1628. self.trackEvent(toolBarType: type)
  1629. }
  1630. Task { @MainActor in
  1631. if (type == .compress) { /// 压缩
  1632. if !self.documentAllowsEdit() {
  1633. return
  1634. }
  1635. if (self.needSaveDocument()) {
  1636. self.saveDocumentWithProgressAlert { [unowned self] params in
  1637. // self.showCompressWindow()
  1638. }
  1639. return
  1640. }
  1641. // self.showCompressWindow()
  1642. return
  1643. }
  1644. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  1645. if type == .conversion_imageToPDF {
  1646. Task {
  1647. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  1648. }
  1649. return
  1650. }
  1651. var identifier: String?
  1652. if (type == .word) { /// Word
  1653. identifier = KMToolbarConversionWordItemIdentifier
  1654. } else if (type == .excel) {
  1655. identifier = KMToolbarConversionExcelItemIdentifier
  1656. } else if (type == .ppt) {
  1657. identifier = KMToolbarConversionPPTItemIdentifier
  1658. } else if (type == .rtf) {
  1659. identifier = KMToolbarConversionRTFItemIdentifier
  1660. } else if (type == .html) {
  1661. identifier = KMToolbarConversionHTMLItemIdentifier
  1662. } else if (type == .conversion_text) {
  1663. identifier = KMToolbarConversionTextItemIdentifier
  1664. } else if (type == .csv) {
  1665. identifier = KMToolbarConversionCSVItemIdentifier
  1666. } else if (type == .conversion_image) {
  1667. identifier = KMToolbarConversionImageItemIdentifier
  1668. }
  1669. if (self.needSaveDocument()) {
  1670. self.saveDocumentWithProgressAlert { [unowned self] params in
  1671. self.showConvertWindow(type: type, identifier: identifier)
  1672. }
  1673. return
  1674. }
  1675. self.showConvertWindow(type: type, identifier: identifier)
  1676. return
  1677. }
  1678. if (type == .merge) { /// 合并
  1679. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  1680. if !self.documentAllowsEdit() {
  1681. return
  1682. }
  1683. if (self.needSaveDocument()) {
  1684. self.saveDocumentWithProgressAlert { [unowned self] params in
  1685. self.showMergeWindow(self.listView.document.password)
  1686. }
  1687. return
  1688. }
  1689. self.showMergeWindow(self.listView.document.password)
  1690. return
  1691. }
  1692. if (type == .bates || type == .headerAndFooter) {
  1693. if !IAPProductsManager.default().isAvailableAllFunction(){
  1694. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1695. if type == .headerAndFooter {
  1696. if index == 1 {
  1697. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  1698. } else if index == 2 {
  1699. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  1700. }
  1701. } else if type == .bates {
  1702. if index == 1 {
  1703. winC?.kEventName = "Reading_AddBates_BuyNow"
  1704. } else if index == 2 {
  1705. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  1706. }
  1707. }
  1708. winC?.showWindow(nil)
  1709. return
  1710. }
  1711. if !self.documentAllowsEdit() {
  1712. return
  1713. }
  1714. if (index == 1) {
  1715. var windowController: KMBaseWindowController = KMBaseWindowController()
  1716. if (type == .bates) {
  1717. } else if (type == .headerAndFooter) {
  1718. } else if (type == .background) {
  1719. } else if (type == .watermark) {
  1720. }
  1721. windowController.pdfDocument = self.listView.document
  1722. windowController.cancelAction = { [unowned self] controller in
  1723. self.view.window?.endSheet((self.currentWindowController.window)!)
  1724. self.currentWindowController = nil
  1725. }
  1726. self.currentWindowController = windowController
  1727. await self.view.window?.beginSheet(windowController.window!)
  1728. return
  1729. }
  1730. if (index == 1) { /// 取消
  1731. ///
  1732. toggleCloseRightSide()
  1733. return
  1734. } else if index == 3 {
  1735. let fpath = self.document?.documentURL?.path ?? ""
  1736. if type == .bates {
  1737. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  1738. } else {
  1739. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  1740. }
  1741. } else if index == 4 {
  1742. let fpath = self.document?.documentURL?.path ?? ""
  1743. if type == .bates {
  1744. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  1745. } else {
  1746. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  1747. }
  1748. } else if (index == 2) { //// 移除
  1749. if type == .headerAndFooter {
  1750. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  1751. let savePanel = NSSavePanel()
  1752. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1753. savePanel.allowedFileTypes = ["pdf"]
  1754. savePanel.accessoryView = savePanelAccessoryViewController.view
  1755. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  1756. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  1757. }
  1758. }
  1759. } else if type == .bates {
  1760. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  1761. let savePanel = NSSavePanel()
  1762. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1763. savePanel.allowedFileTypes = ["pdf"]
  1764. savePanel.accessoryView = savePanelAccessoryViewController.view
  1765. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  1766. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  1767. }
  1768. }
  1769. }
  1770. } else if (index == 2) { /// 应用
  1771. } else if index == 5 {
  1772. self.toggleOpenRightSide()
  1773. }
  1774. } else if (type == .redact) { /// 标记密文
  1775. if !IAPProductsManager.default().isAvailableAllFunction(){
  1776. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1777. return
  1778. }
  1779. if (index == 1) { /// 取消
  1780. if (self.model.hasAddRedact) {
  1781. let alert = NSAlert()
  1782. 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: "")
  1783. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  1784. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1785. let result = alert.runModal()
  1786. if (result == .alertFirstButtonReturn) {
  1787. self.listView.toolMode = .CMoveToolMode
  1788. }
  1789. return
  1790. }
  1791. self.listView.toolMode = .CMoveToolMode
  1792. return
  1793. }
  1794. if (index == 2) { /// 擦除
  1795. self.exeRedactConfirm(.eraserAll) {}
  1796. return
  1797. }
  1798. if (index == 3) { /// 应用
  1799. self.exeRedactConfirm(.redactAll) {}
  1800. return
  1801. }
  1802. if (index == 4) { /// 文本&图像
  1803. self.listView.toolMode = .CRedactToolMode
  1804. return
  1805. }
  1806. if (index == 5) { /// 页面
  1807. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  1808. await self.view.window?.beginSheet(windowController.window!)
  1809. self.currentWindowController = windowController
  1810. windowController.itemClick = { [weak self] index, value in
  1811. if (index == 1) {
  1812. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1813. self?.currentWindowController = nil
  1814. return
  1815. }
  1816. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  1817. let pageType = windowController_pageRange.pageType
  1818. let pageString = windowController_pageRange.pageString
  1819. if (pageType == 5) { /// 自定义页面
  1820. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  1821. if (array.count == 0) {
  1822. let alert = NSAlert()
  1823. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1824. alert.runModal()
  1825. return
  1826. }
  1827. }
  1828. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1829. self!.currentWindowController = nil
  1830. var indexs: IndexSet = []
  1831. if (pageType == 1) { /// 当前页面
  1832. indexs.insert((self?.listView.currentPageIndex)!)
  1833. } else {
  1834. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  1835. }
  1836. if (indexs.count == 0) {
  1837. return
  1838. }
  1839. for i in indexs {
  1840. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1841. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  1842. redactAnno.bounds = page.bounds
  1843. self?.listView.add(redactAnno, to: page)
  1844. }
  1845. }
  1846. return
  1847. }
  1848. } else if (type == .secure) { /// 安全
  1849. if (index == 1) { /// 设置密码
  1850. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1851. if !self.documentAllowsEdit() {
  1852. return
  1853. }
  1854. }
  1855. self.showSecureWindow(self.listView.document.documentURL)
  1856. return
  1857. } else if index == 2 {
  1858. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  1859. let alert = NSAlert()
  1860. alert.alertStyle = .warning
  1861. alert.messageText = NSLocalizedString("Warning", comment: "")
  1862. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1863. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  1864. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  1865. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  1866. if returnCode == .alertSecondButtonReturn {
  1867. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  1868. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  1869. if success {
  1870. self.document?.unlock(withPassword: resultPassword)
  1871. self.clickChildTool(type: .secure, index: 2)
  1872. }
  1873. }
  1874. }
  1875. }
  1876. }
  1877. } else {
  1878. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  1879. controller.pdfDocument = self.document
  1880. self.currentWindowController = controller
  1881. controller.batchAction = { [unowned self] controller, files in
  1882. self.view.window?.endSheet((self.currentWindowController.window)!)
  1883. self.currentWindowController = nil
  1884. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1885. if #available(macOS 10.13, *) {
  1886. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1887. } else {
  1888. baseWindowController.showWindow(nil)
  1889. }
  1890. let arr = NSMutableArray()
  1891. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  1892. file.password = document?.password ?? ""
  1893. arr.add(file)
  1894. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  1895. }
  1896. controller.cancelAction = { [unowned self] controller in
  1897. self.view.window?.endSheet((self.currentWindowController.window)!)
  1898. self.currentWindowController = nil
  1899. }
  1900. controller.doneAction = { [unowned self] controller in
  1901. self.view.window?.endSheet((self.currentWindowController.window)!)
  1902. self.currentWindowController = nil
  1903. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  1904. if success {
  1905. let savePanel = NSSavePanel()
  1906. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  1907. savePanel.allowedFileTypes = ["pdf"]
  1908. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  1909. guard result == .OK else { return }
  1910. /// 删除安全性设置
  1911. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1912. self.model.isSaveKeyChain = false
  1913. self.listView.document.unlock(withPassword: resultPassword)
  1914. }
  1915. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  1916. guard let document = document else { return }
  1917. document.unlock(withPassword: resultPassword)
  1918. let success = document.writeDecrypt(to: savePanel.url)
  1919. if success {
  1920. self.hiddenSecureLimitTip()
  1921. let tip = KMRemovePasswordResultTipView()
  1922. tip.result = .success
  1923. tip.showInView(superView: (self.listView.superview)!)
  1924. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  1925. } else {
  1926. self.hiddenSecureLimitTip()
  1927. let tip = KMRemovePasswordResultTipView()
  1928. tip.result = .failure
  1929. tip.showInView(superView: (self.listView.superview)!)
  1930. }
  1931. }
  1932. }
  1933. }
  1934. }
  1935. await NSWindow.currentWindow().beginSheet(controller.window!)
  1936. }
  1937. return
  1938. }
  1939. } else if type == .comparison {
  1940. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  1941. if !IAPProductsManager.default().isAvailableAllFunction(){
  1942. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1943. winC?.kEventName = "Reading_Compare_BuyNow"
  1944. winC?.showWindow(nil)
  1945. return
  1946. }
  1947. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  1948. self.currentWindowController = controller
  1949. controller.password = self.document?.password ?? ""
  1950. controller.filePath = (self.document?.documentURL.path)!
  1951. controller.cancelAction = { [unowned self] controller in
  1952. self.view.window?.endSheet((self.currentWindowController.window)!)
  1953. self.currentWindowController = nil
  1954. }
  1955. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  1956. self.view.window?.endSheet((self.currentWindowController.window)!)
  1957. self.currentWindowController = nil
  1958. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  1959. }
  1960. controller.coveringComplete = { [unowned self] controller, document in
  1961. self.view.window?.endSheet((self.currentWindowController.window)!)
  1962. self.currentWindowController = nil
  1963. self.openCoveringCompareVC(with: document)
  1964. }
  1965. if index == 1 {
  1966. controller.fileType = .content
  1967. } else {
  1968. controller.fileType = .coverting
  1969. }
  1970. await NSWindow.currentWindow().beginSheet(controller.window!)
  1971. } else if type == .watermark {
  1972. if !IAPProductsManager.default().isAvailableAllFunction(){
  1973. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1974. if index == 1 {
  1975. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  1976. } else if index == 2 {
  1977. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  1978. }
  1979. winC?.showWindow(nil)
  1980. return
  1981. }
  1982. if !self.documentAllowsEdit() {
  1983. return
  1984. }
  1985. if index == 1 {
  1986. } else if index == 2 {
  1987. let watermarks = self.listView.document.watermarks()
  1988. if (watermarks == nil || watermarks!.count <= 0) {
  1989. let alert = NSAlert()
  1990. alert.alertStyle = .warning
  1991. alert.messageText = NSLocalizedString("Could not find a removable watermark in this document. If you see a watermark, it was not added with PDF Reader Pro and therefore cannot be detected.", comment: "")
  1992. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  1993. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1994. alert.runModal()
  1995. return
  1996. }
  1997. let alert = NSAlert()
  1998. alert.alertStyle = .warning
  1999. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  2000. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2001. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2002. let result = alert.runModal()
  2003. if (result != .alertFirstButtonReturn) {
  2004. return
  2005. }
  2006. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2007. let savePanel = NSSavePanel()
  2008. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  2009. savePanel.allowedFileTypes = ["pdf"]
  2010. savePanel.accessoryView = savePanelAccessoryViewController.view
  2011. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2012. guard result == .OK else { return }
  2013. }
  2014. } else if index == 3 {
  2015. let fpath = self.document?.documentURL?.path ?? ""
  2016. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  2017. } else if index == 4 {
  2018. let fpath = self.document?.documentURL?.path ?? ""
  2019. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  2020. } else if index == 5 {
  2021. toggleOpenRightSide()
  2022. return
  2023. }
  2024. } else if type == .background {
  2025. if !IAPProductsManager.default().isAvailableAllFunction(){
  2026. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2027. if index == 1 {
  2028. winC?.kEventName = "Reading_AddBackground_BuyNow"
  2029. } else if index == 2 {
  2030. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  2031. }
  2032. winC?.showWindow(nil)
  2033. return
  2034. }
  2035. if !self.documentAllowsEdit() {
  2036. return
  2037. }
  2038. if index == 1 {
  2039. } else if index == 2 {
  2040. guard let document = self.document else { return }
  2041. if !document.allowsPrinting || !document.allowsCopying {
  2042. let alert = NSAlert()
  2043. alert.alertStyle = .critical
  2044. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2045. alert.runModal()
  2046. return
  2047. }
  2048. guard let documentURL = document.documentURL else { return }
  2049. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2050. let savePanel = NSSavePanel()
  2051. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  2052. savePanel.allowedFileTypes = ["pdf"]
  2053. savePanel.accessoryView = savePanelAccessoryViewController.view
  2054. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2055. guard result == .OK else { return }
  2056. }
  2057. } else if index == 3 {
  2058. let fpath = self.document?.documentURL?.path ?? ""
  2059. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  2060. } else if index == 4 {
  2061. let fpath = self.document?.documentURL?.path ?? ""
  2062. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  2063. } else if index == 5 {
  2064. toggleOpenRightSide()
  2065. return
  2066. }
  2067. } else if type == .measure {
  2068. if !IAPProductsManager.default().isAvailableAllFunction(){
  2069. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2070. winC?.kEventName = "Reading_Measure_BuyNow"
  2071. winC?.showWindow(nil)
  2072. return
  2073. }
  2074. if !self.documentAllowsEdit() {
  2075. return
  2076. }
  2077. self.listView.toolMode = .CNoteToolMode
  2078. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2079. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2080. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  2081. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2082. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2083. areaMeasureInfoWindowController?.hideFloatingWindow()
  2084. }
  2085. if distanceMeasureInfoWindowController == nil {
  2086. let measureInfo = CPDFDistanceMeasureInfo()
  2087. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2088. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  2089. distanceMeasureInfoWindowController?.delegate = self
  2090. }
  2091. if perimeterMeasureInfoWindowController == nil {
  2092. let measureInfo = CPDFPerimeterMeasureInfo()
  2093. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2094. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  2095. perimeterMeasureInfoWindowController?.delegate = self
  2096. }
  2097. if areaMeasureInfoWindowController == nil {
  2098. let measureInfo = CPDFAreaMeasureInfo()
  2099. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2100. areaMeasureInfoWindowController?.measureInfo = measureInfo
  2101. areaMeasureInfoWindowController?.delegate = self
  2102. }
  2103. if index == 1 {
  2104. self.listView.annotationType = .measureLine
  2105. let winW: CGFloat = 300
  2106. let rightW: CGFloat = 270
  2107. var winFrame = self.view.window?.frame ?? .zero
  2108. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2109. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2110. distanceMeasureInfoWindowController?.showWindow(nil)
  2111. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2112. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2113. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2114. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2115. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2116. self.trackEvent(toolMode: .CNoteToolMode)
  2117. } else if index == 2 {
  2118. self.listView.annotationType = .measurePolyLine
  2119. let winW: CGFloat = 300
  2120. let rightW: CGFloat = 270
  2121. var winFrame = self.view.window?.frame ?? .zero
  2122. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2123. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2124. perimeterMeasureInfoWindowController?.showWindow(nil)
  2125. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2126. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2127. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2128. self.trackEvent(toolMode: .CNoteToolMode)
  2129. } else if index == 3 {
  2130. self.listView.annotationType = .measurePolyGon
  2131. let winW: CGFloat = 300
  2132. let rightW: CGFloat = 270
  2133. var winFrame = self.view.window?.frame ?? .zero
  2134. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2135. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2136. areaMeasureInfoWindowController?.showWindow(nil)
  2137. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2138. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2139. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2140. self.trackEvent(toolMode: .CNoteToolMode)
  2141. } else if index == 4 {
  2142. self.listView.annotationType = .measureSquare
  2143. let winW: CGFloat = 300
  2144. let rightW: CGFloat = 270
  2145. var winFrame = self.view.window?.frame ?? .zero
  2146. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2147. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2148. areaMeasureInfoWindowController?.showWindow(nil)
  2149. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2150. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2151. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2152. self.trackEvent(toolMode: .CNoteToolMode)
  2153. } else {
  2154. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  2155. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2156. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  2157. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2158. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  2159. areaMeasureInfoWindowController?.hideFloatingWindow()
  2160. }
  2161. }
  2162. toggleOpenRightSide()
  2163. }
  2164. }
  2165. }
  2166. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  2167. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2168. var array: [KMBatchOperateFile] = []
  2169. for fpath in filepaths ?? [] {
  2170. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  2171. array.append(batchOperateFile)
  2172. }
  2173. batchWindowController.switchToOperateType(type, files: array)
  2174. batchWindowController.window?.makeKeyAndOrderFront("")
  2175. }
  2176. func openNewWindowAlertWindow() {
  2177. var needShowChooseWindow = false
  2178. //#if VERSION_FREE
  2179. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  2180. needShowChooseWindow = true
  2181. }
  2182. //#endif
  2183. if needShowChooseWindow {
  2184. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  2185. if preferenceNoteShow {
  2186. menuItemAction_newTagPageToNewWindow("")
  2187. } else {
  2188. if !KMDataManager.default.isTabbingWin{
  2189. KMDataManager.default.isTabbingWin = true
  2190. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  2191. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  2192. KMDataManager.default.isTabbingWin = false
  2193. if continueOrNot {
  2194. self?.reopenDocument(forPaths: [])
  2195. } else {
  2196. }
  2197. }
  2198. self.km_beginSheet(windowC: tabbingWin)
  2199. }
  2200. }
  2201. }else{
  2202. handleTabbingLogic()
  2203. }
  2204. }
  2205. func reopenDocument(forPaths paths: [String]) -> Void {
  2206. let browser = KMBrowser.init() as KMBrowser
  2207. browser.windowController = KMBrowserWindowController.init(browser: browser)
  2208. browser.addHomeTabContents()
  2209. browser.windowController.showWindow(self)
  2210. }
  2211. func handleTabbingLogic() {
  2212. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  2213. }
  2214. func convertToImg(index: Int) {
  2215. var convertT: KMConvertType = .JPEG
  2216. switch index {
  2217. case 7:
  2218. convertT = .JPEG
  2219. case 8:
  2220. convertT = .JPG
  2221. case 9:
  2222. convertT = .PNG
  2223. case 10:
  2224. convertT = .GIF
  2225. case 11:
  2226. convertT = .TIFF
  2227. case 12:
  2228. convertT = .TGA
  2229. case 13:
  2230. convertT = .BMP
  2231. default:
  2232. convertT = .JPEG
  2233. }
  2234. showAllConvertWindow(convertT: convertT)
  2235. }
  2236. }
  2237. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  2238. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  2239. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2240. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  2241. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2242. distanceSettingWC.delegate = self
  2243. distanceSettingWC.startModal("")
  2244. }
  2245. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2246. }
  2247. }
  2248. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  2249. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  2250. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  2251. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  2252. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2253. distanceSettingWC.delegate = self
  2254. distanceSettingWC.startModal("")
  2255. }
  2256. }
  2257. // MARK: CAreaMeasureInfoWindowControllerDelegate
  2258. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  2259. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  2260. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  2261. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  2262. areaSettingWC.delegate = self
  2263. areaSettingWC.startModal("")
  2264. }
  2265. }
  2266. // MARK: CDistanceSettingWindowControllerDelegate
  2267. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  2268. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  2269. if distanceMeasureInfo != nil {
  2270. if self.listView.activeAnnotations.count > 0 {
  2271. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  2272. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  2273. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2274. }
  2275. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  2276. } else {
  2277. distanceMeasureInfo?.leadLength = 0
  2278. self.listView.distanceMeasureInfo = distanceMeasureInfo
  2279. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  2280. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2281. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2282. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2283. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2284. }
  2285. if let data = self.listView.activeAnnotation {
  2286. }
  2287. }
  2288. self.distanceMeasureInfoWindowController?.showWindow(self)
  2289. }
  2290. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  2291. if perimeterMeasureInfo != nil {
  2292. if self.listView.activeAnnotations.count > 0 {
  2293. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  2294. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  2295. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2296. }
  2297. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  2298. } else {
  2299. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  2300. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  2301. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2302. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2303. }
  2304. if let data = self.listView.activeAnnotation {
  2305. }
  2306. }
  2307. self.perimeterMeasureInfoWindowController?.showWindow(self)
  2308. }
  2309. }
  2310. // MARK: CAreaSettingWindowControllerDelegate
  2311. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  2312. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  2313. if self.listView.annotationType == .measureSquare && self.listView.toolMode == .CNoteToolMode {
  2314. if measureInfo != nil {
  2315. if self.listView.activeAnnotations.count > 0 {
  2316. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2317. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2318. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2319. }
  2320. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2321. } else {
  2322. self.listView.squareAreaMeasureInfo = measureInfo
  2323. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  2324. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2325. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2326. }
  2327. }
  2328. self.areaMeasureInfoWindowController?.showWindow(self)
  2329. } else if self.listView.annotationType == .measurePolyGon && self.listView.toolMode == .CNoteToolMode {
  2330. if measureInfo != nil {
  2331. if self.listView.activeAnnotations.count > 0 {
  2332. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2333. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2334. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2335. }
  2336. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2337. } else {
  2338. self.listView.polygonAreaMeasureInfo = measureInfo
  2339. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  2340. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2341. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2342. }
  2343. }
  2344. self.areaMeasureInfoWindowController?.showWindow(self)
  2345. } else {
  2346. if measureInfo != nil {
  2347. if self.listView.activeAnnotations.count > 0 {
  2348. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2349. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2350. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2351. }
  2352. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2353. }
  2354. }
  2355. self.areaMeasureInfoWindowController?.showWindow(self)
  2356. }
  2357. if measureInfo != nil {
  2358. if let data = self.listView.activeAnnotation {
  2359. }
  2360. }
  2361. }
  2362. }
  2363. //MARK: LeftSideViewController
  2364. extension KMMainViewController {
  2365. func leftSideViewCancelSelect() {
  2366. if self.listView.isEditing() == true {
  2367. if self.listView.editingAreas() != nil &&
  2368. self.listView.editingAreas().count != 0 {
  2369. let areas = self.listView.editingAreas().first
  2370. if areas is CPDFEditTextArea {
  2371. self.listView.clearEditingSelectCharItem()
  2372. self.listView.updateEditing([])
  2373. KMPrint("取消选中")
  2374. }
  2375. }
  2376. }
  2377. }
  2378. }
  2379. // MARK: - Analytics (埋点)
  2380. extension KMMainViewController {
  2381. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  2382. if (type == .Annatiton) {
  2383. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  2384. } else if (type == .editPDF) {
  2385. } else if (type == .Page) {
  2386. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  2387. } else if (type == .Conversion) {
  2388. } else if (type == .Tool) {
  2389. }
  2390. }
  2391. func trackEvent_aiTranslate() -> Void {
  2392. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  2393. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2394. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2395. }
  2396. func trackEvent_print() -> Void {
  2397. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  2398. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2399. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2400. }
  2401. func trackEvent_share() -> Void {
  2402. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  2403. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2404. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2405. }
  2406. func trackEvent_upgrade() -> Void {
  2407. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  2408. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2409. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2410. }
  2411. func trackEvent(annotationType type: CAnnotationType) -> Void {
  2412. if (type == .highlight) {
  2413. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  2414. } else if (type == .underline) {
  2415. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  2416. } else if (type == .strikeOut) {
  2417. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  2418. } else if (type == .ink) {
  2419. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  2420. } else if (type == .freeText) {
  2421. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  2422. } else if (type == .anchored) {
  2423. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  2424. } else if (type == .square) {
  2425. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  2426. } else if (type == .link) {
  2427. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  2428. } else if (type == .stamp) {
  2429. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  2430. } else if (type == .signSignature) {
  2431. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  2432. } else if (type == .circle) {
  2433. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  2434. } else if (type == .arrow) {
  2435. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  2436. } else if (type == .line) {
  2437. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  2438. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .text) {
  2439. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  2440. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  2441. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2442. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .image) {
  2443. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  2444. } else if (type == .textField) {
  2445. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  2446. } else if (type == .checkBox) {
  2447. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  2448. } else if (type == .radioButton) {
  2449. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  2450. } else if (type == .listMenu) {
  2451. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  2452. } else if (type == .comboBox) {
  2453. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  2454. } else if (type == .actionButton) {
  2455. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  2456. } else if (type == .actionButton) {
  2457. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  2458. } else if (type == .signature) {
  2459. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  2460. } else if (type == .squiggly) {
  2461. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  2462. } else if (type == .eraser) {
  2463. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  2464. }
  2465. }
  2466. func trackEvent(toolMode mode: CToolMode) -> Void {
  2467. if (mode == .CSelectToolMode) {
  2468. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  2469. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2470. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2471. } else if (mode == .CMoveToolMode) {
  2472. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  2473. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2474. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2475. } else if mode == .CNoteToolMode {
  2476. if CPDFListView.isMeasure(self.listView.annotationType) == true {
  2477. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  2478. }
  2479. }
  2480. }
  2481. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  2482. if (type == .word) {
  2483. } else if (type == .excel) {
  2484. } else if (type == .ppt) {
  2485. } else if (type == .rtf) {
  2486. } else if (type == .csv) {
  2487. } else if (type == .html) {
  2488. } else if (type == .conversion_text) {
  2489. } else if (type == .conversion_image) {
  2490. } else if (type == .compress) {
  2491. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  2492. } else if (type == .merge) {
  2493. } else if (type == .secure) {
  2494. } else if (type == .crop) {
  2495. } else if type == .json {
  2496. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  2497. }
  2498. }
  2499. func trackEvent_setPassword() -> Void {
  2500. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  2501. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2502. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2503. }
  2504. func trackEvent_removePassword() -> Void {
  2505. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  2506. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2507. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2508. }
  2509. func trackEvent_replace() -> Void {
  2510. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  2511. }
  2512. }
  2513. extension KMMainViewController {
  2514. //文件对比
  2515. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  2516. self.isCompareModel = true
  2517. let compareContentView = KMCompareContentView()
  2518. compareContentView.oldDocument = oldDocument
  2519. compareContentView.document = document
  2520. compareContentView.compareResults = results
  2521. compareContentView.saveHandle = { [unowned self] view in
  2522. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  2523. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  2524. self.currentWindowController = saveController
  2525. saveController.cancelHandle = { [unowned self] controller in
  2526. self.view.window!.endSheet(controller.window!)
  2527. self.currentWindowController = nil
  2528. }
  2529. saveController.saveHandle = { [unowned self] controller, saveType in
  2530. let folderPath = controller.fileSaveFolderPath
  2531. if folderPath != nil {
  2532. if !FileManager.default.fileExists(atPath: folderPath) {
  2533. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  2534. }
  2535. #if VERSION_DMG
  2536. #else
  2537. let url = URL(fileURLWithPath: folderPath)
  2538. let fileAccess = AppSandboxFileAccess()
  2539. fileAccess?.persistPermissionURL(url)
  2540. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  2541. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  2542. let urlString = url.path
  2543. let _url = URL(fileURLWithPath: urlString)
  2544. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  2545. }
  2546. #endif
  2547. var savePath: String
  2548. switch saveType {
  2549. case 0:
  2550. let filePath = oldDocument.documentURL.path
  2551. let fileName = filePath.deletingPathExtension.lastPathComponent
  2552. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  2553. savePath = self.getValidFilePath(savePath)
  2554. oldDocument.write(to: URL(fileURLWithPath: savePath))
  2555. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2556. case 1:
  2557. let filePath = document.documentURL.path
  2558. let fileName = filePath.deletingPathExtension.lastPathComponent
  2559. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  2560. savePath = self.getValidFilePath(savePath)
  2561. document.write(to: URL(fileURLWithPath: savePath))
  2562. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2563. case 2:
  2564. let filePath = oldDocument.documentURL.path
  2565. let fileName = filePath.deletingPathExtension.lastPathComponent
  2566. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  2567. savePath = self.getValidFilePath(savePath)
  2568. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  2569. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2570. default:
  2571. break
  2572. }
  2573. }
  2574. self.view.window!.endSheet(controller.window!)
  2575. self.currentWindowController = nil
  2576. }
  2577. NSWindow.currentWindow().beginSheet(saveController.window!)
  2578. }
  2579. }
  2580. compareContentView.closeHandle = { [unowned self] view in
  2581. self.isCompareModel = false
  2582. view.removeFromSuperview()
  2583. }
  2584. compareContentView.autoresizingMask = [.width,.height]
  2585. }
  2586. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  2587. self.isCompareModel = true
  2588. let coveringView = KMCompareCoveringView()
  2589. coveringView.pdfDocument = pdfDocument
  2590. coveringView.closeHandle = { [unowned self] view in
  2591. self.isCompareModel = false
  2592. view.removeFromSuperview()
  2593. }
  2594. coveringView.saveHandle = { [unowned self] view in
  2595. let savePanel = NSSavePanel()
  2596. savePanel.nameFieldStringValue = "untitled"
  2597. savePanel.allowedFileTypes = ["pdf"]
  2598. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  2599. if result == .OK {
  2600. pdfDocument.write(to: savePanel.url!)
  2601. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2602. }
  2603. }
  2604. }
  2605. coveringView.autoresizingMask = [.width,.height]
  2606. }
  2607. func getValidFilePath(_ oldPath: String) -> String {
  2608. let fileManager = FileManager.default
  2609. do {
  2610. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  2611. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  2612. return oldPath
  2613. }
  2614. var i = 1
  2615. var newPath = oldPath
  2616. while fileManager.fileExists(atPath: newPath) {
  2617. if fileType == FileAttributeType.typeDirectory.rawValue {
  2618. newPath = oldPath + "(\(i))"
  2619. } else {
  2620. let fileExtension = (oldPath as NSString).pathExtension
  2621. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  2622. }
  2623. i += 1
  2624. }
  2625. return newPath
  2626. } catch {
  2627. print("Error getting file attributes: \(error)")
  2628. return oldPath
  2629. }
  2630. }
  2631. }
  2632. extension KMMainViewController {
  2633. func documentAllowsEdit() -> Bool {
  2634. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  2635. let alert = NSAlert()
  2636. alert.alertStyle = .critical
  2637. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2638. alert.runModal()
  2639. return false
  2640. } else {
  2641. return true
  2642. }
  2643. }
  2644. func changeFont(_ sender: NSFontManager) {
  2645. KMPrint("changeFont ...")
  2646. if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
  2647. let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
  2648. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  2649. font = sender.convert(font!)
  2650. annotation.fontSize = font?.pointSize ?? 12
  2651. self.listView.commitEditAnnotationFreeText(annotation)
  2652. self.listView.setNeedsDisplay(annotation)
  2653. }
  2654. }
  2655. func currentSetup() -> [String: Any] {
  2656. var setup: [String: Any] = [:]
  2657. var point = NSZeroPoint
  2658. if listView == nil {
  2659. return setup
  2660. }
  2661. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  2662. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  2663. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  2664. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  2665. setup[KMMainModel.Key.pageIndex] = pageIndex
  2666. return setup
  2667. }
  2668. @objc func didAddContentViewNotification(_ sender: Notification) {
  2669. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  2670. return
  2671. }
  2672. if self.interactionMode == .presentation {
  2673. }
  2674. }
  2675. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  2676. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  2677. guard let anno = sender.object as? CPDFAnnotation else {
  2678. return
  2679. }
  2680. if anno.page?.document != self.listView.document {
  2681. return
  2682. }
  2683. }
  2684. // MARK: Split View
  2685. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  2686. let openPanel = NSOpenPanel()
  2687. openPanel.allowedFileTypes = ["pdf", "PDF"]
  2688. openPanel.allowsMultipleSelection = false
  2689. guard let mainWindow = NSApp.mainWindow else {
  2690. return
  2691. }
  2692. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  2693. if response == NSApplication.ModalResponse.OK {
  2694. guard let url = openPanel.url else {
  2695. return
  2696. }
  2697. if let document = CPDFDocument(url: url) {
  2698. replaceBlock(document.documentURL?.path ?? "")
  2699. } else {
  2700. let alert = NSAlert()
  2701. alert.alertStyle = .critical
  2702. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  2703. alert.runModal()
  2704. }
  2705. }
  2706. }
  2707. }
  2708. }