KMMainViewController+Action.swift 123 KB

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