KMMainViewController+Action.swift 116 KB

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