KMMainViewController+Action.swift 126 KB

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