KMMainViewController+Action.swift 149 KB

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