KMMainViewController+Action.swift 169 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530
  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(selection: 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 : KMToolbarItemView = (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 VERSION_DMG
  520. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  521. return
  522. }
  523. #endif
  524. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  525. self.listView.currentSelection = nil;
  526. if (annotation != nil) {
  527. self.listView.updateActiveAnnotations([annotation!])
  528. }
  529. }
  530. }
  531. }
  532. @objc func aiTranslationAction(sender: NSMenuItem) {
  533. let content = self.listView.currentSelection.string() as? String ?? ""
  534. let origin = self.listView.currentSelection.bounds.origin
  535. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  536. self.aiTranslationWindow?.content = content
  537. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  538. self.aiTranslationWindow!.window?.center()
  539. }
  540. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  541. Task { @MainActor in
  542. #if VERSION_DMG
  543. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) {
  544. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  545. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  546. return
  547. }
  548. }
  549. #endif
  550. var point = mouseRightMenuEvent?.locationInWindow
  551. if (point == nil) {
  552. point = NSZeroPoint
  553. }
  554. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  555. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  556. let pagePoint = self.listView.convert(currentPoint, to: currentPage)
  557. var annotation: CPDFAnnotation?
  558. if self.isReadMode {
  559. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  560. self.listView.toolMode = .noteToolMode
  561. }
  562. switch sender.tag {
  563. case 0:
  564. self.listView.annotationType = CAnnotationType.ink
  565. case 1:
  566. // self.listView.annotationType = CAnnotationType.freeText
  567. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  568. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  569. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  570. if ((annotation) != nil) {
  571. self.listView.updateActiveAnnotations([annotation!])
  572. self.listView.edit(annotation)
  573. }
  574. case 2:
  575. // self.listView.annotationType = CAnnotationType.anchored
  576. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  577. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  578. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  579. self.listView.edit(annotation)
  580. case 3:
  581. // self.listView.annotationType = CAnnotationType.square
  582. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  583. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  584. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  585. case 4:
  586. // self.listView.annotationType = CAnnotationType.circle
  587. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  588. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  589. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  590. case 5:
  591. // self.listView.annotationType = CAnnotationType.arrow
  592. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  593. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  594. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  595. case 6:
  596. // self.listView.annotationType = CAnnotationType.line
  597. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  598. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  599. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  600. case 7:
  601. self.listView.annotationType = CAnnotationType.link
  602. self.openRightPane()
  603. case 8:
  604. self.listView.annotationType = CAnnotationType.stamp
  605. self.openRightPane()
  606. case 9:
  607. self.listView.annotationType = CAnnotationType.signSignature
  608. self.openRightPane()
  609. default:
  610. break
  611. }
  612. self.rightSideViewController.isHidden = true
  613. self.rightSideViewController.subViewType = .AnnotationProperts
  614. } else {
  615. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  616. if(self.toolbarController.toolbarType == .None) {
  617. self.toolbarController.toolbarType = .Annatiton
  618. }
  619. self.listView.toolMode = .noteToolMode
  620. }
  621. switch sender.tag {
  622. case 0:
  623. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  624. self.rightMouseEventing = true
  625. if(self.toolbarController.toolbarType == .None) {
  626. self.toolbarController.toolbarType = .Annatiton
  627. }
  628. self.listView.toolMode = .noteToolMode
  629. self.listView.annotationType = CAnnotationType.ink
  630. case 1:
  631. // self.listView.annotationType = CAnnotationType.freeText
  632. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  633. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  634. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  635. // self.view.window?.makeFirstResponder()
  636. if ((annotation) != nil) {
  637. // self.listView.updateActiveAnnotations([annotation!])
  638. self.listView.edit(annotation)
  639. }
  640. case 2:
  641. // self.listView.annotationType = CAnnotationType.anchored
  642. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  643. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  644. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  645. self.listView.edit(annotation)
  646. case 3:
  647. // self.listView.annotationType = CAnnotationType.square
  648. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  649. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  650. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  651. case 4:
  652. // self.listView.annotationType = CAnnotationType.circle
  653. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  654. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  655. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  656. case 5:
  657. // self.listView.annotationType = CAnnotationType.arrow
  658. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  659. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  660. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  661. case 6:
  662. // self.listView.annotationType = CAnnotationType.line
  663. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  664. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  665. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  666. case 7:
  667. self.listView.annotationType = CAnnotationType.link
  668. self.openRightPane()
  669. case 8:
  670. self.listView.annotationType = CAnnotationType.stamp
  671. self.openRightPane()
  672. case 9:
  673. self.listView.annotationType = CAnnotationType.signSignature
  674. self.openRightPane()
  675. default:
  676. break
  677. }
  678. // self.rightSideViewController.view.isHidden = false
  679. self.rightSideViewController.isHidden = false
  680. // self.openRightPane()
  681. self.rightSideViewController.subViewType = .AnnotationProperts
  682. }
  683. if (annotation != nil) {
  684. self.listView.updateIsRightActiveAnnotations([annotation!])
  685. }
  686. }
  687. }
  688. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  689. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  690. let index = self.listView.currentPageIndex
  691. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  692. self.listView.setNeedsDisplayForVisiblePages()
  693. } else {
  694. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  695. self.listView.setNeedsDisplayForVisiblePages()
  696. }
  697. if self.isReadMode {
  698. } else {
  699. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  700. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  701. }
  702. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  703. if bookMark != nil {
  704. let item = KMBookMarkItem()
  705. item.bookMark = bookMark!
  706. item.label = (bookMark?.label)!
  707. item.index = UInt(bookMark!.pageIndex)
  708. self.leftSideViewController.bookViewController.reloadData()
  709. self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  710. } else {
  711. self.leftSideViewController.bookViewController.reloadData()
  712. }
  713. }
  714. }
  715. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  716. self.leftSideViewController.refreshMethodType(methodType: .Search)
  717. }
  718. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  719. let rect = listView.currentSelectionRect()
  720. let page = listView.currentPage()
  721. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  722. copyPage.setBounds(rect, for: .cropBox)
  723. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  724. // let pdfDocument : PDFDocument = PDFDocument()
  725. // let newpage : PDFPage = PDFPage(image: image)!
  726. // pdfDocument.insert(newpage, at: 0)
  727. // 执行右键操作后,需要取消框选区域
  728. if self.listView.toolMode == .selectToolMode {
  729. objc_sync_enter(self)
  730. self.listView.selectionRect = NSZeroRect
  731. self.listView.selectionPageIndex = UInt(NSNotFound)
  732. objc_sync_exit(self)
  733. }
  734. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  735. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  736. if (result == .cancel) {
  737. return
  738. }
  739. // 解除权限
  740. self?.isSaveKeyChain = false
  741. self?.listView.document.unlock(withPassword: password)
  742. // 隐藏提示
  743. self?.hiddenSecureLimitTip()
  744. // 去打印
  745. KMPrintWindowController.printImage(image: image)
  746. }
  747. return
  748. }
  749. KMPrintWindowController.printImage(image: image)
  750. }
  751. // MARK: Redact 【密文标记】
  752. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  753. self.listView.remove(self.listView.activeAnnotation)
  754. }
  755. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  756. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  757. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  758. self.view.window?.beginSheet(windowController.window!)
  759. self.currentWindowController = windowController
  760. windowController.itemClick = { [weak self] index, value in
  761. if (index == 1) { /// 取消
  762. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  763. self?.currentWindowController = nil
  764. return
  765. }
  766. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  767. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  768. annotaton.setBorderColor(windowController_redact.outsideColor)
  769. annotaton.setInteriorColor(windowController_redact.fillColor)
  770. if (windowController_redact.isOver) {
  771. annotaton.setFontColor(windowController_redact.fontColor)
  772. annotaton.setAlignment(windowController_redact.aligement)
  773. annotaton.setFont(windowController_redact.font)
  774. annotaton.setOverlayText(windowController_redact.overText)
  775. }
  776. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  777. self?.currentWindowController = nil
  778. }
  779. }
  780. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  781. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  782. return
  783. }
  784. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  785. let model = CPDFAnnotationModel(annotationType: .redact)
  786. model?.setColor(annotation.borderColor())
  787. model?.setInteriorColor(annotation.interiorColor())
  788. let overlayText: String = annotation.overlayText()
  789. if (overlayText.isEmpty) {
  790. model?.setIsOverlayText(false)
  791. } else {
  792. model?.setIsOverlayText(true)
  793. model?.setOverlayText(overlayText)
  794. model?.setFontColor(annotation.fontColor())
  795. model?.setAlignment(annotation.alignment())
  796. model?.setFontName(annotation.font().fontName)
  797. model?.setFontSize(annotation.font().pointSize)
  798. }
  799. }
  800. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  801. let anno = self.listView.activeAnnotation
  802. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  803. return
  804. }
  805. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  806. windowController.pageCount = Int(self.listView.document.pageCount)
  807. self.currentWindowController = windowController
  808. self.view.window?.beginSheet(windowController.window!)
  809. windowController.itemClick = { [weak self] index, value in
  810. if (index == 1) {
  811. self!.view.window?.endSheet(self!.currentWindowController.window!)
  812. self!.currentWindowController = nil
  813. return
  814. }
  815. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  816. let pageType = windowController_mutilPageFlag.pageType
  817. let pageString = windowController_mutilPageFlag.pageString
  818. if (pageType == 4) { /// 自定义页面
  819. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  820. if (array.count == 0) {
  821. let alert = NSAlert()
  822. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  823. alert.runModal()
  824. return
  825. }
  826. }
  827. self!.view.window?.endSheet(self!.currentWindowController.window!)
  828. self!.currentWindowController = nil
  829. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  830. if (indexs.count == 0) {
  831. return
  832. }
  833. for i in indexs {
  834. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  835. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  836. self?.listView.add(redactAnno, to: page)
  837. }
  838. }
  839. }
  840. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  841. self.exeRedactConfirm(.redactOne) {}
  842. }
  843. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  844. self.exeRedactConfirm(.eraserOne) {}
  845. }
  846. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  847. }
  848. @objc func exportStampImage(sender:NSMenuItem) {
  849. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  850. var image : NSImage = NSImage()
  851. if (listView.activeAnnotation is CPDFStampAnnotation) {
  852. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  853. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  854. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  855. }
  856. let data = image.tiffRepresentation
  857. if sender.tag == 0 {
  858. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  859. imageRep.size = image.size
  860. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  861. let savePanel = NSSavePanel()
  862. savePanel.allowedFileTypes = ["png"]
  863. savePanel.beginSheetModal(for: self.view.window!) { response in
  864. if (response != .OK) {
  865. return
  866. }
  867. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  868. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  869. }
  870. }
  871. } else {
  872. let pdfdocument = CPDFDocument()
  873. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  874. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  875. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  876. let savePanel = NSSavePanel()
  877. savePanel.allowedFileTypes = ["pdf"]
  878. savePanel.beginSheetModal(for: self.view.window!) { response in
  879. if (response != .OK) {
  880. return
  881. }
  882. if pdfdocument!.write(to: savePanel.url!) {
  883. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  884. }
  885. }
  886. }
  887. }
  888. }
  889. }
  890. @objc func exportCorpImage(sender:NSMenuItem) {
  891. let rect = NSIntegralRect(listView.currentSelectionRect())
  892. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  893. let page : CPDFPage = orgPage.copy() as! CPDFPage
  894. page.setBounds(rect, for: .cropBox)
  895. let image = page.thumbnail(of: rect.size) ?? NSImage()
  896. let data = image.tiffRepresentation
  897. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  898. imageRep.size = rect.size
  899. let savePanel = NSSavePanel()
  900. switch sender.tag {
  901. case 0:
  902. savePanel.allowedFileTypes = ["png"]
  903. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  904. savePanel.beginSheetModal(for: self.view.window!) { response in
  905. if (response != .OK) {
  906. return
  907. }
  908. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  909. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  910. }
  911. }
  912. case 1:
  913. savePanel.allowedFileTypes = ["jpg"]
  914. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  915. savePanel.beginSheetModal(for: self.view.window!) { response in
  916. if (response != .OK) {
  917. return
  918. }
  919. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  920. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  921. }
  922. }
  923. case 2:
  924. savePanel.allowedFileTypes = ["pdf"]
  925. let pdfdocument = CPDFDocument()
  926. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  927. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  928. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  929. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  930. savePanel.beginSheetModal(for: self.view.window!) { response in
  931. if (response != .OK) {
  932. return
  933. }
  934. if pdfdocument!.write(to: savePanel.url!) {
  935. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  936. }
  937. }
  938. }
  939. default:
  940. break
  941. }
  942. // 执行右键操作后,需要取消框选区域
  943. if self.listView.toolMode == .selectToolMode {
  944. objc_sync_enter(self)
  945. self.listView.selectionRect = NSZeroRect
  946. self.listView.selectionPageIndex = UInt(NSNotFound)
  947. objc_sync_exit(self)
  948. }
  949. }
  950. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  951. let rect = listView.currentSelectionRect()
  952. let page = listView.currentPage()
  953. if NSIsEmptyRect(rect) == false && page != nil {
  954. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  955. var bounds = listView.bounds
  956. var scale = 1.0
  957. if isLegacy {
  958. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  959. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  960. }
  961. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  962. scale = NSHeight(bounds) / NSHeight(rect)
  963. } else {
  964. scale = NSWidth(bounds) / NSWidth(rect)
  965. }
  966. listView.setScaleFactor(scale, animated: false)
  967. let scrollView = listView.scroll()
  968. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  969. if ((scrollView?.hasVerticalScroller) != nil) {
  970. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  971. }
  972. if ((scrollView?.hasHorizontalScroller) != nil) {
  973. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  974. }
  975. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  976. scale = NSHeight(bounds) / NSHeight(rect)
  977. } else {
  978. scale = NSWidth(bounds) / NSWidth(rect)
  979. }
  980. listView.setScaleFactor(scale, animated: false)
  981. }
  982. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  983. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  984. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  985. };
  986. }
  987. // 执行右键操作后,需要取消框选区域
  988. if self.listView.toolMode == .selectToolMode {
  989. objc_sync_enter(self)
  990. self.listView.selectionRect = NSZeroRect
  991. self.listView.selectionPageIndex = UInt(NSNotFound)
  992. objc_sync_exit(self)
  993. }
  994. }
  995. @IBAction func autoCropAll(sender:NSMenuItem) {
  996. }
  997. private func cropPagesToRects(rects:NSPointerArray) {
  998. }
  999. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1000. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1001. switch sender.tag {
  1002. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1003. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1004. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1005. var red: CGFloat = 0.0
  1006. var green: CGFloat = 0.0
  1007. var blue: CGFloat = 0.0
  1008. var alpha: CGFloat = 0.0
  1009. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1010. if sender.tag == CAnnotationType.highlight.rawValue {
  1011. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1012. } else if sender.tag == CAnnotationType.underline.rawValue {
  1013. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1014. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1015. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1016. }
  1017. case CAnnotationType.ink.rawValue:
  1018. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1019. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1020. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1021. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1022. var red: CGFloat = 0.0
  1023. var green: CGFloat = 0.0
  1024. var blue: CGFloat = 0.0
  1025. var alpha: CGFloat = 0.0
  1026. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1027. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1028. case CAnnotationType.freeText.rawValue:
  1029. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1030. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1031. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1032. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1033. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1034. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1035. var red: CGFloat = 0.0
  1036. var green: CGFloat = 0.0
  1037. var blue: CGFloat = 0.0
  1038. var alpha: CGFloat = 0.0
  1039. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1040. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1041. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1042. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1043. UserDefaults.standard.synchronize()
  1044. }
  1045. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1046. if (alignment == .left || alignment == .center || alignment == .right) {
  1047. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1048. UserDefaults.standard.synchronize()
  1049. }
  1050. case CAnnotationType.anchored.rawValue:
  1051. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1052. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1053. var red: CGFloat = 0.0
  1054. var green: CGFloat = 0.0
  1055. var blue: CGFloat = 0.0
  1056. var alpha: CGFloat = 0.0
  1057. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1058. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1059. case CAnnotationType.square.rawValue:
  1060. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1061. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1062. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1063. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1064. var red: CGFloat = 0.0
  1065. var green: CGFloat = 0.0
  1066. var blue: CGFloat = 0.0
  1067. var alpha: CGFloat = 0.0
  1068. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1069. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1070. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1071. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1072. case CAnnotationType.circle.rawValue:
  1073. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1074. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1075. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1076. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1077. var red: CGFloat = 0.0
  1078. var green: CGFloat = 0.0
  1079. var blue: CGFloat = 0.0
  1080. var alpha: CGFloat = 0.0
  1081. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1082. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1083. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1084. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1085. default:
  1086. break
  1087. }
  1088. }
  1089. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1090. self.showOrHideNotes()
  1091. }
  1092. //MARK: action
  1093. @objc func cropCurrentPage() {
  1094. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1095. var page: CPDFPage?
  1096. if ((self.listView.currentSelectionPage()) != nil) {
  1097. page = self.listView.currentSelectionPage()
  1098. } else {
  1099. page = self.listView.currentPage()
  1100. }
  1101. if (NSIsEmptyRect(rect)) {
  1102. rect = KMCropTools.getPageForegroundBox(page!)
  1103. }
  1104. let index: UInt = (page?.pageIndex())!
  1105. cropPage(at: index, in: rect)
  1106. // 执行右键操作后,需要取消框选区域
  1107. if self.listView.toolMode == .selectToolMode {
  1108. objc_sync_enter(self)
  1109. self.listView.selectionRect = NSZeroRect
  1110. self.listView.selectionPageIndex = UInt(NSNotFound)
  1111. objc_sync_exit(self)
  1112. }
  1113. }
  1114. func cropPage(at index: UInt, in rect: NSRect) {
  1115. let oldRect = self.listView.document.page(at: index)?.bounds(for: .cropBox)
  1116. let undoManager = self.listView.undoManager
  1117. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)!.cropPage(at: index, in: oldRect!)
  1118. let page = self.listView.document.page(at: index)
  1119. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox))!)
  1120. page?.setBounds(newRect, for: .cropBox)
  1121. /// 刷新预览视图
  1122. self.listView.layoutDocumentView()
  1123. self.listView.displayBox = .cropBox
  1124. }
  1125. @objc private func cropAllPage() {
  1126. var size = NSZeroSize
  1127. for i in 0 ..< self.listView.document.pageCount {
  1128. let page = self.listView.document.page(at: i)
  1129. var rect = KMCropTools.getPageForegroundBox(page!)
  1130. size.width = fmax(size.width, NSWidth(rect))
  1131. size.height = fmax(size.height, NSHeight(rect))
  1132. }
  1133. var rectArray: Array<NSRect> = []
  1134. for i in 0 ..< self.listView.document.pageCount {
  1135. let page = self.listView.document.page(at: i)
  1136. var rect = KMCropTools.getPageForegroundBox(page!)
  1137. var bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1138. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1139. rect.origin.x = rect.maxX-size.width
  1140. }
  1141. rect.origin.y = rect.maxY-size.height
  1142. rect.size = size
  1143. if (NSWidth(rect) > NSWidth(bounds)) {
  1144. rect.size.width = NSWidth(bounds)
  1145. }
  1146. if (NSHeight(rect) > NSHeight(bounds)) {
  1147. rect.size.height = NSHeight(bounds)
  1148. }
  1149. if (NSMinX(rect) < NSMinX(bounds)) {
  1150. rect.origin.x = NSMinX(bounds)
  1151. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1152. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1153. }
  1154. if (NSMinY(rect) < NSMinY(bounds)) {
  1155. rect.origin.y = NSMinY(bounds)
  1156. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1157. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1158. }
  1159. rectArray.append(rect)
  1160. }
  1161. cropPages(to: rectArray)
  1162. }
  1163. func cropPages(to rects: Array<NSRect>) {
  1164. let currentPage = self.listView.currentPage()
  1165. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1166. var oldRectArray: Array<NSRect> = []
  1167. for i in 0 ..< self.listView.document.pageCount {
  1168. let page = self.listView.document.page(at: i)
  1169. var rect = NSIntersectionRect(rects[Int(i)], (page?.bounds(for: .mediaBox))!)
  1170. let oldRect = page?.bounds(for: .cropBox)
  1171. oldRectArray.append(oldRect!)
  1172. page?.setBounds(rect, for: .cropBox)
  1173. }
  1174. let undoManager = self.listView.undoManager
  1175. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1176. /// 刷新预览视图
  1177. self.listView.layoutDocumentView()
  1178. self.listView.displayBox = .cropBox
  1179. self.listView.go(to: currentPage)
  1180. self.listView.go(to: visibleRect, on: currentPage)
  1181. }
  1182. private func cropCustomArea() {
  1183. self.listView.toolMode = .selectToolMode
  1184. self.listView.autoScales = true
  1185. self.listView.autoScales = false
  1186. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  1187. if (self.listView.displaysPageBreaks) {
  1188. pageHeight += 8
  1189. }
  1190. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  1191. // if (scaleFactor < self.preView.scaleFactor) {
  1192. self.listView.scaleFactor = scaleFactor
  1193. // }
  1194. let tipView = KMCropTipView()
  1195. tipView.setString(string: "请框选裁剪区域")
  1196. tipView.frame = self.topTipBox.contentView!.frame
  1197. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  1198. self.addTopTip(tipView)
  1199. tipView.enterAction = {
  1200. () in
  1201. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1202. if (NSIsEmptyRect(rect)) {
  1203. return
  1204. }
  1205. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  1206. self.view.window?.beginSheet(window.window!)
  1207. self.cropSettingWindowController = window
  1208. window.itemClick = { [self]
  1209. (index: Int) in
  1210. if (index == 1) { /// 取消
  1211. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1212. self.cropSettingWindowController = nil
  1213. return
  1214. }
  1215. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  1216. let pageCount: Int = Int(self.listView.document.pageCount)
  1217. var pages: Array<Int> = []
  1218. if (pageRangeType == 0) { /// 当前页面
  1219. pages.append(self.listView.currentPageIndex)
  1220. } else if (pageRangeType == 1) { /// 全部页面
  1221. for i in 0 ..< pageCount {
  1222. pages.append(i)
  1223. }
  1224. } else if (pageRangeType == 2) { /// 奇数页面
  1225. var string: String = ""
  1226. for i in 0 ..< pageCount {
  1227. if (i % 2 == 1) {
  1228. continue
  1229. }
  1230. pages.append(i)
  1231. }
  1232. } else if (pageRangeType == 3) { /// 偶数页面
  1233. var string: String = ""
  1234. for i in 0 ..< pageCount {
  1235. if (i % 2 == 0) {
  1236. continue
  1237. }
  1238. pages.append(i)
  1239. }
  1240. } else { /// 自定义
  1241. for i in self.cropSettingWindowController.pageRangePages {
  1242. pages.append(i)
  1243. }
  1244. }
  1245. if (pages.count < 0) {
  1246. let alert = NSAlert()
  1247. alert.messageText = "请选择页面"
  1248. alert.runModal()
  1249. return
  1250. }
  1251. var pageSize: NSSize = NSZeroSize
  1252. if (self.cropSettingWindowController.pageSize == "None") {
  1253. } else {
  1254. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  1255. }
  1256. for i in pages {
  1257. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  1258. var rect = NSIntegralRect(self.listView.selectionRect)
  1259. if (NSIsEmptyRect(rect)) {
  1260. rect = KMCropTools.getPageForegroundBox(page)
  1261. }
  1262. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  1263. page.setBounds(newRect, for: .cropBox)
  1264. if (pageSize.width == 0 && pageSize.height == 0) {
  1265. } else {
  1266. // let tiffData = page.pdfListViewTIFFData(for: rect)
  1267. let index: UInt = (page.pageIndex())
  1268. // let newPage: CPDFPage = nil
  1269. // self.listView.document.removePage(at: index)
  1270. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  1271. // let result = self.preView.document.insertPageObject(newPage, at: index)
  1272. let result = self.listView.document.insertPage(pageSize, at: index)
  1273. }
  1274. }
  1275. /// 保存到临时路径
  1276. let toPath: String = self.listView.document.documentURL.path
  1277. let documentPath = NSTemporaryDirectory()
  1278. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1279. if (FileManager.default.fileExists(atPath: tempPath)) {
  1280. try?FileManager.default.removeItem(atPath: tempPath)
  1281. }
  1282. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  1283. if (result) {
  1284. if (FileManager.default.fileExists(atPath: toPath)) {
  1285. try?FileManager.default.removeItem(atPath: toPath)
  1286. }
  1287. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1288. } else {
  1289. try?FileManager.default.removeItem(atPath: tempPath)
  1290. }
  1291. DispatchQueue.main.async {
  1292. self.listView.toolMode = .textToolMode
  1293. /// 刷新预览视图
  1294. self.listView.layoutDocumentView()
  1295. self.listView.displayBox = .cropBox
  1296. }
  1297. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1298. self.cropSettingWindowController = nil
  1299. self.addTopTip(nil)
  1300. }
  1301. }
  1302. }
  1303. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1304. if (limit) {
  1305. var doucumentURL : URL = self.listView.document.documentURL
  1306. if doucumentURL != nil {
  1307. let docDir = NSTemporaryDirectory()
  1308. let documentName : String = doucumentURL.path.lastPathComponent
  1309. let path = docDir.stringByAppendingPathComponent(documentName)
  1310. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1311. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1312. let writeSuccess = data != nil
  1313. if writeSuccess == false {
  1314. __NSBeep()
  1315. return;
  1316. }
  1317. doucumentURL = URL(fileURLWithPath: path)
  1318. }
  1319. let array = [doucumentURL]
  1320. let picker = NSSharingServicePicker.init(items: array)
  1321. if sender.shareButton.window != nil {
  1322. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1323. } else {
  1324. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1325. }
  1326. return
  1327. }
  1328. var doucumentURL : URL = self.listView.document.documentURL
  1329. if doucumentURL != nil {
  1330. let docDir = NSTemporaryDirectory()
  1331. let documentName : String = doucumentURL.path.lastPathComponent
  1332. let path = docDir.stringByAppendingPathComponent(documentName)
  1333. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1334. if writeSuccess == false {
  1335. __NSBeep()
  1336. return;
  1337. }
  1338. doucumentURL = URL(fileURLWithPath: path)
  1339. }
  1340. let array = [doucumentURL]
  1341. let picker = NSSharingServicePicker.init(items: array)
  1342. if sender.shareButton.window != nil {
  1343. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1344. } else {
  1345. 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)
  1346. }
  1347. }
  1348. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1349. if (limit) {
  1350. let document = self.listView.document ?? CPDFDocument()
  1351. var path = document!.documentURL.path
  1352. if path != nil {
  1353. let docDir = NSTemporaryDirectory()
  1354. let documentName : String = path.lastPathComponent
  1355. path = docDir.stringByAppendingPathComponent(documentName)
  1356. }
  1357. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1358. var tfileName = path.deletingPathExtension.lastPathComponent
  1359. let tStdFileSuffix = "_flatten"
  1360. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1361. path = pathFolder + "/" + tfileName
  1362. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path))
  1363. let success = data != nil
  1364. if success {
  1365. let url = URL(fileURLWithPath: path)
  1366. let picker = NSSharingServicePicker.init(items: [url])
  1367. if sender.shareButton.window != nil {
  1368. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1369. } else {
  1370. 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)
  1371. }
  1372. }
  1373. return
  1374. }
  1375. let document = self.listView.document ?? CPDFDocument()
  1376. var path = document!.documentURL.path
  1377. if path != nil {
  1378. let docDir = NSTemporaryDirectory()
  1379. let documentName : String = path.lastPathComponent
  1380. path = docDir.stringByAppendingPathComponent(documentName)
  1381. }
  1382. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1383. var tfileName = path.deletingPathExtension.lastPathComponent
  1384. let tStdFileSuffix = "_flatten"
  1385. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1386. path = pathFolder + "/" + tfileName
  1387. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  1388. if success {
  1389. let url = URL(fileURLWithPath: path)
  1390. let picker = NSSharingServicePicker.init(items: [url])
  1391. if sender.shareButton.window != nil {
  1392. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1393. } else {
  1394. 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)
  1395. }
  1396. }
  1397. }
  1398. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  1399. if (limit) {
  1400. let document = self.listView.document ?? CPDFDocument()
  1401. var path = document!.documentURL.path
  1402. if path != nil {
  1403. let docDir = NSTemporaryDirectory()
  1404. let documentName : String = path.lastPathComponent
  1405. path = docDir.stringByAppendingPathComponent(documentName)
  1406. }
  1407. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1408. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1409. var writeSuccess = data != nil
  1410. if writeSuccess == false {
  1411. __NSBeep()
  1412. return;
  1413. }
  1414. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1415. for i in 0 ... newDocument.pageCount-1 {
  1416. let page = newDocument.page(at: i)
  1417. var annotations : [CPDFAnnotation] = []
  1418. for annotation in page!.annotations {
  1419. annotations.append(annotation)
  1420. }
  1421. for annotation in annotations {
  1422. annotation.page.removeAnnotation(annotation)
  1423. }
  1424. }
  1425. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1426. if writeSuccess {
  1427. let url = URL(fileURLWithPath: path)
  1428. let picker = NSSharingServicePicker.init(items: [url])
  1429. if sender.shareButton.window != nil {
  1430. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1431. } else {
  1432. 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)
  1433. }
  1434. }
  1435. return
  1436. }
  1437. let document = self.listView.document ?? CPDFDocument()
  1438. var path = document!.documentURL.path
  1439. if path != nil {
  1440. let docDir = NSTemporaryDirectory()
  1441. let documentName : String = path.lastPathComponent
  1442. path = docDir.stringByAppendingPathComponent(documentName)
  1443. }
  1444. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1445. if writeSuccess == false {
  1446. __NSBeep()
  1447. return;
  1448. }
  1449. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1450. for i in 0 ... newDocument.pageCount-1 {
  1451. let page = newDocument.page(at: i)
  1452. var annotations : [CPDFAnnotation] = []
  1453. for annotation in page!.annotations {
  1454. annotations.append(annotation)
  1455. }
  1456. for annotation in annotations {
  1457. annotation.page.removeAnnotation(annotation)
  1458. }
  1459. }
  1460. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1461. if writeSuccess {
  1462. let url = URL(fileURLWithPath: path)
  1463. let picker = NSSharingServicePicker.init(items: [url])
  1464. if sender.shareButton.window != nil {
  1465. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1466. } else {
  1467. 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)
  1468. }
  1469. }
  1470. }
  1471. // 开启/关闭左边栏
  1472. @objc func toggleLeftPane() -> Void {
  1473. // if lastLeftPanWidth >= functionWidth {
  1474. leftPanelOpen = true
  1475. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1476. // } else {
  1477. // leftPanelOpen = false
  1478. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1479. // }
  1480. }
  1481. // 开启左边栏
  1482. @objc func openLeftPane() -> Void {
  1483. leftPanelOpen = true
  1484. applyLeftSideWidth(panelWidth+functionWidth,rightSideWidth: lastRightPanWidth)
  1485. }
  1486. // 关闭左边栏
  1487. @objc func closeLeftPane() -> Void {
  1488. leftPanelOpen = false
  1489. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1490. }
  1491. // 开启/关闭右边栏
  1492. @objc func toggleRightPane() -> Void {
  1493. if lastRightPanWidth > 5 {
  1494. self.rightPanelIsOpen = false
  1495. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1496. } else {
  1497. self.rightPanelIsOpen = true
  1498. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1499. }
  1500. }
  1501. @objc func openRightPane() -> Void {
  1502. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1503. if self.rightPanelIsOpen {
  1504. return
  1505. }
  1506. self.rightPanelIsOpen = true
  1507. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  1508. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1509. }
  1510. }
  1511. @objc func closeRightPane() -> Void {
  1512. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1513. self.rightPanelIsOpen = false
  1514. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  1515. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1516. }
  1517. }
  1518. func rename(_ sender: NSNotification) -> Void {
  1519. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1520. return
  1521. }
  1522. let tabController = sender.object as? CTTabController
  1523. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1524. let outputSavePanel = NSSavePanel()
  1525. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1526. outputSavePanel.allowedFileTypes = ["pdf"]
  1527. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1528. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1529. let result = outputSavePanel.runModal()
  1530. if result == .OK {
  1531. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1532. let fileURL = pdfDocument?.documentURL
  1533. let fileManager = FileManager.default
  1534. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1535. var result = true
  1536. do {
  1537. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1538. } catch {
  1539. result = false
  1540. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1541. }
  1542. if (result) {
  1543. tabController?.title = outputSavePanel.url!.lastPathComponent
  1544. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1545. self.isSaveKeyChain = false
  1546. newPdfDocument.unlock(withPassword: self.document?.password)
  1547. if (newPdfDocument.pageCount > 0) {
  1548. self.setDocument = newPdfDocument
  1549. }
  1550. }
  1551. }
  1552. } else {
  1553. outputSavePanel.close()
  1554. }
  1555. }
  1556. }
  1557. func showInFinder(_ sender: Any) -> Void {
  1558. if sender is NSNotification {
  1559. let tabController = (sender as! NSNotification).object as? CTTabController
  1560. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1561. let file: URL = (self.myDocument?.fileURL)!
  1562. if FileManager.default.fileExists(atPath: file.path) {
  1563. NSWorkspace.shared.activateFileViewerSelecting([file])
  1564. }
  1565. }
  1566. } else {
  1567. let file: URL = (self.myDocument?.fileURL)!
  1568. if FileManager.default.fileExists(atPath: file.path) {
  1569. NSWorkspace.shared.activateFileViewerSelecting([file])
  1570. }
  1571. }
  1572. }
  1573. func showOrHideNotes() {
  1574. self.listView.hideNotes = !self.listView.hideNotes
  1575. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  1576. //BOTA 注释列表显示隐藏
  1577. self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1578. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1579. }
  1580. func closeTab(_ sender: NSNotification) -> Void {
  1581. let tabController = sender.object as? CTTabController
  1582. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1583. print("closeTab")
  1584. self.leftSideViewController.clearAnnotationFilterData()
  1585. self.leftSideViewController.clearNotification()
  1586. }
  1587. }
  1588. // MARK: -
  1589. // MARK: 显示窗口
  1590. internal func showCompressWindow(url: URL? = nil) {
  1591. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  1592. KMPrint("压缩窗口已显示")
  1593. return
  1594. }
  1595. let windowController = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  1596. self.view.window?.beginSheet(windowController.window!)
  1597. self.currentWindowController = windowController
  1598. if let _url = url {
  1599. windowController.documentURL = _url
  1600. windowController.oriDocumentUrl = self.listView.document.documentURL
  1601. } else {
  1602. windowController.documentURL = self.listView.document.documentURL
  1603. }
  1604. windowController.password = self.listView.document.password
  1605. windowController.itemClick = { [weak self] in
  1606. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1607. self?.currentWindowController = nil
  1608. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1609. }
  1610. windowController.batchAction = { [weak self] view, filePaths in
  1611. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1612. self?.currentWindowController = nil
  1613. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1614. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1615. batchWindowController.window?.makeKeyAndOrderFront("")
  1616. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path)
  1617. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1618. batchWindowController.window?.makeKeyAndOrderFront("")
  1619. }
  1620. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  1621. if (result) {
  1622. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1623. self?.currentWindowController = nil
  1624. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1625. if (openDocument) {
  1626. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1627. } else {
  1628. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1629. }
  1630. } else {
  1631. let alert = NSAlert()
  1632. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1633. alert.runModal()
  1634. }
  1635. }
  1636. }
  1637. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1638. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1639. KMPrint("转档窗口已显示")
  1640. return
  1641. }
  1642. var convertT: KMConvertType = .Word
  1643. var windowController: KMConvertBaseWindowController?
  1644. if (type == .word) { /// Word
  1645. convertT = .Word
  1646. } else if (type == .excel) {
  1647. convertT = .Excel
  1648. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1649. if (type == .ppt) {
  1650. convertT = .PPT
  1651. } else if (type == .rtf) {
  1652. convertT = .RTF
  1653. } else if (type == .html) {
  1654. convertT = .HTML
  1655. } else if (type == .conversion_text) {
  1656. convertT = .Text
  1657. }
  1658. } else if (type == .csv) {
  1659. convertT = .CSV
  1660. } else if (type == .conversion_image) {
  1661. windowController = KMConvertImageWindowController()
  1662. }
  1663. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  1664. var url: URL?
  1665. if (documentUrl != nil) {
  1666. url = documentUrl
  1667. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1668. } else {
  1669. url = self.listView.document.documentURL
  1670. }
  1671. self.showAllConvertWindow(convertT: convertT)
  1672. // let model = KMDocumentModel(url: url!)
  1673. // if (self.listView.document.password != nil) {
  1674. // let _ = model.unlock(self.listView.document.password)
  1675. // }
  1676. // model.currentIndex = self.listView.currentPageIndex
  1677. // windowController?.documentModel = model
  1678. //
  1679. // windowController?.itemClick = { [weak self] index in
  1680. // if (identifier != nil) {
  1681. // self?.toolbarController.cancelSelected(identifier!)
  1682. // }
  1683. //
  1684. // if (self?.currentWindowController == nil) {
  1685. // return
  1686. // }
  1687. // self?.view.window?.endSheet(self!.currentWindowController.window!)
  1688. // self?.currentWindowController = nil
  1689. // }
  1690. //
  1691. // self.view.window?.beginSheet((windowController?.window)!)
  1692. // self.currentWindowController = windowController
  1693. }
  1694. //MARK: 转档 -
  1695. func showAllConvertWindow(convertT: KMConvertType) {
  1696. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1697. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1698. var type: KMConvertWithPDFType = .WordAdvance
  1699. switch convertT {
  1700. case .Word:
  1701. break
  1702. case .Excel:
  1703. type = .Excel
  1704. case .PPT:
  1705. type = .PowerPoint
  1706. case .RTF:
  1707. type = .RTF
  1708. case .CSV:
  1709. type = .CSV
  1710. case .HTML:
  1711. type = .HTML
  1712. case .Text:
  1713. type = .Text
  1714. case .JPEG:
  1715. type = .JPEG
  1716. case .PNG:
  1717. type = .PNG
  1718. case .GIF:
  1719. type = .GIF
  1720. case .JPG:
  1721. type = .JPG
  1722. case .TIFF:
  1723. type = .TIFF
  1724. case .TGA:
  1725. type = .TGA
  1726. case .BMP:
  1727. type = .BMP
  1728. case .JP2:
  1729. type = .JPEG2000
  1730. case .AdvancedWord:
  1731. break
  1732. default:
  1733. break
  1734. }
  1735. // let document = self.document
  1736. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1737. var needShowHint = false
  1738. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  1739. needShowHint = true
  1740. } else {
  1741. var needContinue = false
  1742. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  1743. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  1744. let ss = self.document?.documentURL.path
  1745. if arr.contains(ss!) {
  1746. needContinue = false
  1747. }else {
  1748. needContinue = true
  1749. }
  1750. }else {
  1751. needContinue = true
  1752. }
  1753. if needContinue {
  1754. let ss = self.document?.documentURL.path
  1755. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  1756. file.password = document?.password ?? ""
  1757. KMBatchOperateManager.defaultManager.files?.append(file)
  1758. }
  1759. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  1760. batchWindowController.switchToConvertType(convertType: type)
  1761. }
  1762. batchWindowController.window?.makeKeyAndOrderFront(nil)
  1763. if needShowHint {
  1764. batchWindowController.showIsConvertingHint()
  1765. } else {
  1766. }
  1767. }
  1768. }
  1769. self.km_beginSheet(windowC: convertWC)
  1770. }
  1771. //MARK: 转档 - OCR
  1772. func showOCRWindow() {
  1773. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  1774. self.km_beginSheet(windowC: com)
  1775. }
  1776. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  1777. let newArr = NSMutableArray()
  1778. for item in files {
  1779. newArr.add(item.filePath)
  1780. }
  1781. return newArr as! [String]
  1782. }
  1783. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1784. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1785. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1786. if (result == .cancel) {
  1787. return
  1788. }
  1789. // 解除权限
  1790. self?.listView.document.unlock(withPassword: password)
  1791. // 隐藏提示
  1792. self?.hiddenSecureLimitTip()
  1793. // 去打印
  1794. if let data = self?.saveWatermarkFlag, !data {
  1795. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  1796. return
  1797. }
  1798. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  1799. _ = CPDFDocument(url: _url)
  1800. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  1801. } else {
  1802. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  1803. }
  1804. }
  1805. return
  1806. }
  1807. if (!self.saveWatermarkFlag) {
  1808. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  1809. return
  1810. }
  1811. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  1812. let _document = CPDFDocument(url: _url)
  1813. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  1814. } else {
  1815. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  1816. }
  1817. }
  1818. // MARK: - Split View
  1819. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  1820. }
  1821. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  1822. if !isSinglePage && isHorizontal {
  1823. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  1824. }
  1825. if (!isSinglePage && !isHorizontal) {
  1826. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  1827. }
  1828. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  1829. }
  1830. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  1831. if isSinglePage {
  1832. pdfSplitView.dividerStyle = .thin
  1833. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  1834. } else {
  1835. pdfSplitView.dividerStyle = .paneSplitter
  1836. pdfSplitView.isVertical = !isHorizontal
  1837. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  1838. if secondaryPdfView.document != nil {
  1839. // secondaryPdfView.frame = pdfSplitSecondView.frame
  1840. // pdfSplitSecondView.contentView = secondaryPdfView
  1841. } else {
  1842. openSecondaryPdfView = KMSecondaryViewController.init()
  1843. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  1844. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  1845. openSecondaryPdfView?.delegate = self
  1846. }
  1847. }
  1848. }
  1849. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  1850. if (pdfSplitView.isVertical) {
  1851. return Float(NSWidth(rect))
  1852. } else {
  1853. return Float(NSHeight(rect))
  1854. }
  1855. }
  1856. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  1857. let document = CPDFDocument.init(url: url)
  1858. if document != nil {
  1859. secondaryPdfView.frame = pdfSplitSecondView.frame
  1860. pdfSplitSecondView.contentView = secondaryPdfView
  1861. secondaryPdfView.document = nil
  1862. secondaryPdfView.document = document
  1863. return true
  1864. } else {
  1865. return false
  1866. }
  1867. }
  1868. func updateNextAndPreViousButtonState() {
  1869. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  1870. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  1871. if self.listView.canGoToNextPage() {
  1872. item?.unEnabled = false
  1873. } else {
  1874. item?.unEnabled = true
  1875. }
  1876. if self.listView.canGoToPreviousPage() {
  1877. toItem?.unEnabled = false
  1878. } else {
  1879. toItem?.unEnabled = true
  1880. }
  1881. }
  1882. func updateBackAndForwardButtonState() {
  1883. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  1884. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  1885. if self.listView.km_canGoBack() {
  1886. item?.unEnabled = false
  1887. } else {
  1888. item?.unEnabled = true
  1889. }
  1890. if self.listView.km_canGoForward() {
  1891. toItem?.unEnabled = false
  1892. } else {
  1893. toItem?.unEnabled = true
  1894. }
  1895. }
  1896. func updateZoomInOutButtonState() {
  1897. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  1898. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  1899. if self.listView.canZoomIn {
  1900. item.unEnabled = false
  1901. } else {
  1902. item.unEnabled = true
  1903. }
  1904. if self.listView.canZoomOut {
  1905. toItem.unEnabled = false
  1906. } else {
  1907. toItem.unEnabled = true
  1908. }
  1909. }
  1910. }
  1911. // MARK: -
  1912. // MARK: - KMSecondaryViewControllerDelegate
  1913. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  1914. func receivedFileUrl(_ url: URL!) {
  1915. let state = self.displaySecondaryPDFView(withUrl: url)
  1916. if !state {
  1917. let alert = NSAlert()
  1918. alert.alertStyle = .critical
  1919. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1920. alert.runModal()
  1921. return
  1922. }
  1923. }
  1924. }
  1925. // MARK: -
  1926. // MARK: - KMMainToolbarControllerDelegate
  1927. extension KMMainViewController : KMMainToolbarControllerDelegate {
  1928. func changeModelAction(mode: CToolMode) {
  1929. self.listView.toolMode = mode
  1930. if mode == .editPDFToolMode {
  1931. self.childToolbarController.updateType(newType: .editPDF)
  1932. }
  1933. }
  1934. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  1935. switch selectedTag {
  1936. case 2:
  1937. if self.listView.scaleFactor != 1.0 {
  1938. self.listView.scaleFactor = 1.0
  1939. self.listView.autoScales = false
  1940. }
  1941. break
  1942. case 1:
  1943. let pageHeight = self.listView.currentPage()!.size.height
  1944. let pdfviewHeight = self.listView.bounds.size.height
  1945. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1946. self.listView.autoScales = false
  1947. break
  1948. case 0:
  1949. // self.listView.autoScales = !self.listView.autoScales
  1950. self.listView.autoScales = true
  1951. break
  1952. case 3:
  1953. self.listView.scaleFactor = 0.1
  1954. break
  1955. case 4:
  1956. self.listView.scaleFactor = 0.25
  1957. break
  1958. case 5:
  1959. self.listView.scaleFactor = 0.5
  1960. break
  1961. case 6:
  1962. self.listView.scaleFactor = 0.75
  1963. break
  1964. case 7:
  1965. self.listView.scaleFactor = 1.0
  1966. break
  1967. case 8:
  1968. self.listView.scaleFactor = 1.5
  1969. break
  1970. case 9:
  1971. self.listView.scaleFactor = 2.0
  1972. break
  1973. case 10:
  1974. self.listView.scaleFactor = 4.0
  1975. break
  1976. case 11:
  1977. self.listView.scaleFactor = 8.0
  1978. break
  1979. case 12:
  1980. self.listView.scaleFactor = 10.0
  1981. break
  1982. default:
  1983. break
  1984. }
  1985. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1986. }
  1987. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  1988. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1989. if scale > 100 {
  1990. scale = 100
  1991. }
  1992. if (scale <= 0.101) {
  1993. self.listView.scaleFactor = self.listView.minScaleFactor()
  1994. } else {
  1995. self.listView.scaleFactor = scale
  1996. }
  1997. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1998. DispatchQueue.main.async {
  1999. self.updateZoomInOutButtonState()
  2000. }
  2001. }
  2002. func changePDFViewZoomInAction() {
  2003. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2004. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2005. switch scale {
  2006. case 0...0.25:
  2007. scale += 0.25
  2008. case 0.25...3:
  2009. scale += 0.25
  2010. case 3.1...10:
  2011. scale += 0.4
  2012. case 10.1...100:
  2013. scale += 1
  2014. default:
  2015. scale += 1
  2016. }
  2017. self.listView.scaleFactor = scale
  2018. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2019. // self.listView.zoomIn(nil)
  2020. }
  2021. func changePDFViewZoomOutAction() {
  2022. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2023. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2024. switch scale {
  2025. case 0...0.25:
  2026. scale = 0
  2027. case 0.25...3:
  2028. scale -= 0.25
  2029. case 3.1...10:
  2030. scale -= 0.4
  2031. case 10.1...100:
  2032. scale -= 1
  2033. default:
  2034. scale -= 1
  2035. }
  2036. self.listView.scaleFactor = scale
  2037. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2038. // self.listView.zoomOut(nil)
  2039. // self.updateZoomInOutButtonState()
  2040. }
  2041. func changePDFViewGotoNextPageAction() {
  2042. self.listView.km_goBack(nil)
  2043. if (self.listView.canGoToNextPage()) {
  2044. self.listView.goToNextPage(nil)
  2045. }
  2046. self.updateNextAndPreViousButtonState()
  2047. }
  2048. func changePDFViewGoToPreviousPageAction() {
  2049. if (self.listView.canGoToPreviousPage()) {
  2050. self.listView.goToPreviousPage(nil)
  2051. }
  2052. self.updateNextAndPreViousButtonState()
  2053. }
  2054. func changePDFViewGotoBackAction() {
  2055. self.listView.km_goBack(nil)
  2056. self.updateBackAndForwardButtonState()
  2057. }
  2058. func changePDFViewGoToForwardAction() {
  2059. self.listView.km_goForward(nil)
  2060. self.updateBackAndForwardButtonState()
  2061. }
  2062. func aiTranslationPDFFileAction() {
  2063. #if VERSION_DMG
  2064. #else
  2065. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  2066. KMLoginWindowController.show(window: NSApp.mainWindow!)
  2067. return
  2068. }
  2069. #endif
  2070. self.trackEvent_aiTranslate()
  2071. self._aiTranslationPDFFileAction()
  2072. // Task { @MainActor in
  2073. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2074. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  2075. // if (isClose) {
  2076. // return
  2077. // }
  2078. // if (isSub) {
  2079. // self._aiTranslationPDFFileAction()
  2080. // return
  2081. // }
  2082. // }
  2083. // return
  2084. // }
  2085. //
  2086. // self._aiTranslationPDFFileAction()
  2087. // }
  2088. }
  2089. private func _aiTranslationPDFFileAction() {
  2090. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2091. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2092. let alert = NSAlert()
  2093. alert.alertStyle = .critical
  2094. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2095. alert.runModal()
  2096. return
  2097. } else if isExceedsLimit {
  2098. let alert = NSAlert()
  2099. alert.alertStyle = .critical
  2100. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2101. alert.runModal()
  2102. return
  2103. }
  2104. let alert = NSAlert()
  2105. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2106. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2107. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2108. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2109. if (result == .alertFirstButtonReturn) {
  2110. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  2111. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  2112. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  2113. } else if result == .alertSecondButtonReturn {
  2114. return
  2115. }
  2116. }
  2117. }
  2118. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2119. self.trackEvent_share()
  2120. }
  2121. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2122. if (!self.saveWatermarkFlag) {
  2123. self.shareDocument(sender: viewController)
  2124. return
  2125. }
  2126. Task { @MainActor in
  2127. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2128. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2129. if (isClose) {
  2130. return
  2131. }
  2132. if (isSubscribeSuccess) {
  2133. self.shareDocument(sender: viewController)
  2134. return
  2135. }
  2136. if (isWaterMarkExport) {
  2137. self.shareDocument(sender: viewController, limit: true)
  2138. return
  2139. }
  2140. }
  2141. return
  2142. }
  2143. self.shareDocument(sender: viewController)
  2144. }
  2145. }
  2146. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2147. // if (!self.saveWatermarkFlag) {
  2148. // self.shareFlatten(sender: viewController)
  2149. // return
  2150. // }
  2151. Task { @MainActor in
  2152. #if VERSION_DMG
  2153. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2154. let _ = KMComparativeTableViewController.show(window: self.view.window!, .shareFlatten)
  2155. return
  2156. }
  2157. #endif
  2158. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2159. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2160. if (isClose) {
  2161. return
  2162. }
  2163. if (isSubscribeSuccess) {
  2164. self.shareFlatten(sender: viewController)
  2165. return
  2166. }
  2167. if (isWaterMarkExport) {
  2168. self.shareFlatten(sender: viewController, limit: true)
  2169. return
  2170. }
  2171. }
  2172. return
  2173. }
  2174. self.shareFlatten(sender: viewController)
  2175. }
  2176. }
  2177. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2178. if (!self.saveWatermarkFlag) {
  2179. self.shareOriginalPDF(sender: viewController)
  2180. return
  2181. }
  2182. Task { @MainActor in
  2183. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2184. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2185. if (isClose) {
  2186. return
  2187. }
  2188. if (isSubscribeSuccess) {
  2189. self.shareOriginalPDF(sender: viewController)
  2190. return
  2191. }
  2192. if (isWaterMarkExport) {
  2193. self.shareOriginalPDF(sender: viewController, limit: true)
  2194. return
  2195. }
  2196. }
  2197. return
  2198. }
  2199. self.shareOriginalPDF(sender: viewController)
  2200. }
  2201. }
  2202. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2203. if(0 == selectedTag) {
  2204. // self.documentAIViewController?.enteredIncreaseAllPage()
  2205. // self.documentAIViewController?.updateToolState(false)
  2206. } else {
  2207. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  2208. // self.documentAIViewController?.recognitionPartModel(with: .english)
  2209. // self.documentAIViewController?.updateToolState(true)
  2210. }
  2211. // 0 : Scan 1:OCR Text
  2212. }
  2213. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2214. if beforeType == .editPDF {
  2215. // self.asyncSaveDocument { params in
  2216. //
  2217. // }
  2218. }
  2219. // 埋点
  2220. self.trackEvent(toolType: type)
  2221. if(type != .Page) {
  2222. if (hasEnterPageEdit()) {
  2223. self.exitPageEdit()
  2224. }
  2225. }
  2226. if(type != .ScanOCR) {
  2227. // if ((self.documentAIViewController?.view.superview) != nil) {
  2228. // self.listView.isHidden = false
  2229. // self.documentAIViewController?.creatRecognitionDocument()
  2230. // self.documentAIViewController?.view .removeFromSuperview()
  2231. // self.documentAIViewController = nil;
  2232. // self.listView.layoutDocumentView()
  2233. // }
  2234. }
  2235. if (type == .Page) {
  2236. if (hasEnterPageEdit()) {
  2237. self.exitPageEdit()
  2238. } else {
  2239. self.enterPageEdit(pages)
  2240. }
  2241. } else if(type == .ScanOCR) {
  2242. // if((self.documentAIViewController?.view.superview) != nil) {
  2243. // let alert = NSAlert()
  2244. // alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  2245. // alert.addButton(withTitle: "YES")
  2246. // alert.addButton(withTitle: "NO")
  2247. // let result = alert.runModal()
  2248. // if (result == .alertFirstButtonReturn) { /// 取消
  2249. // self.listView.isHidden = false
  2250. // self.documentAIViewController?.creatRecognitionDocument()
  2251. // self.documentAIViewController?.view .removeFromSuperview()
  2252. // self.documentAIViewController = nil;
  2253. // self.listView.layoutDocumentView()
  2254. // } else {
  2255. // self.toolbarController.toolbarType = .ScanOCR
  2256. // }
  2257. // } else {
  2258. // self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  2259. // self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  2260. // self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  2261. // self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  2262. // self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  2263. // }
  2264. } else if type == .editPDF {
  2265. self.listView.annotationType = .editTextImage
  2266. } else if type == .Annatiton {
  2267. self.rightSideViewController.subViewType = .AnnotationProperts
  2268. }
  2269. }
  2270. func clickChildTool(type: KMToolbarType, index: Int) {
  2271. if (type == .secure) {
  2272. if (index == 1) {
  2273. self.trackEvent_setPassword()
  2274. } else if (index == 2) {
  2275. self.trackEvent_removePassword()
  2276. }
  2277. } else {
  2278. self.trackEvent(toolBarType: type)
  2279. }
  2280. Task { @MainActor in
  2281. if (type == .compress) { /// 压缩
  2282. // #if VERSION_DMG
  2283. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2284. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  2285. // self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2286. // return
  2287. // }
  2288. // #endif
  2289. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2290. // self.view.window?.contentView?.superview?.beginLoading()
  2291. let document = self.listView.document
  2292. let secureOptions = self.secureOptions
  2293. let removeSecureFlag = self.removeSecureFlag
  2294. // DispatchQueue.global().async { [unowned self] in
  2295. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  2296. // DispatchQueue.main.async {
  2297. // self.view.window?.contentView?.superview?.endLoading()
  2298. // }
  2299. return
  2300. }
  2301. // DispatchQueue.main.async {
  2302. // self.view.window?.contentView?.superview?.endLoading()
  2303. self.showCompressWindow(url: _url)
  2304. // }
  2305. // }
  2306. return
  2307. }
  2308. if (self.needSaveDocument()) {
  2309. self.saveDocumentWithProgressAlert { [unowned self] params in
  2310. self.showCompressWindow()
  2311. }
  2312. return
  2313. }
  2314. self.showCompressWindow()
  2315. return
  2316. }
  2317. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  2318. var identifier: String?
  2319. if (type == .word) { /// Word
  2320. identifier = KMToolbarConversionWordItemIdentifier
  2321. } else if (type == .excel) {
  2322. identifier = KMToolbarConversionExcelItemIdentifier
  2323. } else if (type == .ppt) {
  2324. identifier = KMToolbarConversionPPTItemIdentifier
  2325. } else if (type == .rtf) {
  2326. identifier = KMToolbarConversionRTFItemIdentifier
  2327. } else if (type == .html) {
  2328. identifier = KMToolbarConversionHTMLItemIdentifier
  2329. } else if (type == .conversion_text) {
  2330. identifier = KMToolbarConversionTextItemIdentifier
  2331. } else if (type == .csv) {
  2332. identifier = KMToolbarConversionCSVItemIdentifier
  2333. } else if (type == .conversion_image) {
  2334. identifier = KMToolbarConversionImageItemIdentifier
  2335. }
  2336. #if VERSION_DMG
  2337. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2338. // if (identifier != nil) {
  2339. // self.toolbarController.cancelSelected(identifier!)
  2340. // }
  2341. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .convert)
  2342. // return
  2343. // }
  2344. #endif
  2345. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2346. // guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2347. // return
  2348. // }
  2349. // self.showConvertWindow(type: type, documentUrl: _url, identifier: identifier)
  2350. // return
  2351. // }
  2352. if (self.needSaveDocument()) {
  2353. self.saveDocumentWithProgressAlert { [unowned self] params in
  2354. self.showConvertWindow(type: type, identifier: identifier)
  2355. }
  2356. return
  2357. }
  2358. self.showConvertWindow(type: type, identifier: identifier)
  2359. return
  2360. }
  2361. if (type == .merge) { /// 合并
  2362. // #if VERSION_DMG
  2363. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2364. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  2365. //
  2366. // self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  2367. // return
  2368. // }
  2369. // #endif
  2370. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  2371. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2372. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2373. if (result == .cancel) {
  2374. return
  2375. }
  2376. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2377. return
  2378. }
  2379. self.showMergeWindow(url: _url, password)
  2380. }
  2381. return
  2382. }
  2383. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2384. if (result == .cancel) {
  2385. return
  2386. }
  2387. if (self.needSaveDocument()) {
  2388. self.saveDocumentWithProgressAlert { [unowned self] params in
  2389. self.showMergeWindow(password)
  2390. }
  2391. return
  2392. }
  2393. self.showMergeWindow(password)
  2394. }
  2395. return
  2396. }
  2397. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2398. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2399. return
  2400. }
  2401. self.showMergeWindow(url: _url, password)
  2402. return
  2403. }
  2404. if (self.needSaveDocument()) {
  2405. self.saveDocumentWithProgressAlert { [unowned self] params in
  2406. self.showMergeWindow(self.listView.document.password)
  2407. }
  2408. return
  2409. }
  2410. self.showMergeWindow(self.listView.document.password)
  2411. return
  2412. }
  2413. if (type == .crop) {
  2414. #if VERSION_DMG
  2415. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2416. let _ = KMComparativeTableViewController.show(window: self.view.window!, .crop)
  2417. return
  2418. }
  2419. #endif
  2420. self.recordSaveWatermarkFlag(type: .crop)
  2421. if (index == 1) {
  2422. self.cropCurrentPage()
  2423. return
  2424. }
  2425. if (index == 2) {
  2426. self.cropAllPage()
  2427. return
  2428. }
  2429. //// 自定义裁剪区域
  2430. // self.cropCustomArea()
  2431. } else if (type == .bates || type == .headerAndFooter) {
  2432. if (index == 0) {
  2433. var controller: KMWatermarkAdjectivePreViewBaseController!
  2434. if (type == .bates) {
  2435. controller = KMBatesPreviewController()
  2436. } else if (type == .headerAndFooter) {
  2437. controller = KMHeaderFooterPreviewController()
  2438. } else if (type == .background) {
  2439. controller = KMBackgroundController()
  2440. } else if (type == .watermark) {
  2441. controller = KMWatermarkViewController()
  2442. }
  2443. controller.applyDocument = self.listView.document
  2444. controller.view.frame = self.view.bounds
  2445. controller.view.autoresizingMask = [.width, .height]
  2446. controller.documentURL = self.listView.document.documentURL
  2447. self.view.addSubview(controller.view)
  2448. self.addChild(controller)
  2449. controller.itemClick = { [weak self] index, param in
  2450. if (index == 0 || index == 1) { /// 取消 和 应用
  2451. var controller_watermarkAdjective_preView: KMWatermarkAdjectivePreViewBaseController?
  2452. for i in 0 ..< self!.children.count {
  2453. let vc: NSViewController = self!.children[self!.children.count-1-i]
  2454. if (vc.isKind(of: KMWatermarkAdjectivePreViewBaseController.self) == true) {
  2455. controller_watermarkAdjective_preView = vc as! KMWatermarkAdjectivePreViewBaseController
  2456. break
  2457. }
  2458. }
  2459. if (controller_watermarkAdjective_preView == nil) {
  2460. return
  2461. }
  2462. controller_watermarkAdjective_preView!.view.removeFromSuperview()
  2463. controller_watermarkAdjective_preView?.removeFromParent()
  2464. // if (index == 1) {
  2465. self?.listView.document = CPDFDocument(url: self?.listView.document.documentURL)
  2466. self?.listView.layoutDocumentView()
  2467. self?.listView.setNeedsDisplayForVisiblePages()
  2468. // }
  2469. return
  2470. }
  2471. }
  2472. return
  2473. }
  2474. if (index == 1) { /// 取消
  2475. self.toolbarController.exitWatermarkAdjective()
  2476. // self.rightSideViewController.view.isHidden = true
  2477. self.rightSideViewController.isHidden = true
  2478. self.rightSideViewController.subViewType = .None
  2479. self.closeRightPane()
  2480. return
  2481. }
  2482. if (index == 5) { /// 批量
  2483. return
  2484. }
  2485. if (index == 4) { //// 移除
  2486. if (type == .watermark) {
  2487. let watermarks = self.listView.document.watermarks()
  2488. if (watermarks == nil || watermarks!.count <= 0) {
  2489. let alert = NSAlert()
  2490. alert.alertStyle = .warning
  2491. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  2492. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  2493. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2494. alert.runModal()
  2495. return
  2496. }
  2497. let alert = NSAlert()
  2498. alert.alertStyle = .warning
  2499. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  2500. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  2501. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2502. let result = alert.runModal()
  2503. if (result != .alertFirstButtonReturn) {
  2504. return
  2505. }
  2506. }
  2507. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  2508. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  2509. result in
  2510. DispatchQueue.main.async {
  2511. self.listView.layoutDocumentView()
  2512. self.listView.setNeedsDisplayForVisiblePages()
  2513. }
  2514. if (result) {
  2515. let alert = NSAlert()
  2516. alert.alertStyle = .warning
  2517. alert.messageText = "成功"
  2518. alert.runModal()
  2519. } else {
  2520. let alert = NSAlert()
  2521. alert.alertStyle = .critical
  2522. alert.messageText = "失败"
  2523. alert.runModal()
  2524. }
  2525. }
  2526. return
  2527. }
  2528. if (index == 2) { /// 应用
  2529. let model = self.rightSideViewController.model
  2530. if (type == .bates || type == .headerAndFooter) {
  2531. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2532. let alert = NSAlert()
  2533. alert.alertStyle = .critical
  2534. alert.messageText = "没有找到模型"
  2535. alert.runModal()
  2536. return
  2537. }
  2538. if ((model as! KMBatesModel).hasVaild == false) {
  2539. let alert = NSAlert()
  2540. alert.alertStyle = .critical
  2541. alert.messageText = "没有找到内容"
  2542. alert.runModal()
  2543. return
  2544. }
  2545. }
  2546. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2547. result in
  2548. DispatchQueue.main.async {
  2549. self.listView.layoutDocumentView()
  2550. self.listView.setNeedsDisplayForVisiblePages()
  2551. }
  2552. if (result) {
  2553. let alert = NSAlert()
  2554. alert.alertStyle = .warning
  2555. alert.messageText = "成功"
  2556. alert.runModal()
  2557. } else {
  2558. let alert = NSAlert()
  2559. alert.alertStyle = .critical
  2560. alert.messageText = "失败"
  2561. alert.runModal()
  2562. }
  2563. }
  2564. return
  2565. }
  2566. /// 新增
  2567. // self.rightSideViewController.view.isHidden = false
  2568. self.rightSideViewController.isHidden = false
  2569. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2570. self.openRightPane()
  2571. } else if (type == .redact) { /// 标记密文
  2572. if (index == 1) { /// 取消
  2573. if (self.hasAddRedact) {
  2574. let alert = NSAlert()
  2575. 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: "")
  2576. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2577. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2578. let result = alert.runModal()
  2579. if (result == .alertFirstButtonReturn) {
  2580. self.listView.toolMode = .moveToolMode
  2581. self.toolbarController.exitRedact()
  2582. }
  2583. return
  2584. }
  2585. self.listView.toolMode = .moveToolMode
  2586. self.toolbarController.exitRedact()
  2587. return
  2588. }
  2589. if (index == 2) { /// 擦除
  2590. self.exeRedactConfirm(.eraserAll) {}
  2591. return
  2592. }
  2593. if (index == 3) { /// 应用
  2594. self.exeRedactConfirm(.redactAll) {}
  2595. return
  2596. }
  2597. if (index == 4) { /// 文本&图像
  2598. self.listView.toolMode = .redactToolMode
  2599. return
  2600. }
  2601. if (index == 5) { /// 页面
  2602. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2603. await self.view.window?.beginSheet(windowController.window!)
  2604. self.currentWindowController = windowController
  2605. windowController.itemClick = { [weak self] index, value in
  2606. if (index == 1) {
  2607. let topBarView = self?.toolbarController.fetchTopBarView()
  2608. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  2609. return
  2610. }
  2611. (topBarView as! KMRedactTopToolBar).selectItem(0)
  2612. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2613. self?.currentWindowController = nil
  2614. return
  2615. }
  2616. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2617. let pageType = windowController_pageRange.pageType
  2618. let pageString = windowController_pageRange.pageString
  2619. if (pageType == 5) { /// 自定义页面
  2620. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  2621. if (array.count == 0) {
  2622. let alert = NSAlert()
  2623. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2624. alert.runModal()
  2625. return
  2626. }
  2627. }
  2628. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2629. self!.currentWindowController = nil
  2630. var indexs: IndexSet = []
  2631. if (pageType == 1) { /// 当前页面
  2632. indexs.insert((self?.listView.currentPageIndex)!)
  2633. } else {
  2634. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  2635. }
  2636. if (indexs.count == 0) {
  2637. return
  2638. }
  2639. for i in indexs {
  2640. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2641. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2642. redactAnno.bounds = page.bounds
  2643. self?.listView.add(redactAnno, to: page)
  2644. }
  2645. }
  2646. return
  2647. }
  2648. } else if (type == .secure) { /// 安全
  2649. #if VERSION_DMG
  2650. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2651. let _ = KMComparativeTableViewController.show(window: self.view.window!, .secure)
  2652. return
  2653. }
  2654. #endif
  2655. if (index == 1) { /// 设置密码
  2656. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2657. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2658. if (result == .cancel) {
  2659. return
  2660. }
  2661. self?.isSaveKeyChain = false
  2662. self?.listView.document.unlock(withPassword: password)
  2663. self?.hiddenSecureLimitTip()
  2664. self?.showSecureWindow((self?.listView.document.documentURL)!)
  2665. }
  2666. return
  2667. }
  2668. self.showSecureWindow(self.listView.document.documentURL)
  2669. return
  2670. } else if index == 2 {
  2671. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  2672. self.currentWindowController = controller
  2673. controller.batchAction = { [unowned self] controller, files in
  2674. self.view.window?.endSheet((self.currentWindowController.window)!)
  2675. self.currentWindowController = nil
  2676. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2677. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2678. batchWindowController.window?.makeKeyAndOrderFront("")
  2679. let batchOperateFile = KMBatchOperateFile(filePath: files.first?.filePath ?? "")
  2680. batchWindowController.switchToOperateType(.RemovePassword, files: [batchOperateFile])
  2681. batchWindowController.window?.makeKeyAndOrderFront("")
  2682. }
  2683. controller.cancelAction = { [unowned self] controller in
  2684. self.view.window?.endSheet((self.currentWindowController.window)!)
  2685. self.currentWindowController = nil
  2686. }
  2687. controller.doneAction = { [unowned self] controller in
  2688. self.view.window?.endSheet((self.currentWindowController.window)!)
  2689. self.currentWindowController = nil
  2690. KMBaseWindowController.checkPassword(url: self.document!.documentURL!) { [unowned self] success, resultPassword in
  2691. if success {
  2692. /// 删除安全性设置
  2693. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2694. self.isSaveKeyChain = false
  2695. self.listView.document.unlock(withPassword: password)
  2696. self.hiddenSecureLimitTip()
  2697. self.recordRemoveSecureFlag()
  2698. self.recordSaveWatermarkFlag(type: .removePassword)
  2699. let tip = KMRemovePasswordResultTipView()
  2700. tip.result = .success
  2701. tip.showInView(superView: (self.listView.superview)!)
  2702. } else {
  2703. self.recordRemoveSecureFlag()
  2704. self.recordSaveWatermarkFlag(type: .removePassword)
  2705. let tip = KMRemovePasswordResultTipView()
  2706. tip.result = .success
  2707. self.hiddenSecureLimitTip()
  2708. tip.showInView(superView: self.listView.superview!)
  2709. }
  2710. }
  2711. }
  2712. }
  2713. await NSWindow.currentWindow().beginSheet(controller.window!)
  2714. return
  2715. }
  2716. } else if type == .comparison {
  2717. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  2718. self.currentWindowController = controller
  2719. controller.filePath = (self.document?.documentURL.path)!
  2720. controller.cancelAction = { [unowned self] controller in
  2721. self.view.window?.endSheet((self.currentWindowController.window)!)
  2722. self.currentWindowController = nil
  2723. }
  2724. if index == 1 {
  2725. controller.fileType = .content
  2726. } else {
  2727. controller.fileType = .coverting
  2728. }
  2729. await NSWindow.currentWindow().beginSheet(controller.window!)
  2730. } else if type == .watermark {
  2731. let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  2732. self.currentWindowController = controller
  2733. controller.cancelAction = { [unowned self] controller in
  2734. self.view.window?.endSheet((self.currentWindowController.window)!)
  2735. self.currentWindowController = nil
  2736. }
  2737. if index == 1 {
  2738. } else {
  2739. }
  2740. await NSWindow.currentWindow().beginSheet(controller.window!)
  2741. } else if type == .background {
  2742. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  2743. self.currentWindowController = controller
  2744. controller.cancelAction = { [unowned self] controller in
  2745. self.view.window?.endSheet((self.currentWindowController.window)!)
  2746. self.currentWindowController = nil
  2747. }
  2748. if index == 1 {
  2749. } else {
  2750. }
  2751. await NSWindow.currentWindow().beginSheet(controller.window!)
  2752. }
  2753. }
  2754. }
  2755. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  2756. if let itemID = toolbarItem.itemIdentifier {
  2757. if isMainToolItem(itemID) {
  2758. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  2759. Swift.debugPrint("KMDocumentHomeToolbarItemIdentifier ...")
  2760. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  2761. self.changePDFViewGoToPreviousPageAction()
  2762. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  2763. self.changePDFViewGotoNextPageAction()
  2764. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  2765. Swift.debugPrint("KMDocumentViewDisplayToolbarItemIdentifier ...")
  2766. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  2767. toolbarItem.isSelected = !toolbarItem.isSelected
  2768. self.toggleLeftPane()
  2769. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  2770. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  2771. toolbarItem.isSelected = !toolbarItem.isSelected
  2772. self.toggleRightPane()
  2773. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  2774. Swift.debugPrint("KMDocumentRedactToolbarItemIdentifier ...")
  2775. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  2776. Swift.debugPrint("KMDocumentScanOCRToolbarItemIdentifier ...")
  2777. showOCRWindow()
  2778. }
  2779. } else {
  2780. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  2781. let windowC = KMToolbarCustomWindowController()
  2782. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  2783. self.km_beginSheet(windowC: windowC)
  2784. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  2785. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  2786. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  2787. self.trackEvent_print()
  2788. self.showPrintWindow()
  2789. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  2790. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  2791. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  2792. windowC.callBack = { [weak self] string in
  2793. // if (string.length > 0) {
  2794. // [blockSelf.pdfView addTextFieldWithSubType:KMSelfSignAnnotationFreeTextSubType_Profile string:string];
  2795. // }
  2796. self?.km_endSheet()
  2797. }
  2798. self.km_beginSheet(windowC: windowC)
  2799. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  2800. Swift.debugPrint("KMToolbarViewSettingIdentifier ...")
  2801. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  2802. Swift.debugPrint("KMToolbarSnapshotIdentifier ...")
  2803. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  2804. Swift.debugPrint("KMToolbarTTSIdentifier ...")
  2805. }
  2806. }
  2807. }
  2808. }
  2809. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  2810. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  2811. KMPrint("KMToolbarToolWatermarkItemIdentifier \(index)")
  2812. self.clickChildTool(type: .watermark, index: index)
  2813. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  2814. KMPrint("KMToolbarToolBackgroundItemIdentifier \(index)")
  2815. self.clickChildTool(type: .background, index: index)
  2816. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  2817. KMPrint("KMToolbarToolHeaderFooterItemIdentifier \(index)")
  2818. self.clickChildTool(type: .headerAndFooter, index: index)
  2819. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  2820. KMPrint("KMToolbarToolBatesItemIdentifier \(index)")
  2821. self.clickChildTool(type: .bates, index: index)
  2822. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  2823. KMPrint("KMToolbarComparisonItemIdentifier \(index)")
  2824. self.clickChildTool(type: .comparison, index: index)
  2825. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  2826. KMPrint("KMToolbarToolFormAlignIdentifier \(index)")
  2827. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  2828. KMPrint("KMToolbarConversionImageItemIdentifier \(index)")
  2829. convertToImg(index: index)
  2830. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  2831. KMPrint("KMToolbarConversionExportImageItemIdentifier \(index)")
  2832. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  2833. KMPrint("KMToolbarConversionCreatePDFItemIdentifier \(index)")
  2834. self.createPdf(index: index)
  2835. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  2836. KMPrint("KMToolbarCropIdentifier \(index)")
  2837. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  2838. KMPrint("KMToolbarToolSecureItemIdentifier \(index)")
  2839. self.clickChildTool(type: .secure, index: index)
  2840. }
  2841. }
  2842. func convertToImg(index: Int) {
  2843. var convertT: KMConvertType = .JPEG
  2844. switch index {
  2845. case 7:
  2846. convertT = .JPEG
  2847. case 8:
  2848. convertT = .JPG
  2849. case 9:
  2850. convertT = .PNG
  2851. case 10:
  2852. convertT = .GIF
  2853. case 11:
  2854. convertT = .TIFF
  2855. case 12:
  2856. convertT = .TGA
  2857. case 13:
  2858. convertT = .BMP
  2859. default:
  2860. convertT = .JPEG
  2861. }
  2862. showAllConvertWindow(convertT: convertT)
  2863. }
  2864. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String) {
  2865. Swift.debugPrint("Search Result " + searchString)
  2866. }
  2867. }
  2868. // MARK: -
  2869. // MARK: - Mouse
  2870. extension KMMainViewController {
  2871. override func mouseDown(with event: NSEvent) {
  2872. super.mouseDown(with: event)
  2873. KMPrint("KMMainViewController mouseDown")
  2874. self.leftSideViewCancelSelect()
  2875. self.pageNumberDisplayView.isEdit = false
  2876. }
  2877. }
  2878. //MARK: LeftSideViewController
  2879. extension KMMainViewController {
  2880. func leftSideViewCancelSelect() {
  2881. // switch self.leftSideViewController.type.methodType {
  2882. // case .Thumbnail:
  2883. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  2884. // break
  2885. // case .Outline:
  2886. //// self.leftSideViewController.outlineViewController.cancelSelect()
  2887. // break
  2888. // case .BookMark:
  2889. //// self.leftSideViewController.bookViewController.cancelSelect()
  2890. // break
  2891. // case .Search:
  2892. //// self.leftSideViewController.searchViewController.cancelSelect()
  2893. // break
  2894. // case .Annotation:
  2895. //// self.leftSideViewController.annotationViewController.cancelSelect()
  2896. // break
  2897. // default:
  2898. if self.listView.isEditing() {
  2899. if self.listView.editingAreas() != nil &&
  2900. self.listView.editingAreas().count != 0 {
  2901. let areas = self.listView.editingAreas().first
  2902. if areas is CPDFEditTextArea {
  2903. self.listView.clearEditingSelectCharItem()
  2904. self.listView.updateEditing([])
  2905. KMPrint("取消选中")
  2906. }
  2907. }
  2908. }
  2909. KMPrint("其他")
  2910. // }
  2911. }
  2912. }
  2913. extension KMMainViewController: KMReadModelViewDelegate {
  2914. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2915. self.listView.goToFirstPage(nil)
  2916. }
  2917. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  2918. self.listView.goToPreviousPage(nil)
  2919. }
  2920. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2921. self.listView.goToNextPage(nil)
  2922. }
  2923. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2924. self.listView.goToLastPage(nil)
  2925. }
  2926. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  2927. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  2928. }
  2929. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  2930. var scale: Double = 1.0
  2931. switch type {
  2932. case .fitWidth:
  2933. self.listView.autoScales = !self.listView.autoScales
  2934. scale = self.listView.scaleFactor
  2935. break
  2936. case .actualSize:
  2937. if self.listView.scaleFactor != 1.0 {
  2938. self.listView.scaleFactor = 1.0
  2939. self.listView.autoScales = false
  2940. }
  2941. scale = self.listView.scaleFactor
  2942. break
  2943. case .autoSize:
  2944. self.listView.autoScales = true
  2945. self.listView.autoScales = false
  2946. scale = self.listView.scaleFactor
  2947. break
  2948. case ._10:
  2949. scale = 0.1
  2950. break
  2951. case ._25:
  2952. scale = 0.25
  2953. break
  2954. case ._50:
  2955. scale = 0.5
  2956. break
  2957. case ._100:
  2958. scale = 1.0
  2959. break
  2960. case ._150:
  2961. scale = 1.5
  2962. break
  2963. case ._200:
  2964. scale = 2.0
  2965. break
  2966. case ._400:
  2967. scale = 4.0
  2968. break
  2969. case ._800:
  2970. scale = 8.0
  2971. break
  2972. default:
  2973. break
  2974. }
  2975. self.listView.scaleFactor = scale
  2976. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2977. }
  2978. func cancelReadModel(view: KMReadModelView, sender: Any) {
  2979. if self.isReadMode {
  2980. self.closeReadModel()
  2981. }
  2982. }
  2983. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  2984. // if self.readModelViewWidthConstraint.constant != width {
  2985. self.readModelViewWidthConstraint.constant = width
  2986. // }
  2987. }
  2988. }
  2989. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  2990. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  2991. self.listView.go(toPageIndex: pageIndex, animated: true)
  2992. }
  2993. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  2994. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  2995. self.tipCurrentPageBoxWidthConstraint.constant = width
  2996. }
  2997. }
  2998. func commitEditingIfNeed() {
  2999. let isEdited = self.listView?.isEdited() ?? false
  3000. if isEdited || self.isPDFTextImageEdited {
  3001. self.listView.commitEditing()
  3002. }
  3003. }
  3004. }
  3005. // MARK: - Analytics (埋点)
  3006. extension KMMainViewController {
  3007. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  3008. if (type == .Annatiton) {
  3009. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Annotation", parameters: [
  3010. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3011. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3012. } else if (type == .editPDF) {
  3013. KMAnalytics.trackEvent(eventName: "Btn_Tbr_EditPDF", parameters: [
  3014. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3015. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3016. } else if (type == .Page) {
  3017. KMAnalytics.trackEvent(eventName: "Btn_Tbr_PageEdit", parameters: [
  3018. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3019. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3020. } else if (type == .Conversion) {
  3021. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Converter", parameters: [
  3022. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3023. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3024. } else if (type == .Tool) {
  3025. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Tools", parameters: [
  3026. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3027. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3028. }
  3029. }
  3030. func trackEvent_aiTranslate() -> Void {
  3031. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  3032. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3033. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3034. }
  3035. func trackEvent_print() -> Void {
  3036. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  3037. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3038. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3039. }
  3040. func trackEvent_share() -> Void {
  3041. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  3042. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3043. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3044. }
  3045. func trackEvent_upgrade() -> Void {
  3046. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  3047. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3048. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3049. }
  3050. func trackEvent(annotationType type: CAnnotationType) -> Void {
  3051. if (type == .highlight) {
  3052. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  3053. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3054. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3055. } else if (type == .underline) {
  3056. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  3057. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3058. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3059. } else if (type == .strikeOut) {
  3060. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  3061. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3062. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3063. } else if (type == .ink) {
  3064. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  3065. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3066. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3067. } else if (type == .freeText) {
  3068. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  3069. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3070. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3071. } else if (type == .anchored) {
  3072. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  3073. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3074. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3075. } else if (type == .square) {
  3076. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  3077. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3078. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3079. } else if (type == .link) {
  3080. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  3081. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3082. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3083. } else if (type == .stamp) {
  3084. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  3085. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3086. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3087. } else if (type == .signSignature) {
  3088. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  3089. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3090. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3091. } else if (type == .addText) {
  3092. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  3093. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3094. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3095. } else if (type == .addImage) {
  3096. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  3097. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3098. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3099. } else {
  3100. }
  3101. }
  3102. func trackEvent(toolMode mode: CToolMode) -> Void {
  3103. if (mode == .selectToolMode) {
  3104. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3105. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3106. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3107. } else if (mode == .moveToolMode) {
  3108. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3109. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3110. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3111. }
  3112. }
  3113. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3114. if (type == .word) {
  3115. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toWord", parameters: [
  3116. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3117. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3118. } else if (type == .excel) {
  3119. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toExcel", parameters: [
  3120. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3121. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3122. } else if (type == .ppt) {
  3123. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toPPT", parameters: [
  3124. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3125. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3126. } else if (type == .rtf) {
  3127. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toRTF", parameters: [
  3128. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3129. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3130. } else if (type == .csv) {
  3131. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toCSV", parameters: [
  3132. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3133. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3134. } else if (type == .html) {
  3135. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toHTML", parameters: [
  3136. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3137. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3138. } else if (type == .conversion_text) {
  3139. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toText", parameters: [
  3140. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3141. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3142. } else if (type == .conversion_image) {
  3143. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toImage", parameters: [
  3144. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3145. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3146. } else if (type == .compress) {
  3147. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Compress", parameters: [
  3148. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3149. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3150. } else if (type == .merge) {
  3151. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Merge", parameters: [
  3152. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3153. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3154. } else if (type == .secure) {
  3155. } else if (type == .crop) {
  3156. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Crop", parameters: [
  3157. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3158. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3159. }
  3160. }
  3161. func trackEvent_setPassword() -> Void {
  3162. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3163. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3164. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3165. }
  3166. func trackEvent_removePassword() -> Void {
  3167. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3168. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3169. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3170. }
  3171. }