KMMainViewController+Action.swift 154 KB

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