KMMainViewController+Action.swift 117 KB

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