KMMainViewController+Action.swift 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Office
  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("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 1)
  142. return menu
  143. }
  144. func cropMenu() -> NSMenu {
  145. let menu = NSMenu()
  146. menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  147. menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  148. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  149. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  150. return menu
  151. }
  152. func zoomSelectionMenuItem() -> NSMenuItem {
  153. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)!
  154. return item
  155. }
  156. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  157. let item = NSMenuItem(title: NSLocalizedString("Set Default Porpert", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)!
  158. return item
  159. }
  160. func enterAnnotationStype() -> NSMenuItem {
  161. let stypItem = NSMenuItem(title: NSLocalizedString("Add Annotation", comment: ""), action: nil, target: self)!
  162. let stypeMenu = NSMenu()
  163. stypeMenu.addItem(withTitle: NSLocalizedString("Ink", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  164. stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  165. stypeMenu.addItem(withTitle: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  166. stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  167. stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  168. stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  169. stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  170. stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  171. stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  172. stypeMenu.addItem(withTitle: NSLocalizedString("Signture", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  173. stypItem.submenu = stypeMenu
  174. if self.listView.annotationType == .ink {
  175. stypeMenu.item(at: 0)?.state = .on
  176. } else if self.listView.annotationType == .freeText {
  177. stypeMenu.item(at: 1)?.state = .on
  178. } else if self.listView.annotationType == .anchored {
  179. stypeMenu.item(at: 2)?.state = .on
  180. } else if self.listView.annotationType == .square {
  181. stypeMenu.item(at: 3)?.state = .on
  182. } else if self.listView.annotationType == .circle {
  183. stypeMenu.item(at: 4)?.state = .on
  184. } else if self.listView.annotationType == .arrow {
  185. stypeMenu.item(at: 5)?.state = .on
  186. } else if self.listView.annotationType == .line {
  187. stypeMenu.item(at: 6)?.state = .on
  188. } else if self.listView.annotationType == .link {
  189. stypeMenu.item(at: 7)?.state = .on
  190. } else if self.listView.annotationType == .stamp {
  191. stypeMenu.item(at: 8)?.state = .on
  192. } else if self.listView.annotationType == .signSignature {
  193. stypeMenu.item(at: 9)?.state = .on
  194. }
  195. return stypItem
  196. }
  197. func setAnnotationToolStype() -> NSMenuItem {
  198. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Model", comment: ""), action: nil, target: self)!
  199. let stypeMenu = NSMenu()
  200. stypeMenu.addItem(withTitle: NSLocalizedString("Default Tool", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 0)
  201. stypeMenu.addItem(withTitle: NSLocalizedString("Roll Tool", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 1)
  202. stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 2)
  203. stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 3)
  204. stypeMenu.addItem(withTitle: NSLocalizedString("Zoom Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  205. stypItem.submenu = stypeMenu
  206. if self.toolbarController.toolbarType == .Annatiton {
  207. stypeMenu.item(at: 0)?.state = .on
  208. } else if self.toolbarController.toolbarType == .Move {
  209. stypeMenu.item(at: 1)?.state = .on
  210. } else if self.toolbarController.toolbarType == .Magnify {
  211. stypeMenu.item(at: 2)?.state = .on
  212. } else if self.toolbarController.toolbarType == .Select {
  213. stypeMenu.item(at: 3)?.state = .on
  214. } else if self.toolbarController.toolbarType == .SelectZoom {
  215. stypeMenu.item(at: 4)?.state = .on
  216. }
  217. return stypItem
  218. }
  219. func addAnnotationForStyleMenu(menu:NSMenu) {
  220. if menu == nil {
  221. return
  222. }
  223. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)!
  224. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)!
  225. let strickout = NSMenuItem(title: NSLocalizedString("Strickout", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)!
  226. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)!
  227. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)!
  228. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)!
  229. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)!
  230. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)!
  231. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)!
  232. let outline = NSMenuItem(title: NSLocalizedString("Add outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)!
  233. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  234. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  235. if listView.currentSelection.selectionType() != .image {
  236. menu.insertItem(height, at: menu.items.count)
  237. menu.insertItem(underline, at: menu.items.count)
  238. menu.insertItem(strickout, at: menu.items.count)
  239. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  240. }
  241. menu.insertItem(text, at: menu.items.count)
  242. menu.insertItem(note, at: menu.items.count)
  243. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  244. menu.insertItem(rectangle, at: menu.items.count)
  245. menu.insertItem(oval, at: menu.items.count)
  246. menu.insertItem(line, at: menu.items.count)
  247. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  248. menu.insertItem(link, at: menu.items.count)
  249. menu.insertItem(outline, at: menu.items.count)
  250. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  251. }
  252. func addBookmarkMenu() -> NSMenuItem {
  253. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  254. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add BookMark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)!
  255. return bookMarkItem
  256. } else {
  257. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove BookMark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)!
  258. return bookMarkItem
  259. }
  260. }
  261. func findStringMenu() -> NSMenuItem {
  262. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)!
  263. return menuItem
  264. }
  265. func printingMenu() -> NSMenuItem {
  266. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), target: self)!
  267. return menuItem
  268. }
  269. func fontSizes()->NSArray {
  270. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  271. }
  272. //MARK: menuItem Action
  273. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  274. let color = listView.editingSelectionFontColor()
  275. let panel = NSColorPanel.shared
  276. panel.setTarget(self)
  277. panel.setAction(#selector(fontColorChangeAction))
  278. panel.orderFront(nil)
  279. panel.showsAlpha = false
  280. panel.color = color ?? NSColor.black
  281. }
  282. @objc func fontColorChangeAction(sender: NSColorPanel) {
  283. self.listView.setEditingSelectionFontColor(sender.color)
  284. }
  285. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  286. let fontSize = self.fontSizes().object(at: sender.tag)
  287. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  288. }
  289. @objc func addImageText(sender: NSMenuItem) {
  290. }
  291. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  292. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  293. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  294. }
  295. }
  296. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  297. if self.rightSideViewController.eidtPDFImageProperty != nil {
  298. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  299. } else {
  300. self.listView.exitCrop(with: self.listView.selectImageAreas)
  301. self.listView.cropAreas = nil
  302. self.listView.isEditImage = false
  303. }
  304. }
  305. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  306. if self.listView.selectImageAreas != nil {
  307. self.listView.isEditImage = true
  308. self.listView.enterCrop(with: self.listView.selectImageAreas)
  309. }
  310. }
  311. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  312. if self.listView.selectImageAreas == nil {
  313. return
  314. }
  315. let panel = NSOpenPanel()
  316. panel.allowsMultipleSelection = false
  317. panel.allowedFileTypes = ["png","jpg"]
  318. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  319. if response == .OK {
  320. let openPath = panel.url?.path
  321. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  322. if s {
  323. }
  324. }
  325. }
  326. }
  327. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  328. if self.listView.selectImageAreas == nil {
  329. return
  330. }
  331. let panel = NSSavePanel()
  332. panel.nameFieldStringValue = "[新文件].png"
  333. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  334. button.state = .on
  335. panel.accessoryView = button
  336. panel.isExtensionHidden = true
  337. let response = panel.runModal()
  338. if response == .OK {
  339. let url = panel.url
  340. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  341. if result {
  342. if button.state == .on { /// 开启文档
  343. NSWorkspace.shared.openFile(url!.path)
  344. } else {
  345. }
  346. }
  347. }
  348. }
  349. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  350. self.listView.toolMode = .noteToolMode
  351. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  352. var model : KMToolbarViewType = .None
  353. switch sender.tag {
  354. case 0:
  355. identifier = KMDocumentAnnotationToolbarItemIdentifier
  356. model = .Annatiton
  357. case 1:
  358. identifier = KMToolbarMoveToolModeItemIdentifier
  359. model = .Move
  360. case 2:
  361. identifier = KMToolbarMagnifyToolModeItemIdentifier
  362. model = .Magnify
  363. case 3:
  364. identifier = KMToolbarSelectToolModeItemIdentifier
  365. model = .Select
  366. case 4:
  367. identifier = KMToolbarZoomToSelectionItemIdentifier
  368. model = .SelectZoom
  369. default:
  370. break
  371. }
  372. let item : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  373. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item)
  374. }
  375. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  376. var annotationType : CAnnotationType = .unkown
  377. switch sender.tag {
  378. case 0:
  379. annotationType = .highlight
  380. case 1:
  381. annotationType = .underline
  382. case 2:
  383. annotationType = .strikeOut
  384. case 3:
  385. annotationType = .freeText
  386. case 4:
  387. annotationType = .anchored
  388. case 5:
  389. annotationType = .square
  390. case 6:
  391. annotationType = .circle
  392. case 7:
  393. annotationType = .line
  394. case 8:
  395. annotationType = .link
  396. case 9:
  397. // var newOutline : CPDFOutline = CPDFOutline()
  398. // newOutline.label = "11111111"
  399. // let des = self.listView.currentDestination
  400. // if "\(des?.point.x ?? 0)" != "nan" {
  401. // newOutline.destination = self.listView.currentDestination
  402. // } else {
  403. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  404. // newOutline.destination = destination
  405. // }
  406. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  407. // let parent = current.parent ?? CPDFOutline()
  408. // let index = current.index + 1
  409. // parent.insertChild(newOutline, at: index)
  410. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  411. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  412. }
  413. self.leftSideViewController.outlineViewController.addPDFOutlineCurrentSelections()
  414. return
  415. case 10:
  416. annotationType = .unkown
  417. default:
  418. break
  419. }
  420. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  421. }
  422. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  423. if(self.toolbarController.toolbarType == .None) {
  424. self.toolbarController.toolbarType = .Annatiton
  425. }
  426. self.listView.toolMode = .noteToolMode
  427. switch sender.tag {
  428. case 0:
  429. self.listView.annotationType = CAnnotationType.ink
  430. case 1:
  431. self.listView.annotationType = CAnnotationType.freeText
  432. case 2:
  433. self.listView.annotationType = CAnnotationType.anchored
  434. case 3:
  435. self.listView.annotationType = CAnnotationType.square
  436. case 4:
  437. self.listView.annotationType = CAnnotationType.square
  438. case 5:
  439. self.listView.annotationType = CAnnotationType.arrow
  440. case 6:
  441. self.listView.annotationType = CAnnotationType.line
  442. case 7:
  443. self.listView.annotationType = CAnnotationType.link
  444. case 8:
  445. self.listView.annotationType = CAnnotationType.stamp
  446. case 9:
  447. self.listView.annotationType = CAnnotationType.signSignature
  448. default:
  449. break
  450. }
  451. self.rightSideViewController.view.isHidden = false
  452. self.openRightPane()
  453. self.rightSideViewController.subViewType = .AnnotationProperts
  454. }
  455. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  456. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  457. let index = self.listView.currentPageIndex
  458. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  459. self.listView.setNeedsDisplayForVisiblePages()
  460. } else {
  461. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  462. self.listView.setNeedsDisplayForVisiblePages()
  463. }
  464. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  465. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  466. }
  467. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  468. if bookMark != nil {
  469. self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: bookMark!)
  470. } else {
  471. self.leftSideViewController.bookViewController.reloadData()
  472. }
  473. }
  474. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  475. self.leftSideViewController.refreshMethodType(methodType: .Search)
  476. }
  477. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  478. let rect = listView.currentSelectionRect()
  479. let page = listView.currentPage()
  480. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  481. copyPage.setBounds(rect, for: .cropBox)
  482. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  483. let pdfDocument : PDFDocument = PDFDocument()
  484. let newpage : PDFPage = PDFPage(image: image)!
  485. pdfDocument.insert(newpage, at: 0)
  486. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: KMPrintPageRange(type: .allPage, selectPages: []))
  487. }
  488. // MARK: Redact 【密文标记】
  489. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  490. self.listView.remove(self.listView.activeAnnotation)
  491. }
  492. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  493. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  494. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  495. self.view.window?.beginSheet(windowController.window!)
  496. self.currentWindowController = windowController
  497. windowController.itemClick = { [weak self] index, value in
  498. if (index == 1) { /// 取消
  499. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  500. self?.currentWindowController = nil
  501. return
  502. }
  503. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  504. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  505. annotaton.setBorderColor(windowController_redact.outsideColor)
  506. annotaton.setInteriorColor(windowController_redact.fillColor)
  507. if (windowController_redact.isOver) {
  508. annotaton.setFontColor(windowController_redact.fontColor)
  509. annotaton.setAlignment(windowController_redact.aligement)
  510. annotaton.setFont(windowController_redact.font)
  511. annotaton.setOverlayText(windowController_redact.overText)
  512. }
  513. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  514. self?.currentWindowController = nil
  515. }
  516. }
  517. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  518. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  519. return
  520. }
  521. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  522. let model = CPDFAnnotationModel(annotationType: .redact)
  523. model?.setColor(annotation.borderColor())
  524. model?.setInteriorColor(annotation.interiorColor())
  525. let overlayText: String = annotation.overlayText()
  526. if (overlayText.isEmpty) {
  527. model?.setIsOverlayText(false)
  528. } else {
  529. model?.setIsOverlayText(true)
  530. model?.setOverlayText(overlayText)
  531. model?.setFontColor(annotation.fontColor())
  532. model?.setAlignment(annotation.alignment())
  533. model?.setFontName(annotation.font().fontName)
  534. model?.setFontSize(annotation.font().pointSize)
  535. }
  536. }
  537. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  538. let anno = self.listView.activeAnnotation
  539. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  540. return
  541. }
  542. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  543. windowController.pageCount = Int(self.listView.document.pageCount)
  544. self.currentWindowController = windowController
  545. self.view.window?.beginSheet(windowController.window!)
  546. windowController.itemClick = { [weak self] index, value in
  547. if (index == 1) {
  548. self!.view.window?.endSheet(self!.currentWindowController.window!)
  549. self!.currentWindowController = nil
  550. return
  551. }
  552. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  553. let pageType = windowController_mutilPageFlag.pageType
  554. let pageString = windowController_mutilPageFlag.pageString
  555. if (pageType == 4) { /// 自定义页面
  556. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  557. if (array.count == 0) {
  558. let alert = NSAlert()
  559. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  560. alert.runModal()
  561. return
  562. }
  563. }
  564. self!.view.window?.endSheet(self!.currentWindowController.window!)
  565. self!.currentWindowController = nil
  566. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  567. if (indexs.count == 0) {
  568. return
  569. }
  570. for i in indexs {
  571. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  572. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  573. self?.listView.add(redactAnno, to: page)
  574. }
  575. }
  576. }
  577. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  578. self.exeRedactConfirm(.redactOne) {}
  579. }
  580. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  581. self.exeRedactConfirm(.eraserOne) {}
  582. }
  583. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  584. }
  585. @objc func exportStampImage(sender:NSMenuItem) {
  586. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  587. var image : NSImage = NSImage()
  588. if (listView.activeAnnotation is CPDFStampAnnotation) {
  589. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  590. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  591. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  592. }
  593. let data = image.tiffRepresentation
  594. if sender.tag == 0 {
  595. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  596. imageRep.size = image.size
  597. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  598. let savePanel = NSSavePanel()
  599. savePanel.allowedFileTypes = ["png"]
  600. savePanel.beginSheetModal(for: self.view.window!) { response in
  601. if (response != .OK) {
  602. return
  603. }
  604. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  605. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  606. }
  607. }
  608. } else {
  609. let pdfdocument = CPDFDocument()
  610. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  611. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  612. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  613. let savePanel = NSSavePanel()
  614. savePanel.allowedFileTypes = ["pdf"]
  615. savePanel.beginSheetModal(for: self.view.window!) { response in
  616. if (response != .OK) {
  617. return
  618. }
  619. if pdfdocument!.write(to: savePanel.url!) {
  620. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  621. }
  622. }
  623. }
  624. }
  625. }
  626. }
  627. @objc func exportCorpImage(sender:NSMenuItem) {
  628. let rect = NSIntegralRect(listView.currentSelectionRect())
  629. let page : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  630. page.setBounds(rect, for: .cropBox)
  631. let image = page.thumbnail(of: rect.size) ?? NSImage()
  632. let data = image.tiffRepresentation
  633. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  634. imageRep.size = rect.size
  635. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  636. let savePanel = NSSavePanel()
  637. switch sender.tag {
  638. case 0:
  639. savePanel.allowedFileTypes = ["png"]
  640. case 1:
  641. savePanel.allowedFileTypes = ["jpg"]
  642. case 2:
  643. savePanel.allowedFileTypes = ["pdf"]
  644. default:
  645. break
  646. }
  647. savePanel.beginSheetModal(for: self.view.window!) { response in
  648. if (response != .OK) {
  649. return
  650. }
  651. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  652. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  653. }
  654. }
  655. }
  656. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  657. let rect = listView.currentSelectionRect()
  658. let page = listView.currentPage()
  659. if NSIsEmptyRect(rect) == false && page != nil {
  660. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  661. var bounds = listView.bounds
  662. var scale = 1.0
  663. if isLegacy {
  664. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  665. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  666. }
  667. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  668. scale = NSHeight(bounds) / NSHeight(rect)
  669. } else {
  670. scale = NSWidth(bounds) / NSWidth(rect)
  671. }
  672. listView.setScaleFactor(scale, animated: true)
  673. let scrollView = listView.scroll()
  674. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  675. if ((scrollView?.hasVerticalScroller) != nil) {
  676. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  677. }
  678. if ((scrollView?.hasHorizontalScroller) != nil) {
  679. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  680. }
  681. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  682. scale = NSHeight(bounds) / NSHeight(rect)
  683. } else {
  684. scale = NSWidth(bounds) / NSWidth(rect)
  685. }
  686. listView.setScaleFactor(scale, animated: true)
  687. }
  688. listView.go(to: rect, on: page)
  689. }
  690. }
  691. @IBAction func autoCropAll(sender:NSMenuItem) {
  692. }
  693. private func cropPagesToRects(rects:NSPointerArray) {
  694. }
  695. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  696. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  697. switch sender.tag {
  698. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  699. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  700. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  701. case CAnnotationType.ink.rawValue:
  702. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  703. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  704. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  705. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  706. case CAnnotationType.freeText.rawValue:
  707. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  708. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  709. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  710. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  711. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  712. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  713. case CAnnotationType.anchored.rawValue:
  714. model.setColor((listView.activeAnnotation as! CPDFSignatureAnnotation).color)
  715. case CAnnotationType.square.rawValue:
  716. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  717. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  718. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  719. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  720. case CAnnotationType.circle.rawValue:
  721. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  722. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  723. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  724. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  725. default:
  726. break
  727. }
  728. }
  729. //MARK: action
  730. @objc func cropCurrentPage() {
  731. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  732. var page: CPDFPage?
  733. if ((self.listView.currentSelectionPage()) != nil) {
  734. page = self.listView.currentSelectionPage()
  735. } else {
  736. page = self.listView.currentPage()
  737. }
  738. if (NSIsEmptyRect(rect)) {
  739. rect = KMCropTools.getPageForegroundBox(page!)
  740. }
  741. let index: UInt = (page?.pageIndex())!
  742. cropPage(at: index, in: rect)
  743. }
  744. func cropPage(at index: UInt, in rect: NSRect) {
  745. let oldRect = self.listView.document.page(at: index)?.bounds(for: .cropBox)
  746. let undoManager = self.listView.undoManager
  747. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)!.cropPage(at: index, in: oldRect!)
  748. let page = self.listView.document.page(at: index)
  749. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox))!)
  750. page?.setBounds(newRect, for: .cropBox)
  751. /// 刷新预览视图
  752. self.listView.layoutDocumentView()
  753. self.listView.displayBox = .cropBox
  754. }
  755. @objc private func cropAllPage() {
  756. var size = NSZeroSize
  757. for i in 0 ..< self.listView.document.pageCount {
  758. let page = self.listView.document.page(at: i)
  759. var rect = KMCropTools.getPageForegroundBox(page!)
  760. size.width = fmax(size.width, NSWidth(rect))
  761. size.height = fmax(size.height, NSHeight(rect))
  762. }
  763. var rectArray: Array<NSRect> = []
  764. for i in 0 ..< self.listView.document.pageCount {
  765. let page = self.listView.document.page(at: i)
  766. var rect = KMCropTools.getPageForegroundBox(page!)
  767. var bounds: NSRect = (page?.bounds(for: .mediaBox))!
  768. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  769. rect.origin.x = rect.maxX-size.width
  770. }
  771. rect.origin.y = rect.maxY-size.height
  772. rect.size = size
  773. if (NSWidth(rect) > NSWidth(bounds)) {
  774. rect.size.width = NSWidth(bounds)
  775. }
  776. if (NSHeight(rect) > NSHeight(bounds)) {
  777. rect.size.height = NSHeight(bounds)
  778. }
  779. if (NSMinX(rect) < NSMinX(bounds)) {
  780. rect.origin.x = NSMinX(bounds)
  781. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  782. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  783. }
  784. if (NSMinY(rect) < NSMinY(bounds)) {
  785. rect.origin.y = NSMinY(bounds)
  786. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  787. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  788. }
  789. rectArray.append(rect)
  790. }
  791. cropPages(to: rectArray)
  792. }
  793. func cropPages(to rects: Array<NSRect>) {
  794. let currentPage = self.listView.currentPage()
  795. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  796. var oldRectArray: Array<NSRect> = []
  797. for i in 0 ..< self.listView.document.pageCount {
  798. let page = self.listView.document.page(at: i)
  799. var rect = NSIntersectionRect(rects[Int(i)], (page?.bounds(for: .mediaBox))!)
  800. let oldRect = page?.bounds(for: .cropBox)
  801. oldRectArray.append(oldRect!)
  802. page?.setBounds(rect, for: .cropBox)
  803. }
  804. let undoManager = self.listView.undoManager
  805. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  806. /// 刷新预览视图
  807. self.listView.layoutDocumentView()
  808. self.listView.displayBox = .cropBox
  809. self.listView.go(to: currentPage)
  810. self.listView.go(to: visibleRect, on: currentPage)
  811. }
  812. private func cropCustomArea() {
  813. self.listView.toolMode = .selectToolMode
  814. self.listView.autoScales = true
  815. self.listView.autoScales = false
  816. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  817. if (self.listView.displaysPageBreaks) {
  818. pageHeight += 8
  819. }
  820. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  821. // if (scaleFactor < self.preView.scaleFactor) {
  822. self.listView.scaleFactor = scaleFactor
  823. // }
  824. let tipView = KMCropTipView()
  825. tipView.setString(string: "请框选裁剪区域")
  826. tipView.frame = self.topTipBox.contentView!.frame
  827. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  828. self.addTopTip(tipView)
  829. tipView.enterAction = {
  830. () in
  831. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  832. if (NSIsEmptyRect(rect)) {
  833. return
  834. }
  835. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  836. self.view.window?.beginSheet(window.window!)
  837. self.cropSettingWindowController = window
  838. window.itemClick = { [self]
  839. (index: Int) in
  840. if (index == 1) { /// 取消
  841. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  842. self.cropSettingWindowController = nil
  843. return
  844. }
  845. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  846. let pageCount: Int = Int(self.listView.document.pageCount)
  847. var pages: Array<Int> = []
  848. if (pageRangeType == 0) { /// 当前页面
  849. pages.append(self.listView.currentPageIndex)
  850. } else if (pageRangeType == 1) { /// 全部页面
  851. for i in 0 ..< pageCount {
  852. pages.append(i)
  853. }
  854. } else if (pageRangeType == 2) { /// 奇数页面
  855. var string: String = ""
  856. for i in 0 ..< pageCount {
  857. if (i % 2 == 1) {
  858. continue
  859. }
  860. pages.append(i)
  861. }
  862. } else if (pageRangeType == 3) { /// 偶数页面
  863. var string: String = ""
  864. for i in 0 ..< pageCount {
  865. if (i % 2 == 0) {
  866. continue
  867. }
  868. pages.append(i)
  869. }
  870. } else { /// 自定义
  871. for i in self.cropSettingWindowController.pageRangePages {
  872. pages.append(i)
  873. }
  874. }
  875. if (pages.count < 0) {
  876. let alert = NSAlert()
  877. alert.messageText = "请选择页面"
  878. alert.runModal()
  879. return
  880. }
  881. var pageSize: NSSize = NSZeroSize
  882. if (self.cropSettingWindowController.pageSize == "None") {
  883. } else {
  884. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  885. }
  886. for i in pages {
  887. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  888. var rect = NSIntegralRect(self.listView.selectionRect)
  889. if (NSIsEmptyRect(rect)) {
  890. rect = KMCropTools.getPageForegroundBox(page)
  891. }
  892. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  893. page.setBounds(newRect, for: .cropBox)
  894. if (pageSize.width == 0 && pageSize.height == 0) {
  895. } else {
  896. // let tiffData = page.pdfListViewTIFFData(for: rect)
  897. let index: UInt = (page.pageIndex())
  898. // let newPage: CPDFPage = nil
  899. // self.listView.document.removePage(at: index)
  900. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  901. // let result = self.preView.document.insertPageObject(newPage, at: index)
  902. let result = self.listView.document.insertPage(pageSize, at: index)
  903. }
  904. }
  905. /// 保存到临时路径
  906. let toPath: String = self.listView.document.documentURL.path
  907. let documentPath = NSTemporaryDirectory()
  908. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  909. if (FileManager.default.fileExists(atPath: tempPath)) {
  910. try?FileManager.default.removeItem(atPath: tempPath)
  911. }
  912. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  913. if (result) {
  914. if (FileManager.default.fileExists(atPath: toPath)) {
  915. try?FileManager.default.removeItem(atPath: toPath)
  916. }
  917. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  918. } else {
  919. try?FileManager.default.removeItem(atPath: tempPath)
  920. }
  921. DispatchQueue.main.async {
  922. self.listView.toolMode = .textToolMode
  923. /// 刷新预览视图
  924. self.listView.layoutDocumentView()
  925. self.listView.displayBox = .cropBox
  926. }
  927. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  928. self.cropSettingWindowController = nil
  929. self.addTopTip(nil)
  930. }
  931. }
  932. }
  933. @objc private func shareDocument(sender:KMToolbarViewController) {
  934. var doucumentURL : URL = self.listView.document.documentURL
  935. if doucumentURL != nil {
  936. let docDir = NSTemporaryDirectory()
  937. let documentName : String = doucumentURL.path.lastPathComponent
  938. let path = docDir.stringByAppendingPathComponent(documentName)
  939. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  940. if writeSuccess == false {
  941. __NSBeep()
  942. return;
  943. }
  944. doucumentURL = URL(fileURLWithPath: path)
  945. }
  946. let array = [doucumentURL]
  947. let picker = NSSharingServicePicker.init(items: array)
  948. if sender.shareButton.window != nil {
  949. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  950. } else {
  951. 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)
  952. }
  953. }
  954. @objc private func shareFlatten(sender:KMToolbarViewController) {
  955. let document = self.listView.document ?? CPDFDocument()
  956. var path = document!.documentURL.path
  957. if path != nil {
  958. let docDir = NSTemporaryDirectory()
  959. let documentName : String = path.lastPathComponent
  960. path = docDir.stringByAppendingPathComponent(documentName)
  961. }
  962. let pathFolder = path.fileURL.deletingLastPathComponent().path
  963. var tfileName = path.deletingPathExtension.lastPathComponent
  964. let tStdFileSuffix = "_flatten"
  965. tfileName = tfileName + tStdFileSuffix + ".pdf"
  966. path = pathFolder + "/" + tfileName
  967. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  968. if success {
  969. let url = URL(fileURLWithPath: path)
  970. let picker = NSSharingServicePicker.init(items: [url])
  971. if sender.shareButton.window != nil {
  972. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  973. } else {
  974. 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)
  975. }
  976. }
  977. }
  978. @objc private func shareOriginalPDF(sender:KMToolbarViewController) {
  979. let document = self.listView.document ?? CPDFDocument()
  980. var path = document!.documentURL.path
  981. if path != nil {
  982. let docDir = NSTemporaryDirectory()
  983. let documentName : String = path.lastPathComponent
  984. path = docDir.stringByAppendingPathComponent(documentName)
  985. }
  986. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  987. if writeSuccess == false {
  988. __NSBeep()
  989. return;
  990. }
  991. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  992. for i in 0 ... newDocument.pageCount-1 {
  993. let page = newDocument.page(at: i)
  994. var annotations : [CPDFAnnotation] = []
  995. for annotation in page!.annotations {
  996. annotations.append(annotation)
  997. }
  998. for annotation in annotations {
  999. annotation.page.removeAnnotation(annotation)
  1000. }
  1001. }
  1002. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1003. if writeSuccess {
  1004. let url = URL(fileURLWithPath: path)
  1005. let picker = NSSharingServicePicker.init(items: [url])
  1006. if sender.shareButton.window != nil {
  1007. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1008. } else {
  1009. 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)
  1010. }
  1011. }
  1012. }
  1013. // 开启/关闭左边栏
  1014. @objc func toggleLeftPane() -> Void {
  1015. if lastLeftPanWidth >= functionWidth {
  1016. leftPanelOpen = true
  1017. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1018. } else {
  1019. leftPanelOpen = false
  1020. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1021. }
  1022. }
  1023. @objc func openLeftPane() -> Void {
  1024. leftPanelOpen = true
  1025. applyLeftSideWidth(panelWidth+functionWidth,rightSideWidth: lastRightPanWidth)
  1026. }
  1027. @objc func closeLeftPane() -> Void {
  1028. leftPanelOpen = false
  1029. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1030. }
  1031. // 开启/关闭右边栏
  1032. @objc func toggleRightPane() -> Void {
  1033. if lastRightPanWidth > 5 {
  1034. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1035. } else {
  1036. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1037. }
  1038. }
  1039. @objc func openRightPane() -> Void {
  1040. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1041. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1042. }
  1043. }
  1044. @objc func closeRightPane() -> Void {
  1045. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1046. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1047. }
  1048. }
  1049. func rename(_ sender: Any) -> Void {
  1050. let outputSavePanel = NSSavePanel()
  1051. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1052. outputSavePanel.allowedFileTypes = ["pdf"]
  1053. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.path)!
  1054. let result = outputSavePanel.runModal()
  1055. if result == .OK {
  1056. let success = (self.document?.write(to: outputSavePanel.url))! as Bool
  1057. if success {
  1058. let workspace = NSWorkspace.shared
  1059. workspace.activateFileViewerSelecting([outputSavePanel.url!])
  1060. }
  1061. }
  1062. }
  1063. func showInFinder(_ sender: Any) -> Void {
  1064. let file: URL = (self.myDocument?.fileURL)!
  1065. if FileManager.default.fileExists(atPath: file.path) {
  1066. NSWorkspace.shared.activateFileViewerSelecting([file])
  1067. }
  1068. }
  1069. // MARK: - Split View
  1070. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  1071. }
  1072. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  1073. if !isSinglePage && isHorizontal {
  1074. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  1075. }
  1076. if (!isSinglePage && !isHorizontal) {
  1077. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  1078. }
  1079. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  1080. }
  1081. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  1082. if isSinglePage {
  1083. pdfSplitView.dividerStyle = .thin
  1084. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  1085. } else {
  1086. pdfSplitView.dividerStyle = .paneSplitter
  1087. pdfSplitView.isVertical = !isHorizontal
  1088. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  1089. if secondaryPdfView.document != nil {
  1090. // secondaryPdfView.frame = pdfSplitSecondView.frame
  1091. // pdfSplitSecondView.contentView = secondaryPdfView
  1092. } else {
  1093. openSecondaryPdfView = KMSecondaryViewController.init()
  1094. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  1095. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  1096. openSecondaryPdfView?.delegate = self
  1097. }
  1098. }
  1099. }
  1100. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  1101. if (pdfSplitView.isVertical) {
  1102. return Float(NSWidth(rect))
  1103. } else {
  1104. return Float(NSHeight(rect))
  1105. }
  1106. }
  1107. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  1108. let document = CPDFDocument.init(url: url)
  1109. if document != nil {
  1110. secondaryPdfView.frame = pdfSplitSecondView.frame
  1111. pdfSplitSecondView.contentView = secondaryPdfView
  1112. secondaryPdfView.document = nil
  1113. secondaryPdfView.document = document
  1114. return true
  1115. } else {
  1116. return false
  1117. }
  1118. }
  1119. func updateNextAndPreViousButtonState() {
  1120. let item : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier))!
  1121. let toItem : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier))!
  1122. if self.listView.canGoToNextPage() {
  1123. item.unEnabled = false
  1124. } else {
  1125. item.unEnabled = true
  1126. }
  1127. if self.listView.canGoToPreviousPage() {
  1128. toItem.unEnabled = false
  1129. } else {
  1130. toItem.unEnabled = true
  1131. }
  1132. }
  1133. func updateZoomInOutButtonState() {
  1134. let item : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier))!
  1135. let toItem : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier))!
  1136. if self.listView.canZoomIn {
  1137. item.unEnabled = false
  1138. } else {
  1139. item.unEnabled = true
  1140. }
  1141. if self.listView.canZoomOut {
  1142. toItem.unEnabled = false
  1143. } else {
  1144. toItem.unEnabled = true
  1145. }
  1146. }
  1147. }
  1148. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  1149. func receivedFileUrl(_ url: URL!) {
  1150. let state = self.displaySecondaryPDFView(withUrl: url)
  1151. if !state {
  1152. let alert = NSAlert()
  1153. alert.alertStyle = .critical
  1154. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1155. alert.runModal()
  1156. return
  1157. }
  1158. }
  1159. }
  1160. extension KMMainViewController : KMMainToolbarControllerDelegate {
  1161. func changeModelAction(mode: CToolMode) {
  1162. self.listView.toolMode = mode
  1163. if mode == .editPDFToolMode {
  1164. self.childToolbarController.updateType(newType: .editPDF)
  1165. }
  1166. }
  1167. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  1168. switch selectedTag {
  1169. case 2:
  1170. self.listView.autoScales = !self.listView.autoScales
  1171. break
  1172. case 1:
  1173. if self.listView.scaleFactor != 1.0 {
  1174. self.listView.scaleFactor = 1.0
  1175. self.listView.autoScales = false
  1176. }
  1177. break
  1178. case 0:
  1179. self.listView.autoScales = true
  1180. self.listView.autoScales = false
  1181. break
  1182. case 3:
  1183. self.listView.scaleFactor = 0.1
  1184. break
  1185. case 4:
  1186. self.listView.scaleFactor = 0.25
  1187. break
  1188. case 5:
  1189. self.listView.scaleFactor = 0.5
  1190. break
  1191. case 6:
  1192. self.listView.scaleFactor = 0.75
  1193. break
  1194. case 7:
  1195. self.listView.scaleFactor = 1.0
  1196. break
  1197. case 8:
  1198. self.listView.scaleFactor = 1.5
  1199. break
  1200. case 9:
  1201. self.listView.scaleFactor = 2.0
  1202. break
  1203. case 10:
  1204. self.listView.scaleFactor = 4.0
  1205. break
  1206. case 11:
  1207. self.listView.scaleFactor = 6.0
  1208. break
  1209. case 12:
  1210. self.listView.scaleFactor = 10.0
  1211. break
  1212. default:
  1213. break
  1214. }
  1215. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1216. }
  1217. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  1218. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1219. if scale > 100 {
  1220. scale = 100
  1221. }
  1222. self.listView.scaleFactor = scale
  1223. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1224. }
  1225. func changePDFViewZoomInAction() {
  1226. self.listView.zoomIn(nil)
  1227. self.updateZoomInOutButtonState()
  1228. }
  1229. func changePDFViewZoomOutAction() {
  1230. self.listView.zoomOut(nil)
  1231. self.updateZoomInOutButtonState()
  1232. }
  1233. func changePDFViewGotoNextPageAction() {
  1234. self.listView.goToNextPage(nil)
  1235. self.updateNextAndPreViousButtonState()
  1236. }
  1237. func changePDFViewGoToPreviousPageAction() {
  1238. self.listView.goToPreviousPage(nil)
  1239. self.updateNextAndPreViousButtonState()
  1240. }
  1241. func showPDFViewPrintViewController() {
  1242. self.menuItemAnnotationClick_Print(sender: NSMenuItem())
  1243. }
  1244. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  1245. self.shareDocument(sender: viewController)
  1246. }
  1247. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  1248. self.shareFlatten(sender: viewController)
  1249. }
  1250. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  1251. self.shareOriginalPDF(sender: viewController)
  1252. }
  1253. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  1254. if(0 == selectedTag) {
  1255. self.documentAIViewController?.enteredIncreaseAllPage()
  1256. self.documentAIViewController?.updateToolState(false)
  1257. } else {
  1258. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  1259. self.documentAIViewController?.recognitionPartModel(with: .english)
  1260. self.documentAIViewController?.updateToolState(true)
  1261. }
  1262. // 0 : Scan 1:OCR Text
  1263. }
  1264. func mainToolDidClicked(_ toolController: KMToolbarController, _ type: KMToolbarViewType, _ item: KMToolBoxItem) {
  1265. if(type != .Page) {
  1266. if (hasEnterPageEdit()) {
  1267. self.exitPageEdit()
  1268. }
  1269. }
  1270. if(type != .ScanOCR) {
  1271. if ((self.documentAIViewController?.view.superview) != nil) {
  1272. self.listView.isHidden = false
  1273. self.documentAIViewController?.creatRecognitionDocument()
  1274. self.documentAIViewController?.view .removeFromSuperview()
  1275. self.documentAIViewController = nil;
  1276. self.listView.layoutDocumentView()
  1277. }
  1278. }
  1279. if (type == .Page) {
  1280. if (hasEnterPageEdit()) {
  1281. self.exitPageEdit()
  1282. } else {
  1283. self.enterPageEdit()
  1284. }
  1285. } else if(type == .ScanOCR) {
  1286. if((self.documentAIViewController?.view.superview) != nil) {
  1287. let alert = NSAlert()
  1288. alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  1289. alert.addButton(withTitle: "YES")
  1290. alert.addButton(withTitle: "NO")
  1291. let result = alert.runModal()
  1292. if (result == .alertFirstButtonReturn) { /// 取消
  1293. self.listView.isHidden = false
  1294. self.documentAIViewController?.creatRecognitionDocument()
  1295. self.documentAIViewController?.view .removeFromSuperview()
  1296. self.documentAIViewController = nil;
  1297. self.listView.layoutDocumentView()
  1298. } else {
  1299. self.toolbarController.toolbarType = .ScanOCR
  1300. }
  1301. } else {
  1302. self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  1303. self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  1304. self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  1305. self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  1306. self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  1307. }
  1308. }
  1309. }
  1310. func clickChildTool(type: KMToolbarType, index: Int) {
  1311. if (type == .compress) { /// 压缩
  1312. self.saveDocument()
  1313. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  1314. self.view.window?.beginSheet(windowController.window!)
  1315. self.currentWindowController = windowController
  1316. windowController.documentURL = self.listView.document.documentURL
  1317. windowController.password = self.listView.document.password
  1318. windowController.itemClick = { [weak self] (index: Int) -> () in
  1319. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1320. self?.currentWindowController = nil
  1321. if (index == 2) { /// 关闭
  1322. return
  1323. }
  1324. /// 批量压缩
  1325. KMBatchWindowController.openFile(self?.document?.documentURL, .Compression)
  1326. }
  1327. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  1328. if result {
  1329. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1330. self?.currentWindowController = nil
  1331. if openDocument {
  1332. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1333. } else {
  1334. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1335. }
  1336. } else {
  1337. let alert = NSAlert()
  1338. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1339. alert.runModal()
  1340. }
  1341. }
  1342. return
  1343. }
  1344. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  1345. var windowController: KMConvertBaseWindowController!
  1346. if (type == .word) { /// Word
  1347. windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  1348. } else if (type == .excel) {
  1349. windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  1350. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1351. windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  1352. if (type == .ppt) {
  1353. windowController.subType = 1
  1354. } else if (type == .rtf) {
  1355. windowController.subType = 2
  1356. } else if (type == .html) {
  1357. windowController.subType = 3
  1358. } else if (type == .conversion_text) {
  1359. windowController.subType = 4
  1360. }
  1361. } else if (type == .csv) {
  1362. windowController = KMConvertCSVWindowController(windowNibName: "KMConvertBaseWindowController")
  1363. } else if (type == .conversion_image) {
  1364. windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  1365. }
  1366. self.saveDocument()
  1367. let model = KMDocumentModel()
  1368. model.documentURL = self.listView.document.documentURL
  1369. if (self.listView.document.password != nil) {
  1370. model.password = self.listView.document.password
  1371. }
  1372. windowController.documentModel = model
  1373. windowController.itemClick = { [weak self] (index: Int) in
  1374. if (self!.currentWindowController == nil) {
  1375. return
  1376. }
  1377. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1378. self?.currentWindowController = nil
  1379. if (index == 2) { /// 关闭
  1380. return
  1381. }
  1382. /// 批量转档
  1383. KMBatchWindowController.openFile(self!.listView.document.documentURL, .ConvertPDF)
  1384. }
  1385. self.view.window?.beginSheet(windowController.window!)
  1386. self.currentWindowController = windowController
  1387. return
  1388. }
  1389. if (type == .merge) { /// 合并
  1390. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  1391. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { result , password in
  1392. if (result == .cancel) {
  1393. return
  1394. }
  1395. self.showMergeWindow(password)
  1396. }
  1397. return
  1398. }
  1399. self.showMergeWindow(self.listView.document.password)
  1400. return
  1401. }
  1402. if (type == .crop) {
  1403. if (index == 1) {
  1404. self.cropCurrentPage()
  1405. return
  1406. }
  1407. if (index == 2) {
  1408. self.cropAllPage()
  1409. return
  1410. }
  1411. //// 自定义裁剪区域
  1412. // self.cropCustomArea()
  1413. } else if (type == .bates || type == .headerAndFooter || type == .background || type == .watermark) {
  1414. if (index == 0) {
  1415. var controller: KMWatermarkAdjectivePreViewBaseController!
  1416. if (type == .bates) {
  1417. controller = KMBatesPreviewController()
  1418. } else if (type == .headerAndFooter) {
  1419. controller = KMHeaderFooterPreviewController()
  1420. } else if (type == .background) {
  1421. controller = KMBackgroundController()
  1422. } else if (type == .watermark) {
  1423. controller = KMWatermarkViewController()
  1424. }
  1425. controller.applyDocument = self.listView.document
  1426. controller.view.frame = self.view.bounds
  1427. controller.view.autoresizingMask = [.width, .height]
  1428. controller.documentURL = self.listView.document.documentURL
  1429. self.view.addSubview(controller.view)
  1430. self.addChild(controller)
  1431. controller.itemClick = { [weak self] index, param in
  1432. if (index == 0 || index == 1) { /// 取消 和 应用
  1433. var controller_watermarkAdjective_preView: KMWatermarkAdjectivePreViewBaseController?
  1434. for i in 0 ..< self!.children.count {
  1435. let vc: NSViewController = self!.children[self!.children.count-1-i]
  1436. if (vc.isKind(of: KMWatermarkAdjectivePreViewBaseController.self) == true) {
  1437. controller_watermarkAdjective_preView = vc as! KMWatermarkAdjectivePreViewBaseController
  1438. break
  1439. }
  1440. }
  1441. if (controller_watermarkAdjective_preView == nil) {
  1442. return
  1443. }
  1444. controller_watermarkAdjective_preView!.view.removeFromSuperview()
  1445. controller_watermarkAdjective_preView?.removeFromParent()
  1446. // if (index == 1) {
  1447. self?.listView.document = CPDFDocument(url: self?.listView.document.documentURL)
  1448. self?.listView.layoutDocumentView()
  1449. self?.listView.setNeedsDisplayForVisiblePages()
  1450. // }
  1451. return
  1452. }
  1453. }
  1454. return
  1455. }
  1456. if (index == 1) { /// 取消
  1457. self.toolbarController.exitWatermarkAdjective()
  1458. self.rightSideViewController.view.isHidden = true
  1459. self.rightSideViewController.subViewType = .None
  1460. self.closeRightPane()
  1461. return
  1462. }
  1463. if (index == 5) { /// 批量
  1464. return
  1465. }
  1466. if (index == 4) { //// 移除
  1467. if (type == .watermark) {
  1468. let watermarks = self.listView.document.watermarks()
  1469. if (watermarks == nil || watermarks!.count <= 0) {
  1470. let alert = NSAlert()
  1471. alert.alertStyle = .warning
  1472. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Office添加的,因此无法被检测到。", comment: "")
  1473. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  1474. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  1475. alert.runModal()
  1476. return
  1477. }
  1478. let alert = NSAlert()
  1479. alert.alertStyle = .warning
  1480. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  1481. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  1482. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  1483. let result = alert.runModal()
  1484. if (result != .alertFirstButtonReturn) {
  1485. return
  1486. }
  1487. }
  1488. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  1489. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  1490. result in
  1491. DispatchQueue.main.async {
  1492. self.listView.layoutDocumentView()
  1493. self.listView.setNeedsDisplayForVisiblePages()
  1494. }
  1495. if (result) {
  1496. let alert = NSAlert()
  1497. alert.alertStyle = .warning
  1498. alert.messageText = "成功"
  1499. alert.runModal()
  1500. } else {
  1501. let alert = NSAlert()
  1502. alert.alertStyle = .critical
  1503. alert.messageText = "失败"
  1504. alert.runModal()
  1505. }
  1506. }
  1507. return
  1508. }
  1509. if (index == 2) { /// 应用
  1510. let model = self.rightSideViewController.model
  1511. if (type == .bates || type == .headerAndFooter) {
  1512. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  1513. let alert = NSAlert()
  1514. alert.alertStyle = .critical
  1515. alert.messageText = "没有找到模型"
  1516. alert.runModal()
  1517. return
  1518. }
  1519. if ((model as! KMBatesModel).hasVaild == false) {
  1520. let alert = NSAlert()
  1521. alert.alertStyle = .critical
  1522. alert.messageText = "没有找到内容"
  1523. alert.runModal()
  1524. return
  1525. }
  1526. }
  1527. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  1528. result in
  1529. DispatchQueue.main.async {
  1530. self.listView.layoutDocumentView()
  1531. self.listView.setNeedsDisplayForVisiblePages()
  1532. }
  1533. if (result) {
  1534. let alert = NSAlert()
  1535. alert.alertStyle = .warning
  1536. alert.messageText = "成功"
  1537. alert.runModal()
  1538. } else {
  1539. let alert = NSAlert()
  1540. alert.alertStyle = .critical
  1541. alert.messageText = "失败"
  1542. alert.runModal()
  1543. }
  1544. }
  1545. return
  1546. }
  1547. /// 新增
  1548. self.rightSideViewController.view.isHidden = false
  1549. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  1550. self.openRightPane()
  1551. } else if (type == .redact) { /// 标记密文
  1552. if (index == 1) { /// 取消
  1553. if (self.hasAddRedact) {
  1554. let alert = NSAlert()
  1555. 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: "")
  1556. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  1557. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1558. let result = alert.runModal()
  1559. if (result == .alertFirstButtonReturn) {
  1560. self.listView.toolMode = .moveToolMode
  1561. self.toolbarController.exitRedact()
  1562. }
  1563. return
  1564. }
  1565. self.listView.toolMode = .moveToolMode
  1566. self.toolbarController.exitRedact()
  1567. return
  1568. }
  1569. if (index == 2) { /// 擦除
  1570. self.exeRedactConfirm(.eraserAll) {}
  1571. return
  1572. }
  1573. if (index == 3) { /// 应用
  1574. self.exeRedactConfirm(.redactAll) {}
  1575. return
  1576. }
  1577. if (index == 4) { /// 文本&图像
  1578. self.listView.toolMode = .redactToolMode
  1579. return
  1580. }
  1581. if (index == 5) { /// 页面
  1582. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  1583. self.view.window?.beginSheet(windowController.window!)
  1584. self.currentWindowController = windowController
  1585. windowController.itemClick = { [weak self] index, value in
  1586. if (index == 1) {
  1587. let topBarView = self?.toolbarController.fetchTopBarView()
  1588. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  1589. return
  1590. }
  1591. (topBarView as! KMRedactTopToolBar).selectItem(0)
  1592. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1593. self?.currentWindowController = nil
  1594. return
  1595. }
  1596. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  1597. let pageType = windowController_pageRange.pageType
  1598. let pageString = windowController_pageRange.pageString
  1599. if (pageType == 5) { /// 自定义页面
  1600. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  1601. if (array.count == 0) {
  1602. let alert = NSAlert()
  1603. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1604. alert.runModal()
  1605. return
  1606. }
  1607. }
  1608. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1609. self!.currentWindowController = nil
  1610. var indexs: IndexSet = []
  1611. if (pageType == 1) { /// 当前页面
  1612. indexs.insert((self?.listView.currentPageIndex)!)
  1613. } else {
  1614. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  1615. }
  1616. if (indexs.count == 0) {
  1617. return
  1618. }
  1619. for i in indexs {
  1620. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1621. let redactAnno = CPDFRedactAnnotation(pdfListViewNoteWith: self?.listView.document)
  1622. redactAnno?.bounds = page.bounds
  1623. self?.listView.add(redactAnno, to: page)
  1624. }
  1625. }
  1626. return
  1627. }
  1628. } else if (type == .secure) { /// 安全
  1629. if (index == 1) { /// 设置密码
  1630. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  1631. let url: URL = self.listView.document.documentURL
  1632. windowController.documentURL = url
  1633. windowController.myDocument = self.listView.document
  1634. self.currentWindowController = windowController
  1635. windowController.itemClick = { [weak self] (index: Int) -> () in
  1636. self!.view.window?.endSheet((self?.currentWindowController.window!)!)
  1637. self?.currentWindowController = nil
  1638. if (index == 2) { /// 取消
  1639. return
  1640. }
  1641. /// 批量
  1642. KMBatchWindowController.openFile(self!.listView.document.documentURL, .Security)
  1643. }
  1644. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  1645. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  1646. self!.view.window?.endSheet((self?.currentWindowController.window!)!)
  1647. self!.currentWindowController = nil
  1648. self!.listView.document.setPasswordOptions(windowController_secure.options)
  1649. self!.needSave = true
  1650. if result {
  1651. self!.showSecureSuccessTip()
  1652. } else {
  1653. let alert = NSAlert()
  1654. alert.messageText = NSLocalizedString("Failure", comment: "")
  1655. alert.runModal()
  1656. }
  1657. }
  1658. self.view.window?.beginSheet(windowController.window!)
  1659. return
  1660. }
  1661. /// 删除安全性设置
  1662. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1663. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  1664. if (result == .cancel) {
  1665. return
  1666. }
  1667. self?.listView.document.unlock(withPassword: password)
  1668. let result: Bool? = self?.listView.document.writeDecrypt(to: self?.listView.document.documentURL)
  1669. let tip = KMRemovePasswordResultTipView()
  1670. if (result != nil && result!) {
  1671. tip.result = .success
  1672. } else {
  1673. tip.result = .failure
  1674. }
  1675. tip.showInView(superView: (self?.listView.superview)!)
  1676. }
  1677. return
  1678. }
  1679. let alert = NSAlert()
  1680. alert.messageText = NSLocalizedString("Are you sure you want to remove the security settings for the file?", comment: "")
  1681. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1682. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1683. let response = alert.runModal()
  1684. if (response != .alertFirstButtonReturn) {
  1685. return
  1686. }
  1687. let result = self.listView.document.writeDecrypt(to: self.listView.document.documentURL)
  1688. let tip = KMRemovePasswordResultTipView()
  1689. if result {
  1690. tip.result = .success
  1691. } else {
  1692. tip.result = .failure
  1693. }
  1694. tip.showInView(superView: self.listView.superview!)
  1695. }
  1696. }
  1697. }
  1698. //extension KMMainViewController : KMToolbarViewControllerDelegate {
  1699. // func changeAnnotationModeAction(item: KMToolBoxItem) {
  1700. //// self.listView.toolMode = CToolMode.noteToolMode
  1701. // self.listView.annotationType = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  1702. // if(self.listView.annotationType == .addText) {
  1703. // self.rightSideViewController.view.isHidden = false
  1704. // self.rightSideViewController.subViewType = .EditPDFAddText
  1705. // self.listView.setShouAddEdit(CAddEditingAreaType.text);
  1706. // } else if (self.listView.annotationType == .addImage) {
  1707. // self.rightSideViewController.view.isHidden = true
  1708. // self.rightSideViewController.subViewType = .EditPDFAddImage
  1709. // self.listView.setIsSupportMultipleSelectEditingArea(true)
  1710. // self.listView.setShouAddEdit(CAddEditingAreaType.image);
  1711. // }
  1712. // }
  1713. //}