KMMainViewController+Action.swift 124 KB

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