KMMainViewController+Action.swift 150 KB

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