KMMainViewController+Action.swift 83 KB

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