KMMainViewController+Action.swift 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702
  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. print("添加文字")
  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. print("添加图片")
  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. print("粘贴")
  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) {
  1298. var doucumentURL : URL = self.listView.document.documentURL
  1299. if doucumentURL != nil {
  1300. let docDir = NSTemporaryDirectory()
  1301. let documentName : String = doucumentURL.path.lastPathComponent
  1302. let path = docDir.stringByAppendingPathComponent(documentName)
  1303. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1304. if writeSuccess == false {
  1305. __NSBeep()
  1306. return;
  1307. }
  1308. doucumentURL = URL(fileURLWithPath: path)
  1309. }
  1310. let array = [doucumentURL]
  1311. let picker = NSSharingServicePicker.init(items: array)
  1312. if sender.shareButton.window != nil {
  1313. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1314. } else {
  1315. 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)
  1316. }
  1317. }
  1318. @objc private func shareFlatten(sender:KMToolbarViewController) {
  1319. let document = self.listView.document ?? CPDFDocument()
  1320. var path = document!.documentURL.path
  1321. if path != nil {
  1322. let docDir = NSTemporaryDirectory()
  1323. let documentName : String = path.lastPathComponent
  1324. path = docDir.stringByAppendingPathComponent(documentName)
  1325. }
  1326. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1327. var tfileName = path.deletingPathExtension.lastPathComponent
  1328. let tStdFileSuffix = "_flatten"
  1329. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1330. path = pathFolder + "/" + tfileName
  1331. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  1332. if success {
  1333. let url = URL(fileURLWithPath: path)
  1334. let picker = NSSharingServicePicker.init(items: [url])
  1335. if sender.shareButton.window != nil {
  1336. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1337. } else {
  1338. 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)
  1339. }
  1340. }
  1341. }
  1342. @objc private func shareOriginalPDF(sender:KMToolbarViewController) {
  1343. let document = self.listView.document ?? CPDFDocument()
  1344. var path = document!.documentURL.path
  1345. if path != nil {
  1346. let docDir = NSTemporaryDirectory()
  1347. let documentName : String = path.lastPathComponent
  1348. path = docDir.stringByAppendingPathComponent(documentName)
  1349. }
  1350. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1351. if writeSuccess == false {
  1352. __NSBeep()
  1353. return;
  1354. }
  1355. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1356. for i in 0 ... newDocument.pageCount-1 {
  1357. let page = newDocument.page(at: i)
  1358. var annotations : [CPDFAnnotation] = []
  1359. for annotation in page!.annotations {
  1360. annotations.append(annotation)
  1361. }
  1362. for annotation in annotations {
  1363. annotation.page.removeAnnotation(annotation)
  1364. }
  1365. }
  1366. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1367. if writeSuccess {
  1368. let url = URL(fileURLWithPath: path)
  1369. let picker = NSSharingServicePicker.init(items: [url])
  1370. if sender.shareButton.window != nil {
  1371. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1372. } else {
  1373. 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)
  1374. }
  1375. }
  1376. }
  1377. // 开启/关闭左边栏
  1378. @objc func toggleLeftPane() -> Void {
  1379. // if lastLeftPanWidth >= functionWidth {
  1380. leftPanelOpen = true
  1381. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1382. // } else {
  1383. // leftPanelOpen = false
  1384. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1385. // }
  1386. }
  1387. // 开启左边栏
  1388. @objc func openLeftPane() -> Void {
  1389. leftPanelOpen = true
  1390. applyLeftSideWidth(panelWidth+functionWidth,rightSideWidth: lastRightPanWidth)
  1391. }
  1392. // 关闭左边栏
  1393. @objc func closeLeftPane() -> Void {
  1394. leftPanelOpen = false
  1395. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1396. }
  1397. // 开启/关闭右边栏
  1398. @objc func toggleRightPane() -> Void {
  1399. if lastRightPanWidth > 5 {
  1400. self.rightPanelIsOpen = false
  1401. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1402. } else {
  1403. self.rightPanelIsOpen = true
  1404. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1405. }
  1406. }
  1407. @objc func openRightPane() -> Void {
  1408. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1409. if self.rightPanelIsOpen {
  1410. return
  1411. }
  1412. self.rightPanelIsOpen = true
  1413. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  1414. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1415. }
  1416. }
  1417. @objc func closeRightPane() -> Void {
  1418. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1419. self.rightPanelIsOpen = false
  1420. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  1421. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1422. }
  1423. }
  1424. func rename(_ sender: NSNotification) -> Void {
  1425. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1426. return
  1427. }
  1428. let tabController = sender.object as? CTTabController
  1429. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1430. let outputSavePanel = NSSavePanel()
  1431. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1432. outputSavePanel.allowedFileTypes = ["pdf"]
  1433. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1434. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1435. let result = outputSavePanel.runModal()
  1436. if result == .OK {
  1437. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1438. let fileURL = pdfDocument?.documentURL
  1439. let fileManager = FileManager.default
  1440. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1441. var result = true
  1442. do {
  1443. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1444. } catch {
  1445. result = false
  1446. print("Error renaming file! Threw: \(error.localizedDescription)")
  1447. }
  1448. if (result) {
  1449. tabController?.title = outputSavePanel.url!.lastPathComponent
  1450. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1451. self.isSaveKeyChain = false
  1452. newPdfDocument.unlock(withPassword: self.document?.password)
  1453. if (newPdfDocument.pageCount > 0) {
  1454. self.setDocument = newPdfDocument
  1455. }
  1456. }
  1457. }
  1458. } else {
  1459. outputSavePanel.close()
  1460. }
  1461. }
  1462. }
  1463. func showInFinder(_ sender: Any) -> Void {
  1464. if sender is NSNotification {
  1465. let tabController = (sender as! NSNotification).object as? CTTabController
  1466. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1467. let file: URL = (self.myDocument?.fileURL)!
  1468. if FileManager.default.fileExists(atPath: file.path) {
  1469. NSWorkspace.shared.activateFileViewerSelecting([file])
  1470. }
  1471. }
  1472. } else {
  1473. let file: URL = (self.myDocument?.fileURL)!
  1474. if FileManager.default.fileExists(atPath: file.path) {
  1475. NSWorkspace.shared.activateFileViewerSelecting([file])
  1476. }
  1477. }
  1478. }
  1479. func showOrHideNotes() {
  1480. self.listView.hideNotes = !self.listView.hideNotes
  1481. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  1482. //BOTA 注释列表显示隐藏
  1483. self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1484. self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1485. }
  1486. func closeTab(_ sender: NSNotification) -> Void {
  1487. let tabController = sender.object as? CTTabController
  1488. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1489. print("closeTab")
  1490. self.leftSideViewController.clearAnnotationFilterData()
  1491. self.leftSideViewController.clearNotification()
  1492. }
  1493. }
  1494. // MARK: -
  1495. // MARK: 显示窗口
  1496. internal func showCompressWindow() {
  1497. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  1498. KMPrint("压缩窗口已显示")
  1499. return
  1500. }
  1501. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  1502. self.view.window?.beginSheet(windowController.window!)
  1503. self.currentWindowController = windowController
  1504. windowController.documentURL = self.listView.document.documentURL
  1505. windowController.password = self.listView.document.password
  1506. windowController.itemClick = { [weak self] _ in
  1507. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1508. self?.currentWindowController = nil
  1509. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1510. }
  1511. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  1512. if (result) {
  1513. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1514. self?.currentWindowController = nil
  1515. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1516. if (openDocument) {
  1517. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1518. } else {
  1519. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1520. }
  1521. } else {
  1522. let alert = NSAlert()
  1523. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1524. alert.runModal()
  1525. }
  1526. }
  1527. }
  1528. internal func showConvertWindow(type: KMToolbarType, identifier: String?) {
  1529. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1530. KMPrint("转档窗口已显示")
  1531. return
  1532. }
  1533. var windowController: KMConvertBaseWindowController?
  1534. if (type == .word) { /// Word
  1535. windowController = KMConvertWordWindowController()
  1536. } else if (type == .excel) {
  1537. windowController = KMConvertExcelWindowController()
  1538. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1539. windowController = KMConvertPPTsWindowController()
  1540. if (type == .ppt) {
  1541. windowController?.subType = 1
  1542. } else if (type == .rtf) {
  1543. windowController?.subType = 2
  1544. } else if (type == .html) {
  1545. windowController?.subType = 3
  1546. } else if (type == .conversion_text) {
  1547. windowController?.subType = 4
  1548. }
  1549. } else if (type == .csv) {
  1550. windowController = KMConvertCSVWindowController()
  1551. } else if (type == .conversion_image) {
  1552. windowController = KMConvertImageWindowController()
  1553. }
  1554. let model = KMDocumentModel(url: self.listView.document.documentURL)
  1555. if (self.listView.document.password != nil) {
  1556. let _ = model.unlock(self.listView.document.password)
  1557. }
  1558. model.currentIndex = self.listView.currentPageIndex
  1559. windowController?.documentModel = model
  1560. windowController?.itemClick = { [weak self] index in
  1561. if (identifier != nil) {
  1562. self?.toolbarController.cancelSelected(identifier!)
  1563. }
  1564. if (self?.currentWindowController == nil) {
  1565. return
  1566. }
  1567. self?.view.window?.endSheet(self!.currentWindowController.window!)
  1568. self?.currentWindowController = nil
  1569. }
  1570. self.view.window?.beginSheet((windowController?.window)!)
  1571. self.currentWindowController = windowController
  1572. }
  1573. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1574. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1575. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1576. if (result == .cancel) {
  1577. return
  1578. }
  1579. // 解除权限
  1580. self?.listView.document.unlock(withPassword: password)
  1581. // 隐藏提示
  1582. self?.hiddenSecureLimitTip()
  1583. // 去打印
  1584. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  1585. }
  1586. return
  1587. }
  1588. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  1589. }
  1590. // MARK: - Split View
  1591. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  1592. }
  1593. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  1594. if !isSinglePage && isHorizontal {
  1595. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  1596. }
  1597. if (!isSinglePage && !isHorizontal) {
  1598. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  1599. }
  1600. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  1601. }
  1602. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  1603. if isSinglePage {
  1604. pdfSplitView.dividerStyle = .thin
  1605. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  1606. } else {
  1607. pdfSplitView.dividerStyle = .paneSplitter
  1608. pdfSplitView.isVertical = !isHorizontal
  1609. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  1610. if secondaryPdfView.document != nil {
  1611. // secondaryPdfView.frame = pdfSplitSecondView.frame
  1612. // pdfSplitSecondView.contentView = secondaryPdfView
  1613. } else {
  1614. openSecondaryPdfView = KMSecondaryViewController.init()
  1615. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  1616. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  1617. openSecondaryPdfView?.delegate = self
  1618. }
  1619. }
  1620. }
  1621. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  1622. if (pdfSplitView.isVertical) {
  1623. return Float(NSWidth(rect))
  1624. } else {
  1625. return Float(NSHeight(rect))
  1626. }
  1627. }
  1628. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  1629. let document = CPDFDocument.init(url: url)
  1630. if document != nil {
  1631. secondaryPdfView.frame = pdfSplitSecondView.frame
  1632. pdfSplitSecondView.contentView = secondaryPdfView
  1633. secondaryPdfView.document = nil
  1634. secondaryPdfView.document = document
  1635. return true
  1636. } else {
  1637. return false
  1638. }
  1639. }
  1640. func updateNextAndPreViousButtonState() {
  1641. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  1642. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  1643. if self.listView.canGoToNextPage() {
  1644. item?.unEnabled = false
  1645. } else {
  1646. item?.unEnabled = true
  1647. }
  1648. if self.listView.canGoToPreviousPage() {
  1649. toItem?.unEnabled = false
  1650. } else {
  1651. toItem?.unEnabled = true
  1652. }
  1653. }
  1654. func updateZoomInOutButtonState() {
  1655. let item : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolBoxItem()
  1656. let toItem : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolBoxItem()
  1657. if self.listView.canZoomIn {
  1658. item.unEnabled = false
  1659. } else {
  1660. item.unEnabled = true
  1661. }
  1662. if self.listView.canZoomOut {
  1663. toItem.unEnabled = false
  1664. } else {
  1665. toItem.unEnabled = true
  1666. }
  1667. }
  1668. }
  1669. // MARK: -
  1670. // MARK: - KMSecondaryViewControllerDelegate
  1671. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  1672. func receivedFileUrl(_ url: URL!) {
  1673. let state = self.displaySecondaryPDFView(withUrl: url)
  1674. if !state {
  1675. let alert = NSAlert()
  1676. alert.alertStyle = .critical
  1677. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1678. alert.runModal()
  1679. return
  1680. }
  1681. }
  1682. }
  1683. // MARK: -
  1684. // MARK: - KMMainToolbarControllerDelegate
  1685. extension KMMainViewController : KMMainToolbarControllerDelegate {
  1686. func changeModelAction(mode: CToolMode) {
  1687. self.listView.toolMode = mode
  1688. if mode == .editPDFToolMode {
  1689. self.childToolbarController.updateType(newType: .editPDF)
  1690. }
  1691. }
  1692. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  1693. switch selectedTag {
  1694. case 2:
  1695. if self.listView.scaleFactor != 1.0 {
  1696. self.listView.scaleFactor = 1.0
  1697. self.listView.autoScales = false
  1698. }
  1699. break
  1700. case 1:
  1701. let pageHeight = self.listView.currentPage()!.size.height
  1702. let pdfviewHeight = self.listView.bounds.size.height
  1703. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1704. self.listView.autoScales = false
  1705. break
  1706. case 0:
  1707. // self.listView.autoScales = !self.listView.autoScales
  1708. self.listView.autoScales = true
  1709. break
  1710. case 3:
  1711. self.listView.scaleFactor = 0.1
  1712. break
  1713. case 4:
  1714. self.listView.scaleFactor = 0.25
  1715. break
  1716. case 5:
  1717. self.listView.scaleFactor = 0.5
  1718. break
  1719. case 6:
  1720. self.listView.scaleFactor = 0.75
  1721. break
  1722. case 7:
  1723. self.listView.scaleFactor = 1.0
  1724. break
  1725. case 8:
  1726. self.listView.scaleFactor = 1.5
  1727. break
  1728. case 9:
  1729. self.listView.scaleFactor = 2.0
  1730. break
  1731. case 10:
  1732. self.listView.scaleFactor = 4.0
  1733. break
  1734. case 11:
  1735. self.listView.scaleFactor = 8.0
  1736. break
  1737. case 12:
  1738. self.listView.scaleFactor = 10.0
  1739. break
  1740. default:
  1741. break
  1742. }
  1743. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1744. }
  1745. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  1746. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1747. if scale > 100 {
  1748. scale = 100
  1749. }
  1750. if (scale <= 0.101) {
  1751. self.listView.scaleFactor = self.listView.minScaleFactor()
  1752. } else {
  1753. self.listView.scaleFactor = scale
  1754. }
  1755. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1756. DispatchQueue.main.async {
  1757. self.updateZoomInOutButtonState()
  1758. }
  1759. }
  1760. func changePDFViewZoomInAction() {
  1761. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  1762. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1763. switch scale {
  1764. case 0...0.25:
  1765. scale += 0.25
  1766. case 0.25...3:
  1767. scale += 0.25
  1768. case 3.1...10:
  1769. scale += 0.4
  1770. case 10.1...100:
  1771. scale += 1
  1772. default:
  1773. scale += 1
  1774. }
  1775. self.listView.scaleFactor = scale
  1776. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  1777. // self.listView.zoomIn(nil)
  1778. }
  1779. func changePDFViewZoomOutAction() {
  1780. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  1781. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1782. switch scale {
  1783. case 0...0.25:
  1784. scale = 0
  1785. case 0.25...3:
  1786. scale -= 0.25
  1787. case 3.1...10:
  1788. scale -= 0.4
  1789. case 10.1...100:
  1790. scale -= 1
  1791. default:
  1792. scale -= 1
  1793. }
  1794. self.listView.scaleFactor = scale
  1795. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  1796. // self.listView.zoomOut(nil)
  1797. // self.updateZoomInOutButtonState()
  1798. }
  1799. func changePDFViewGotoNextPageAction() {
  1800. self.listView.goToNextPage(nil)
  1801. self.updateNextAndPreViousButtonState()
  1802. }
  1803. func changePDFViewGoToPreviousPageAction() {
  1804. self.listView.goToPreviousPage(nil)
  1805. self.updateNextAndPreViousButtonState()
  1806. }
  1807. func showPDFViewPrintViewController() {
  1808. // self.menuItemAnnotationClick_Print(sender: NSMenuItem())
  1809. self.showPrintWindow()
  1810. }
  1811. func aiTranslationPDFFileAction() {
  1812. if !KMLightMemberManager.manager.isLogin() {
  1813. KMLoginWindowController.show(window: NSApp.mainWindow!)
  1814. return
  1815. }
  1816. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  1817. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  1818. let alert = NSAlert()
  1819. alert.alertStyle = .critical
  1820. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  1821. alert.runModal()
  1822. return
  1823. } else if isExceedsLimit {
  1824. let alert = NSAlert()
  1825. alert.alertStyle = .critical
  1826. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  1827. alert.runModal()
  1828. return
  1829. }
  1830. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  1831. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  1832. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  1833. }
  1834. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  1835. self.shareDocument(sender: viewController)
  1836. }
  1837. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  1838. self.shareFlatten(sender: viewController)
  1839. }
  1840. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  1841. self.shareOriginalPDF(sender: viewController)
  1842. }
  1843. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  1844. if(0 == selectedTag) {
  1845. self.documentAIViewController?.enteredIncreaseAllPage()
  1846. self.documentAIViewController?.updateToolState(false)
  1847. } else {
  1848. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  1849. // self.documentAIViewController?.recognitionPartModel(with: .english)
  1850. // self.documentAIViewController?.updateToolState(true)
  1851. }
  1852. // 0 : Scan 1:OCR Text
  1853. }
  1854. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolBoxItem , _ pages: [Int]) {
  1855. print("mainToolDidClicked")
  1856. if beforeType == .editPDF {
  1857. self.asyncSaveDocument { params in
  1858. }
  1859. }
  1860. if(type != .Page) {
  1861. if (hasEnterPageEdit()) {
  1862. self.exitPageEdit()
  1863. }
  1864. }
  1865. if(type != .ScanOCR) {
  1866. if ((self.documentAIViewController?.view.superview) != nil) {
  1867. self.listView.isHidden = false
  1868. self.documentAIViewController?.creatRecognitionDocument()
  1869. self.documentAIViewController?.view .removeFromSuperview()
  1870. self.documentAIViewController = nil;
  1871. self.listView.layoutDocumentView()
  1872. }
  1873. }
  1874. if (type == .Page) {
  1875. if (hasEnterPageEdit()) {
  1876. self.exitPageEdit()
  1877. } else {
  1878. self.enterPageEdit(pages)
  1879. }
  1880. } else if(type == .ScanOCR) {
  1881. if((self.documentAIViewController?.view.superview) != nil) {
  1882. let alert = NSAlert()
  1883. alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  1884. alert.addButton(withTitle: "YES")
  1885. alert.addButton(withTitle: "NO")
  1886. let result = alert.runModal()
  1887. if (result == .alertFirstButtonReturn) { /// 取消
  1888. self.listView.isHidden = false
  1889. self.documentAIViewController?.creatRecognitionDocument()
  1890. self.documentAIViewController?.view .removeFromSuperview()
  1891. self.documentAIViewController = nil;
  1892. self.listView.layoutDocumentView()
  1893. } else {
  1894. self.toolbarController.toolbarType = .ScanOCR
  1895. }
  1896. } else {
  1897. self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  1898. self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  1899. self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  1900. self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  1901. self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  1902. }
  1903. } else if type == .editPDF {
  1904. self.listView.annotationType = .editTextImage
  1905. } else if type == .Annatiton {
  1906. self.rightSideViewController.subViewType = .AnnotationProperts
  1907. }
  1908. }
  1909. func clickChildTool(type: KMToolbarType, index: Int) {
  1910. print("clickChildTool")
  1911. Task { @MainActor in
  1912. if (type == .compress) { /// 压缩
  1913. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1914. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1915. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1916. return
  1917. }
  1918. if (self.needSaveDocument()) {
  1919. self.saveDocumentWithProgressAlert { [unowned self] params in
  1920. self.showCompressWindow()
  1921. }
  1922. return
  1923. }
  1924. self.showCompressWindow()
  1925. return
  1926. }
  1927. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  1928. var identifier: String?
  1929. if (type == .word) { /// Word
  1930. identifier = KMToolbarConversionWordItemIdentifier
  1931. } else if (type == .excel) {
  1932. identifier = KMToolbarConversionExcelItemIdentifier
  1933. } else if (type == .ppt) {
  1934. identifier = KMToolbarConversionPPTItemIdentifier
  1935. } else if (type == .rtf) {
  1936. identifier = KMToolbarConversionRTFItemIdentifier
  1937. } else if (type == .html) {
  1938. identifier = KMToolbarConversionHTMLItemIdentifier
  1939. } else if (type == .conversion_text) {
  1940. identifier = KMToolbarConversionTextItemIdentifier
  1941. } else if (type == .csv) {
  1942. identifier = KMToolbarConversionCSVItemIdentifier
  1943. } else if (type == .conversion_image) {
  1944. identifier = KMToolbarConversionImageItemIdentifier
  1945. }
  1946. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1947. if (identifier != nil) {
  1948. self.toolbarController.cancelSelected(identifier!)
  1949. }
  1950. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!) { isSubscribeSuccess, _, _ in
  1951. }
  1952. return
  1953. }
  1954. if (self.needSaveDocument()) {
  1955. self.saveDocumentWithProgressAlert { [unowned self] params in
  1956. self.showConvertWindow(type: type, identifier: identifier)
  1957. }
  1958. return
  1959. }
  1960. self.showConvertWindow(type: type, identifier: identifier)
  1961. return
  1962. }
  1963. if (type == .merge) { /// 合并
  1964. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1965. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1966. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  1967. return
  1968. }
  1969. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  1970. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  1971. if (result == .cancel) {
  1972. return
  1973. }
  1974. if (self.needSaveDocument()) {
  1975. self.saveDocumentWithProgressAlert { [unowned self] params in
  1976. self.showMergeWindow(password)
  1977. }
  1978. return
  1979. }
  1980. self.showMergeWindow(password)
  1981. }
  1982. return
  1983. }
  1984. if (self.needSaveDocument()) {
  1985. self.saveDocumentWithProgressAlert { [unowned self] params in
  1986. self.showMergeWindow(self.listView.document.password)
  1987. }
  1988. return
  1989. }
  1990. self.showMergeWindow(self.listView.document.password)
  1991. return
  1992. }
  1993. if (type == .crop) {
  1994. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1995. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1996. return
  1997. }
  1998. if (index == 1) {
  1999. self.cropCurrentPage()
  2000. return
  2001. }
  2002. if (index == 2) {
  2003. self.cropAllPage()
  2004. return
  2005. }
  2006. //// 自定义裁剪区域
  2007. // self.cropCustomArea()
  2008. } else if (type == .bates || type == .headerAndFooter || type == .background || type == .watermark) {
  2009. if (index == 0) {
  2010. var controller: KMWatermarkAdjectivePreViewBaseController!
  2011. if (type == .bates) {
  2012. controller = KMBatesPreviewController()
  2013. } else if (type == .headerAndFooter) {
  2014. controller = KMHeaderFooterPreviewController()
  2015. } else if (type == .background) {
  2016. controller = KMBackgroundController()
  2017. } else if (type == .watermark) {
  2018. controller = KMWatermarkViewController()
  2019. }
  2020. controller.applyDocument = self.listView.document
  2021. controller.view.frame = self.view.bounds
  2022. controller.view.autoresizingMask = [.width, .height]
  2023. controller.documentURL = self.listView.document.documentURL
  2024. self.view.addSubview(controller.view)
  2025. self.addChild(controller)
  2026. controller.itemClick = { [weak self] index, param in
  2027. if (index == 0 || index == 1) { /// 取消 和 应用
  2028. var controller_watermarkAdjective_preView: KMWatermarkAdjectivePreViewBaseController?
  2029. for i in 0 ..< self!.children.count {
  2030. let vc: NSViewController = self!.children[self!.children.count-1-i]
  2031. if (vc.isKind(of: KMWatermarkAdjectivePreViewBaseController.self) == true) {
  2032. controller_watermarkAdjective_preView = vc as! KMWatermarkAdjectivePreViewBaseController
  2033. break
  2034. }
  2035. }
  2036. if (controller_watermarkAdjective_preView == nil) {
  2037. return
  2038. }
  2039. controller_watermarkAdjective_preView!.view.removeFromSuperview()
  2040. controller_watermarkAdjective_preView?.removeFromParent()
  2041. // if (index == 1) {
  2042. self?.listView.document = CPDFDocument(url: self?.listView.document.documentURL)
  2043. self?.listView.layoutDocumentView()
  2044. self?.listView.setNeedsDisplayForVisiblePages()
  2045. // }
  2046. return
  2047. }
  2048. }
  2049. return
  2050. }
  2051. if (index == 1) { /// 取消
  2052. self.toolbarController.exitWatermarkAdjective()
  2053. // self.rightSideViewController.view.isHidden = true
  2054. self.rightSideViewController.isHidden = true
  2055. self.rightSideViewController.subViewType = .None
  2056. self.closeRightPane()
  2057. return
  2058. }
  2059. if (index == 5) { /// 批量
  2060. return
  2061. }
  2062. if (index == 4) { //// 移除
  2063. if (type == .watermark) {
  2064. let watermarks = self.listView.document.watermarks()
  2065. if (watermarks == nil || watermarks!.count <= 0) {
  2066. let alert = NSAlert()
  2067. alert.alertStyle = .warning
  2068. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  2069. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  2070. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2071. alert.runModal()
  2072. return
  2073. }
  2074. let alert = NSAlert()
  2075. alert.alertStyle = .warning
  2076. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  2077. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  2078. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2079. let result = alert.runModal()
  2080. if (result != .alertFirstButtonReturn) {
  2081. return
  2082. }
  2083. }
  2084. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  2085. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  2086. result in
  2087. DispatchQueue.main.async {
  2088. self.listView.layoutDocumentView()
  2089. self.listView.setNeedsDisplayForVisiblePages()
  2090. }
  2091. if (result) {
  2092. let alert = NSAlert()
  2093. alert.alertStyle = .warning
  2094. alert.messageText = "成功"
  2095. alert.runModal()
  2096. } else {
  2097. let alert = NSAlert()
  2098. alert.alertStyle = .critical
  2099. alert.messageText = "失败"
  2100. alert.runModal()
  2101. }
  2102. }
  2103. return
  2104. }
  2105. if (index == 2) { /// 应用
  2106. let model = self.rightSideViewController.model
  2107. if (type == .bates || type == .headerAndFooter) {
  2108. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2109. let alert = NSAlert()
  2110. alert.alertStyle = .critical
  2111. alert.messageText = "没有找到模型"
  2112. alert.runModal()
  2113. return
  2114. }
  2115. if ((model as! KMBatesModel).hasVaild == false) {
  2116. let alert = NSAlert()
  2117. alert.alertStyle = .critical
  2118. alert.messageText = "没有找到内容"
  2119. alert.runModal()
  2120. return
  2121. }
  2122. }
  2123. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2124. result in
  2125. DispatchQueue.main.async {
  2126. self.listView.layoutDocumentView()
  2127. self.listView.setNeedsDisplayForVisiblePages()
  2128. }
  2129. if (result) {
  2130. let alert = NSAlert()
  2131. alert.alertStyle = .warning
  2132. alert.messageText = "成功"
  2133. alert.runModal()
  2134. } else {
  2135. let alert = NSAlert()
  2136. alert.alertStyle = .critical
  2137. alert.messageText = "失败"
  2138. alert.runModal()
  2139. }
  2140. }
  2141. return
  2142. }
  2143. /// 新增
  2144. // self.rightSideViewController.view.isHidden = false
  2145. self.rightSideViewController.isHidden = false
  2146. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2147. self.openRightPane()
  2148. } else if (type == .redact) { /// 标记密文
  2149. if (index == 1) { /// 取消
  2150. if (self.hasAddRedact) {
  2151. let alert = NSAlert()
  2152. 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: "")
  2153. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2154. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2155. let result = alert.runModal()
  2156. if (result == .alertFirstButtonReturn) {
  2157. self.listView.toolMode = .moveToolMode
  2158. self.toolbarController.exitRedact()
  2159. }
  2160. return
  2161. }
  2162. self.listView.toolMode = .moveToolMode
  2163. self.toolbarController.exitRedact()
  2164. return
  2165. }
  2166. if (index == 2) { /// 擦除
  2167. self.exeRedactConfirm(.eraserAll) {}
  2168. return
  2169. }
  2170. if (index == 3) { /// 应用
  2171. self.exeRedactConfirm(.redactAll) {}
  2172. return
  2173. }
  2174. if (index == 4) { /// 文本&图像
  2175. self.listView.toolMode = .redactToolMode
  2176. return
  2177. }
  2178. if (index == 5) { /// 页面
  2179. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2180. await self.view.window?.beginSheet(windowController.window!)
  2181. self.currentWindowController = windowController
  2182. windowController.itemClick = { [weak self] index, value in
  2183. if (index == 1) {
  2184. let topBarView = self?.toolbarController.fetchTopBarView()
  2185. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  2186. return
  2187. }
  2188. (topBarView as! KMRedactTopToolBar).selectItem(0)
  2189. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2190. self?.currentWindowController = nil
  2191. return
  2192. }
  2193. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2194. let pageType = windowController_pageRange.pageType
  2195. let pageString = windowController_pageRange.pageString
  2196. if (pageType == 5) { /// 自定义页面
  2197. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  2198. if (array.count == 0) {
  2199. let alert = NSAlert()
  2200. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2201. alert.runModal()
  2202. return
  2203. }
  2204. }
  2205. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2206. self!.currentWindowController = nil
  2207. var indexs: IndexSet = []
  2208. if (pageType == 1) { /// 当前页面
  2209. indexs.insert((self?.listView.currentPageIndex)!)
  2210. } else {
  2211. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  2212. }
  2213. if (indexs.count == 0) {
  2214. return
  2215. }
  2216. for i in indexs {
  2217. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2218. let redactAnno = CPDFRedactAnnotation(pdfListViewNoteWith: self?.listView.document)
  2219. redactAnno?.bounds = page.bounds
  2220. self?.listView.add(redactAnno, to: page)
  2221. }
  2222. }
  2223. return
  2224. }
  2225. } else if (type == .secure) { /// 安全
  2226. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2227. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  2228. return
  2229. }
  2230. if (index == 1) { /// 设置密码
  2231. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2232. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2233. if (result == .cancel) {
  2234. return
  2235. }
  2236. self?.isSaveKeyChain = false
  2237. self?.listView.document.unlock(withPassword: password)
  2238. self?.hiddenSecureLimitTip()
  2239. self?.showSecureWindow((self?.listView.document.documentURL)!)
  2240. }
  2241. return
  2242. }
  2243. self.showSecureWindow(self.listView.document.documentURL)
  2244. return
  2245. }
  2246. /// 删除安全性设置
  2247. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2248. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2249. if (result == .cancel) {
  2250. return
  2251. }
  2252. self?.isSaveKeyChain = false
  2253. self?.listView.document.unlock(withPassword: password)
  2254. self?.hiddenSecureLimitTip()
  2255. self?.recordRemoveSecureFlag()
  2256. let tip = KMRemovePasswordResultTipView()
  2257. tip.result = .success
  2258. tip.showInView(superView: (self?.listView.superview)!)
  2259. }
  2260. return
  2261. }
  2262. let alert = NSAlert()
  2263. alert.messageText = NSLocalizedString("Are you sure you want to remove the security settings for the file?", comment: "")
  2264. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2265. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2266. let response = alert.runModal()
  2267. if (response != .alertFirstButtonReturn) {
  2268. return
  2269. }
  2270. self.recordRemoveSecureFlag()
  2271. let tip = KMRemovePasswordResultTipView()
  2272. tip.result = .success
  2273. self.hiddenSecureLimitTip()
  2274. tip.showInView(superView: self.listView.superview!)
  2275. }
  2276. }
  2277. }
  2278. }
  2279. // MARK: -
  2280. // MARK: - Mouse
  2281. extension KMMainViewController {
  2282. override func mouseDown(with event: NSEvent) {
  2283. super.mouseDown(with: event)
  2284. print("KMMainViewController mouseDown")
  2285. self.leftSideViewCancelSelect()
  2286. self.pageNumberDisplayView.isEdit = false
  2287. }
  2288. }
  2289. //MARK: LeftSideViewController
  2290. extension KMMainViewController {
  2291. func leftSideViewCancelSelect() {
  2292. switch self.leftSideViewController.type.methodType {
  2293. // case .Thumbnail:
  2294. // self.leftSideViewController.thumbnailViewController.cancelSelect()
  2295. case .Outline:
  2296. self.leftSideViewController.outlineViewController.cancelSelect()
  2297. case .BookMark:
  2298. self.leftSideViewController.bookViewController.cancelSelect()
  2299. case .Search:
  2300. self.leftSideViewController.searchViewController.cancelSelect()
  2301. case .Annotation:
  2302. self.leftSideViewController.annotationViewController.cancelSelect()
  2303. default:
  2304. print("其他")
  2305. }
  2306. }
  2307. }
  2308. extension KMMainViewController: KMReadModelViewDelegate {
  2309. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2310. self.listView.goToFirstPage(nil)
  2311. }
  2312. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  2313. self.listView.goToPreviousPage(nil)
  2314. }
  2315. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2316. self.listView.goToNextPage(nil)
  2317. }
  2318. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2319. self.listView.goToLastPage(nil)
  2320. }
  2321. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  2322. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  2323. }
  2324. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  2325. var scale: Double = 1.0
  2326. switch type {
  2327. case .fitWidth:
  2328. self.listView.autoScales = !self.listView.autoScales
  2329. scale = self.listView.scaleFactor
  2330. break
  2331. case .actualSize:
  2332. if self.listView.scaleFactor != 1.0 {
  2333. self.listView.scaleFactor = 1.0
  2334. self.listView.autoScales = false
  2335. }
  2336. scale = self.listView.scaleFactor
  2337. break
  2338. case .autoSize:
  2339. self.listView.autoScales = true
  2340. self.listView.autoScales = false
  2341. scale = self.listView.scaleFactor
  2342. break
  2343. case ._10:
  2344. scale = 0.1
  2345. break
  2346. case ._25:
  2347. scale = 0.25
  2348. break
  2349. case ._50:
  2350. scale = 0.5
  2351. break
  2352. case ._100:
  2353. scale = 1.0
  2354. break
  2355. case ._150:
  2356. scale = 1.5
  2357. break
  2358. case ._200:
  2359. scale = 2.0
  2360. break
  2361. case ._400:
  2362. scale = 4.0
  2363. break
  2364. case ._800:
  2365. scale = 8.0
  2366. break
  2367. default:
  2368. break
  2369. }
  2370. self.listView.scaleFactor = scale
  2371. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2372. }
  2373. func cancelReadModel(view: KMReadModelView, sender: Any) {
  2374. if self.isReadMode {
  2375. self.closeReadModel()
  2376. }
  2377. }
  2378. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  2379. // if self.readModelViewWidthConstraint.constant != width {
  2380. self.readModelViewWidthConstraint.constant = width
  2381. // }
  2382. }
  2383. }
  2384. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  2385. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  2386. self.listView.go(toPageIndex: pageIndex, animated: true)
  2387. }
  2388. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  2389. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  2390. self.tipCurrentPageBoxWidthConstraint.constant = width
  2391. }
  2392. }
  2393. func commitEditingIfNeed() {
  2394. let isEdited = self.listView?.isEdited() ?? false
  2395. if isEdited || self.isPDFTextImageEdited {
  2396. self.listView.commitEditing()
  2397. }
  2398. }
  2399. }