KMMainViewController+Action.swift 116 KB

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