KMMainViewController+Action.swift 142 KB

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