KMMainViewController+Action.swift 120 KB

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