KMMainViewController+Action.swift 124 KB

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