KMMainViewController+Action.swift 88 KB

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