KMMainViewController+Action.swift 160 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329
  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 windowController: KMConvertBaseWindowController?
  1643. if (type == .word) { /// Word
  1644. windowController = KMConvertWordWindowController()
  1645. } else if (type == .excel) {
  1646. windowController = KMConvertExcelWindowController()
  1647. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1648. windowController = KMConvertPPTsWindowController()
  1649. if (type == .ppt) {
  1650. windowController?.subType = 1
  1651. } else if (type == .rtf) {
  1652. windowController?.subType = 2
  1653. } else if (type == .html) {
  1654. windowController?.subType = 3
  1655. } else if (type == .conversion_text) {
  1656. windowController?.subType = 4
  1657. }
  1658. } else if (type == .csv) {
  1659. windowController = KMConvertCSVWindowController()
  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. let model = KMDocumentModel(url: url!)
  1672. if (self.listView.document.password != nil) {
  1673. let _ = model.unlock(self.listView.document.password)
  1674. }
  1675. model.currentIndex = self.listView.currentPageIndex
  1676. windowController?.documentModel = model
  1677. windowController?.itemClick = { [weak self] index in
  1678. if (identifier != nil) {
  1679. self?.toolbarController.cancelSelected(identifier!)
  1680. }
  1681. if (self?.currentWindowController == nil) {
  1682. return
  1683. }
  1684. self?.view.window?.endSheet(self!.currentWindowController.window!)
  1685. self?.currentWindowController = nil
  1686. }
  1687. self.view.window?.beginSheet((windowController?.window)!)
  1688. self.currentWindowController = windowController
  1689. }
  1690. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1691. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1692. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1693. if (result == .cancel) {
  1694. return
  1695. }
  1696. // 解除权限
  1697. self?.listView.document.unlock(withPassword: password)
  1698. // 隐藏提示
  1699. self?.hiddenSecureLimitTip()
  1700. // 去打印
  1701. if let data = self?.saveWatermarkFlag, !data {
  1702. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  1703. return
  1704. }
  1705. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  1706. let _document = CPDFDocument(url: _url)
  1707. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  1708. } else {
  1709. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  1710. }
  1711. }
  1712. return
  1713. }
  1714. if (!self.saveWatermarkFlag) {
  1715. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  1716. return
  1717. }
  1718. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  1719. let _document = CPDFDocument(url: _url)
  1720. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  1721. } else {
  1722. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  1723. }
  1724. }
  1725. // MARK: - Split View
  1726. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  1727. }
  1728. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  1729. if !isSinglePage && isHorizontal {
  1730. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  1731. }
  1732. if (!isSinglePage && !isHorizontal) {
  1733. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  1734. }
  1735. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  1736. }
  1737. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  1738. if isSinglePage {
  1739. pdfSplitView.dividerStyle = .thin
  1740. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  1741. } else {
  1742. pdfSplitView.dividerStyle = .paneSplitter
  1743. pdfSplitView.isVertical = !isHorizontal
  1744. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  1745. if secondaryPdfView.document != nil {
  1746. // secondaryPdfView.frame = pdfSplitSecondView.frame
  1747. // pdfSplitSecondView.contentView = secondaryPdfView
  1748. } else {
  1749. openSecondaryPdfView = KMSecondaryViewController.init()
  1750. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  1751. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  1752. openSecondaryPdfView?.delegate = self
  1753. }
  1754. }
  1755. }
  1756. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  1757. if (pdfSplitView.isVertical) {
  1758. return Float(NSWidth(rect))
  1759. } else {
  1760. return Float(NSHeight(rect))
  1761. }
  1762. }
  1763. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  1764. let document = CPDFDocument.init(url: url)
  1765. if document != nil {
  1766. secondaryPdfView.frame = pdfSplitSecondView.frame
  1767. pdfSplitSecondView.contentView = secondaryPdfView
  1768. secondaryPdfView.document = nil
  1769. secondaryPdfView.document = document
  1770. return true
  1771. } else {
  1772. return false
  1773. }
  1774. }
  1775. func updateNextAndPreViousButtonState() {
  1776. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  1777. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  1778. if self.listView.canGoToNextPage() {
  1779. item?.unEnabled = false
  1780. } else {
  1781. item?.unEnabled = true
  1782. }
  1783. if self.listView.canGoToPreviousPage() {
  1784. toItem?.unEnabled = false
  1785. } else {
  1786. toItem?.unEnabled = true
  1787. }
  1788. }
  1789. func updateBackAndForwardButtonState() {
  1790. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  1791. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  1792. if self.listView.km_canGoBack() {
  1793. item?.unEnabled = false
  1794. } else {
  1795. item?.unEnabled = true
  1796. }
  1797. if self.listView.km_canGoForward() {
  1798. toItem?.unEnabled = false
  1799. } else {
  1800. toItem?.unEnabled = true
  1801. }
  1802. }
  1803. func updateZoomInOutButtonState() {
  1804. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  1805. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  1806. if self.listView.canZoomIn {
  1807. item.unEnabled = false
  1808. } else {
  1809. item.unEnabled = true
  1810. }
  1811. if self.listView.canZoomOut {
  1812. toItem.unEnabled = false
  1813. } else {
  1814. toItem.unEnabled = true
  1815. }
  1816. }
  1817. }
  1818. // MARK: -
  1819. // MARK: - KMSecondaryViewControllerDelegate
  1820. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  1821. func receivedFileUrl(_ url: URL!) {
  1822. let state = self.displaySecondaryPDFView(withUrl: url)
  1823. if !state {
  1824. let alert = NSAlert()
  1825. alert.alertStyle = .critical
  1826. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1827. alert.runModal()
  1828. return
  1829. }
  1830. }
  1831. }
  1832. // MARK: -
  1833. // MARK: - KMMainToolbarControllerDelegate
  1834. extension KMMainViewController : KMMainToolbarControllerDelegate {
  1835. func changeModelAction(mode: CToolMode) {
  1836. self.listView.toolMode = mode
  1837. if mode == .editPDFToolMode {
  1838. self.childToolbarController.updateType(newType: .editPDF)
  1839. }
  1840. }
  1841. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  1842. switch selectedTag {
  1843. case 2:
  1844. if self.listView.scaleFactor != 1.0 {
  1845. self.listView.scaleFactor = 1.0
  1846. self.listView.autoScales = false
  1847. }
  1848. break
  1849. case 1:
  1850. let pageHeight = self.listView.currentPage()!.size.height
  1851. let pdfviewHeight = self.listView.bounds.size.height
  1852. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1853. self.listView.autoScales = false
  1854. break
  1855. case 0:
  1856. // self.listView.autoScales = !self.listView.autoScales
  1857. self.listView.autoScales = true
  1858. break
  1859. case 3:
  1860. self.listView.scaleFactor = 0.1
  1861. break
  1862. case 4:
  1863. self.listView.scaleFactor = 0.25
  1864. break
  1865. case 5:
  1866. self.listView.scaleFactor = 0.5
  1867. break
  1868. case 6:
  1869. self.listView.scaleFactor = 0.75
  1870. break
  1871. case 7:
  1872. self.listView.scaleFactor = 1.0
  1873. break
  1874. case 8:
  1875. self.listView.scaleFactor = 1.5
  1876. break
  1877. case 9:
  1878. self.listView.scaleFactor = 2.0
  1879. break
  1880. case 10:
  1881. self.listView.scaleFactor = 4.0
  1882. break
  1883. case 11:
  1884. self.listView.scaleFactor = 8.0
  1885. break
  1886. case 12:
  1887. self.listView.scaleFactor = 10.0
  1888. break
  1889. default:
  1890. break
  1891. }
  1892. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1893. }
  1894. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  1895. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1896. if scale > 100 {
  1897. scale = 100
  1898. }
  1899. if (scale <= 0.101) {
  1900. self.listView.scaleFactor = self.listView.minScaleFactor()
  1901. } else {
  1902. self.listView.scaleFactor = scale
  1903. }
  1904. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1905. DispatchQueue.main.async {
  1906. self.updateZoomInOutButtonState()
  1907. }
  1908. }
  1909. func changePDFViewZoomInAction() {
  1910. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  1911. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1912. switch scale {
  1913. case 0...0.25:
  1914. scale += 0.25
  1915. case 0.25...3:
  1916. scale += 0.25
  1917. case 3.1...10:
  1918. scale += 0.4
  1919. case 10.1...100:
  1920. scale += 1
  1921. default:
  1922. scale += 1
  1923. }
  1924. self.listView.scaleFactor = scale
  1925. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  1926. // self.listView.zoomIn(nil)
  1927. }
  1928. func changePDFViewZoomOutAction() {
  1929. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  1930. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1931. switch scale {
  1932. case 0...0.25:
  1933. scale = 0
  1934. case 0.25...3:
  1935. scale -= 0.25
  1936. case 3.1...10:
  1937. scale -= 0.4
  1938. case 10.1...100:
  1939. scale -= 1
  1940. default:
  1941. scale -= 1
  1942. }
  1943. self.listView.scaleFactor = scale
  1944. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  1945. // self.listView.zoomOut(nil)
  1946. // self.updateZoomInOutButtonState()
  1947. }
  1948. func changePDFViewGotoNextPageAction() {
  1949. self.listView.km_goBack(nil)
  1950. if (self.listView.canGoToNextPage()) {
  1951. self.listView.goToNextPage(nil)
  1952. }
  1953. self.updateNextAndPreViousButtonState()
  1954. }
  1955. func changePDFViewGoToPreviousPageAction() {
  1956. if (self.listView.canGoToPreviousPage()) {
  1957. self.listView.goToPreviousPage(nil)
  1958. }
  1959. self.updateNextAndPreViousButtonState()
  1960. }
  1961. func changePDFViewGotoBackAction() {
  1962. self.listView.km_goBack(nil)
  1963. self.updateBackAndForwardButtonState()
  1964. }
  1965. func changePDFViewGoToForwardAction() {
  1966. self.listView.km_goForward(nil)
  1967. self.updateBackAndForwardButtonState()
  1968. }
  1969. func aiTranslationPDFFileAction() {
  1970. #if VERSION_DMG
  1971. #else
  1972. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  1973. KMLoginWindowController.show(window: NSApp.mainWindow!)
  1974. return
  1975. }
  1976. #endif
  1977. self.trackEvent_aiTranslate()
  1978. self._aiTranslationPDFFileAction()
  1979. // Task { @MainActor in
  1980. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  1981. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  1982. // if (isClose) {
  1983. // return
  1984. // }
  1985. // if (isSub) {
  1986. // self._aiTranslationPDFFileAction()
  1987. // return
  1988. // }
  1989. // }
  1990. // return
  1991. // }
  1992. //
  1993. // self._aiTranslationPDFFileAction()
  1994. // }
  1995. }
  1996. private func _aiTranslationPDFFileAction() {
  1997. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  1998. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  1999. let alert = NSAlert()
  2000. alert.alertStyle = .critical
  2001. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2002. alert.runModal()
  2003. return
  2004. } else if isExceedsLimit {
  2005. let alert = NSAlert()
  2006. alert.alertStyle = .critical
  2007. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2008. alert.runModal()
  2009. return
  2010. }
  2011. let alert = NSAlert()
  2012. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2013. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2014. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2015. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2016. if (result == .alertFirstButtonReturn) {
  2017. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  2018. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  2019. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  2020. } else if result == .alertSecondButtonReturn {
  2021. return
  2022. }
  2023. }
  2024. }
  2025. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2026. self.trackEvent_share()
  2027. }
  2028. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2029. if (!self.saveWatermarkFlag) {
  2030. self.shareDocument(sender: viewController)
  2031. return
  2032. }
  2033. Task { @MainActor in
  2034. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2035. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2036. if (isClose) {
  2037. return
  2038. }
  2039. if (isSubscribeSuccess) {
  2040. self.shareDocument(sender: viewController)
  2041. return
  2042. }
  2043. if (isWaterMarkExport) {
  2044. self.shareDocument(sender: viewController, limit: true)
  2045. return
  2046. }
  2047. }
  2048. return
  2049. }
  2050. self.shareDocument(sender: viewController)
  2051. }
  2052. }
  2053. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2054. // if (!self.saveWatermarkFlag) {
  2055. // self.shareFlatten(sender: viewController)
  2056. // return
  2057. // }
  2058. Task { @MainActor in
  2059. #if VERSION_DMG
  2060. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2061. let _ = KMComparativeTableViewController.show(window: self.view.window!, .shareFlatten)
  2062. return
  2063. }
  2064. #endif
  2065. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2066. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2067. if (isClose) {
  2068. return
  2069. }
  2070. if (isSubscribeSuccess) {
  2071. self.shareFlatten(sender: viewController)
  2072. return
  2073. }
  2074. if (isWaterMarkExport) {
  2075. self.shareFlatten(sender: viewController, limit: true)
  2076. return
  2077. }
  2078. }
  2079. return
  2080. }
  2081. self.shareFlatten(sender: viewController)
  2082. }
  2083. }
  2084. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2085. if (!self.saveWatermarkFlag) {
  2086. self.shareOriginalPDF(sender: viewController)
  2087. return
  2088. }
  2089. Task { @MainActor in
  2090. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2091. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2092. if (isClose) {
  2093. return
  2094. }
  2095. if (isSubscribeSuccess) {
  2096. self.shareOriginalPDF(sender: viewController)
  2097. return
  2098. }
  2099. if (isWaterMarkExport) {
  2100. self.shareOriginalPDF(sender: viewController, limit: true)
  2101. return
  2102. }
  2103. }
  2104. return
  2105. }
  2106. self.shareOriginalPDF(sender: viewController)
  2107. }
  2108. }
  2109. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2110. if(0 == selectedTag) {
  2111. // self.documentAIViewController?.enteredIncreaseAllPage()
  2112. // self.documentAIViewController?.updateToolState(false)
  2113. } else {
  2114. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  2115. // self.documentAIViewController?.recognitionPartModel(with: .english)
  2116. // self.documentAIViewController?.updateToolState(true)
  2117. }
  2118. // 0 : Scan 1:OCR Text
  2119. }
  2120. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2121. if beforeType == .editPDF {
  2122. // self.asyncSaveDocument { params in
  2123. //
  2124. // }
  2125. }
  2126. // 埋点
  2127. self.trackEvent(toolType: type)
  2128. if(type != .Page) {
  2129. if (hasEnterPageEdit()) {
  2130. self.exitPageEdit()
  2131. }
  2132. }
  2133. if(type != .ScanOCR) {
  2134. // if ((self.documentAIViewController?.view.superview) != nil) {
  2135. // self.listView.isHidden = false
  2136. // self.documentAIViewController?.creatRecognitionDocument()
  2137. // self.documentAIViewController?.view .removeFromSuperview()
  2138. // self.documentAIViewController = nil;
  2139. // self.listView.layoutDocumentView()
  2140. // }
  2141. }
  2142. if (type == .Page) {
  2143. if (hasEnterPageEdit()) {
  2144. self.exitPageEdit()
  2145. } else {
  2146. self.enterPageEdit(pages)
  2147. }
  2148. } else if(type == .ScanOCR) {
  2149. // if((self.documentAIViewController?.view.superview) != nil) {
  2150. // let alert = NSAlert()
  2151. // alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  2152. // alert.addButton(withTitle: "YES")
  2153. // alert.addButton(withTitle: "NO")
  2154. // let result = alert.runModal()
  2155. // if (result == .alertFirstButtonReturn) { /// 取消
  2156. // self.listView.isHidden = false
  2157. // self.documentAIViewController?.creatRecognitionDocument()
  2158. // self.documentAIViewController?.view .removeFromSuperview()
  2159. // self.documentAIViewController = nil;
  2160. // self.listView.layoutDocumentView()
  2161. // } else {
  2162. // self.toolbarController.toolbarType = .ScanOCR
  2163. // }
  2164. // } else {
  2165. // self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  2166. // self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  2167. // self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  2168. // self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  2169. // self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  2170. // }
  2171. } else if type == .editPDF {
  2172. self.listView.annotationType = .editTextImage
  2173. } else if type == .Annatiton {
  2174. self.rightSideViewController.subViewType = .AnnotationProperts
  2175. }
  2176. }
  2177. func clickChildTool(type: KMToolbarType, index: Int) {
  2178. if (type == .secure) {
  2179. if (index == 1) {
  2180. self.trackEvent_setPassword()
  2181. } else if (index == 2) {
  2182. self.trackEvent_removePassword()
  2183. }
  2184. } else {
  2185. self.trackEvent(toolBarType: type)
  2186. }
  2187. Task { @MainActor in
  2188. if (type == .compress) { /// 压缩
  2189. // #if VERSION_DMG
  2190. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2191. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  2192. // self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2193. // return
  2194. // }
  2195. // #endif
  2196. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2197. // self.view.window?.contentView?.superview?.beginLoading()
  2198. let document = self.listView.document
  2199. let secureOptions = self.secureOptions
  2200. let removeSecureFlag = self.removeSecureFlag
  2201. // DispatchQueue.global().async { [unowned self] in
  2202. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  2203. // DispatchQueue.main.async {
  2204. // self.view.window?.contentView?.superview?.endLoading()
  2205. // }
  2206. return
  2207. }
  2208. // DispatchQueue.main.async {
  2209. // self.view.window?.contentView?.superview?.endLoading()
  2210. self.showCompressWindow(url: _url)
  2211. // }
  2212. // }
  2213. return
  2214. }
  2215. if (self.needSaveDocument()) {
  2216. self.saveDocumentWithProgressAlert { [unowned self] params in
  2217. self.showCompressWindow()
  2218. }
  2219. return
  2220. }
  2221. self.showCompressWindow()
  2222. return
  2223. }
  2224. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  2225. var identifier: String?
  2226. if (type == .word) { /// Word
  2227. identifier = KMToolbarConversionWordItemIdentifier
  2228. } else if (type == .excel) {
  2229. identifier = KMToolbarConversionExcelItemIdentifier
  2230. } else if (type == .ppt) {
  2231. identifier = KMToolbarConversionPPTItemIdentifier
  2232. } else if (type == .rtf) {
  2233. identifier = KMToolbarConversionRTFItemIdentifier
  2234. } else if (type == .html) {
  2235. identifier = KMToolbarConversionHTMLItemIdentifier
  2236. } else if (type == .conversion_text) {
  2237. identifier = KMToolbarConversionTextItemIdentifier
  2238. } else if (type == .csv) {
  2239. identifier = KMToolbarConversionCSVItemIdentifier
  2240. } else if (type == .conversion_image) {
  2241. identifier = KMToolbarConversionImageItemIdentifier
  2242. }
  2243. #if VERSION_DMG
  2244. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2245. // if (identifier != nil) {
  2246. // self.toolbarController.cancelSelected(identifier!)
  2247. // }
  2248. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .convert)
  2249. // return
  2250. // }
  2251. #endif
  2252. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2253. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2254. return
  2255. }
  2256. self.showConvertWindow(type: type, documentUrl: _url, identifier: identifier)
  2257. return
  2258. }
  2259. if (self.needSaveDocument()) {
  2260. self.saveDocumentWithProgressAlert { [unowned self] params in
  2261. self.showConvertWindow(type: type, identifier: identifier)
  2262. }
  2263. return
  2264. }
  2265. self.showConvertWindow(type: type, identifier: identifier)
  2266. return
  2267. }
  2268. if (type == .merge) { /// 合并
  2269. // #if VERSION_DMG
  2270. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2271. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  2272. //
  2273. // self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  2274. // return
  2275. // }
  2276. // #endif
  2277. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  2278. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2279. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2280. if (result == .cancel) {
  2281. return
  2282. }
  2283. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2284. return
  2285. }
  2286. self.showMergeWindow(url: _url, password)
  2287. }
  2288. return
  2289. }
  2290. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2291. if (result == .cancel) {
  2292. return
  2293. }
  2294. if (self.needSaveDocument()) {
  2295. self.saveDocumentWithProgressAlert { [unowned self] params in
  2296. self.showMergeWindow(password)
  2297. }
  2298. return
  2299. }
  2300. self.showMergeWindow(password)
  2301. }
  2302. return
  2303. }
  2304. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2305. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2306. return
  2307. }
  2308. self.showMergeWindow(url: _url, password)
  2309. return
  2310. }
  2311. if (self.needSaveDocument()) {
  2312. self.saveDocumentWithProgressAlert { [unowned self] params in
  2313. self.showMergeWindow(self.listView.document.password)
  2314. }
  2315. return
  2316. }
  2317. self.showMergeWindow(self.listView.document.password)
  2318. return
  2319. }
  2320. if (type == .crop) {
  2321. #if VERSION_DMG
  2322. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2323. let _ = KMComparativeTableViewController.show(window: self.view.window!, .crop)
  2324. return
  2325. }
  2326. #endif
  2327. self.recordSaveWatermarkFlag(type: .crop)
  2328. if (index == 1) {
  2329. self.cropCurrentPage()
  2330. return
  2331. }
  2332. if (index == 2) {
  2333. self.cropAllPage()
  2334. return
  2335. }
  2336. //// 自定义裁剪区域
  2337. // self.cropCustomArea()
  2338. } else if (type == .bates || type == .headerAndFooter || type == .background || type == .watermark) {
  2339. if (index == 0) {
  2340. var controller: KMWatermarkAdjectivePreViewBaseController!
  2341. if (type == .bates) {
  2342. controller = KMBatesPreviewController()
  2343. } else if (type == .headerAndFooter) {
  2344. controller = KMHeaderFooterPreviewController()
  2345. } else if (type == .background) {
  2346. controller = KMBackgroundController()
  2347. } else if (type == .watermark) {
  2348. controller = KMWatermarkViewController()
  2349. }
  2350. controller.applyDocument = self.listView.document
  2351. controller.view.frame = self.view.bounds
  2352. controller.view.autoresizingMask = [.width, .height]
  2353. controller.documentURL = self.listView.document.documentURL
  2354. self.view.addSubview(controller.view)
  2355. self.addChild(controller)
  2356. controller.itemClick = { [weak self] index, param in
  2357. if (index == 0 || index == 1) { /// 取消 和 应用
  2358. var controller_watermarkAdjective_preView: KMWatermarkAdjectivePreViewBaseController?
  2359. for i in 0 ..< self!.children.count {
  2360. let vc: NSViewController = self!.children[self!.children.count-1-i]
  2361. if (vc.isKind(of: KMWatermarkAdjectivePreViewBaseController.self) == true) {
  2362. controller_watermarkAdjective_preView = vc as! KMWatermarkAdjectivePreViewBaseController
  2363. break
  2364. }
  2365. }
  2366. if (controller_watermarkAdjective_preView == nil) {
  2367. return
  2368. }
  2369. controller_watermarkAdjective_preView!.view.removeFromSuperview()
  2370. controller_watermarkAdjective_preView?.removeFromParent()
  2371. // if (index == 1) {
  2372. self?.listView.document = CPDFDocument(url: self?.listView.document.documentURL)
  2373. self?.listView.layoutDocumentView()
  2374. self?.listView.setNeedsDisplayForVisiblePages()
  2375. // }
  2376. return
  2377. }
  2378. }
  2379. return
  2380. }
  2381. if (index == 1) { /// 取消
  2382. self.toolbarController.exitWatermarkAdjective()
  2383. // self.rightSideViewController.view.isHidden = true
  2384. self.rightSideViewController.isHidden = true
  2385. self.rightSideViewController.subViewType = .None
  2386. self.closeRightPane()
  2387. return
  2388. }
  2389. if (index == 5) { /// 批量
  2390. return
  2391. }
  2392. if (index == 4) { //// 移除
  2393. if (type == .watermark) {
  2394. let watermarks = self.listView.document.watermarks()
  2395. if (watermarks == nil || watermarks!.count <= 0) {
  2396. let alert = NSAlert()
  2397. alert.alertStyle = .warning
  2398. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  2399. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  2400. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2401. alert.runModal()
  2402. return
  2403. }
  2404. let alert = NSAlert()
  2405. alert.alertStyle = .warning
  2406. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  2407. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  2408. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2409. let result = alert.runModal()
  2410. if (result != .alertFirstButtonReturn) {
  2411. return
  2412. }
  2413. }
  2414. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  2415. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  2416. result in
  2417. DispatchQueue.main.async {
  2418. self.listView.layoutDocumentView()
  2419. self.listView.setNeedsDisplayForVisiblePages()
  2420. }
  2421. if (result) {
  2422. let alert = NSAlert()
  2423. alert.alertStyle = .warning
  2424. alert.messageText = "成功"
  2425. alert.runModal()
  2426. } else {
  2427. let alert = NSAlert()
  2428. alert.alertStyle = .critical
  2429. alert.messageText = "失败"
  2430. alert.runModal()
  2431. }
  2432. }
  2433. return
  2434. }
  2435. if (index == 2) { /// 应用
  2436. let model = self.rightSideViewController.model
  2437. if (type == .bates || type == .headerAndFooter) {
  2438. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2439. let alert = NSAlert()
  2440. alert.alertStyle = .critical
  2441. alert.messageText = "没有找到模型"
  2442. alert.runModal()
  2443. return
  2444. }
  2445. if ((model as! KMBatesModel).hasVaild == false) {
  2446. let alert = NSAlert()
  2447. alert.alertStyle = .critical
  2448. alert.messageText = "没有找到内容"
  2449. alert.runModal()
  2450. return
  2451. }
  2452. }
  2453. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2454. result in
  2455. DispatchQueue.main.async {
  2456. self.listView.layoutDocumentView()
  2457. self.listView.setNeedsDisplayForVisiblePages()
  2458. }
  2459. if (result) {
  2460. let alert = NSAlert()
  2461. alert.alertStyle = .warning
  2462. alert.messageText = "成功"
  2463. alert.runModal()
  2464. } else {
  2465. let alert = NSAlert()
  2466. alert.alertStyle = .critical
  2467. alert.messageText = "失败"
  2468. alert.runModal()
  2469. }
  2470. }
  2471. return
  2472. }
  2473. /// 新增
  2474. // self.rightSideViewController.view.isHidden = false
  2475. self.rightSideViewController.isHidden = false
  2476. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2477. self.openRightPane()
  2478. } else if (type == .redact) { /// 标记密文
  2479. if (index == 1) { /// 取消
  2480. if (self.hasAddRedact) {
  2481. let alert = NSAlert()
  2482. 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: "")
  2483. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2484. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2485. let result = alert.runModal()
  2486. if (result == .alertFirstButtonReturn) {
  2487. self.listView.toolMode = .moveToolMode
  2488. self.toolbarController.exitRedact()
  2489. }
  2490. return
  2491. }
  2492. self.listView.toolMode = .moveToolMode
  2493. self.toolbarController.exitRedact()
  2494. return
  2495. }
  2496. if (index == 2) { /// 擦除
  2497. self.exeRedactConfirm(.eraserAll) {}
  2498. return
  2499. }
  2500. if (index == 3) { /// 应用
  2501. self.exeRedactConfirm(.redactAll) {}
  2502. return
  2503. }
  2504. if (index == 4) { /// 文本&图像
  2505. self.listView.toolMode = .redactToolMode
  2506. return
  2507. }
  2508. if (index == 5) { /// 页面
  2509. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2510. await self.view.window?.beginSheet(windowController.window!)
  2511. self.currentWindowController = windowController
  2512. windowController.itemClick = { [weak self] index, value in
  2513. if (index == 1) {
  2514. let topBarView = self?.toolbarController.fetchTopBarView()
  2515. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  2516. return
  2517. }
  2518. (topBarView as! KMRedactTopToolBar).selectItem(0)
  2519. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2520. self?.currentWindowController = nil
  2521. return
  2522. }
  2523. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2524. let pageType = windowController_pageRange.pageType
  2525. let pageString = windowController_pageRange.pageString
  2526. if (pageType == 5) { /// 自定义页面
  2527. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  2528. if (array.count == 0) {
  2529. let alert = NSAlert()
  2530. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2531. alert.runModal()
  2532. return
  2533. }
  2534. }
  2535. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2536. self!.currentWindowController = nil
  2537. var indexs: IndexSet = []
  2538. if (pageType == 1) { /// 当前页面
  2539. indexs.insert((self?.listView.currentPageIndex)!)
  2540. } else {
  2541. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  2542. }
  2543. if (indexs.count == 0) {
  2544. return
  2545. }
  2546. for i in indexs {
  2547. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2548. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2549. redactAnno.bounds = page.bounds
  2550. self?.listView.add(redactAnno, to: page)
  2551. }
  2552. }
  2553. return
  2554. }
  2555. } else if (type == .secure) { /// 安全
  2556. #if VERSION_DMG
  2557. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2558. let _ = KMComparativeTableViewController.show(window: self.view.window!, .secure)
  2559. return
  2560. }
  2561. #endif
  2562. if (index == 1) { /// 设置密码
  2563. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2564. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2565. if (result == .cancel) {
  2566. return
  2567. }
  2568. self?.isSaveKeyChain = false
  2569. self?.listView.document.unlock(withPassword: password)
  2570. self?.hiddenSecureLimitTip()
  2571. self?.showSecureWindow((self?.listView.document.documentURL)!)
  2572. }
  2573. return
  2574. }
  2575. self.showSecureWindow(self.listView.document.documentURL)
  2576. return
  2577. }
  2578. /// 删除安全性设置
  2579. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2580. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2581. if (result == .cancel) {
  2582. return
  2583. }
  2584. self?.isSaveKeyChain = false
  2585. self?.listView.document.unlock(withPassword: password)
  2586. self?.hiddenSecureLimitTip()
  2587. self?.recordRemoveSecureFlag()
  2588. self?.recordSaveWatermarkFlag(type: .removePassword)
  2589. let tip = KMRemovePasswordResultTipView()
  2590. tip.result = .success
  2591. tip.showInView(superView: (self?.listView.superview)!)
  2592. }
  2593. return
  2594. }
  2595. let alert = NSAlert()
  2596. alert.messageText = NSLocalizedString("Are you sure you want to remove the security settings for the file?", comment: "")
  2597. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2598. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2599. let response = alert.runModal()
  2600. if (response != .alertFirstButtonReturn) {
  2601. return
  2602. }
  2603. self.recordRemoveSecureFlag()
  2604. self.recordSaveWatermarkFlag(type: .removePassword)
  2605. let tip = KMRemovePasswordResultTipView()
  2606. tip.result = .success
  2607. self.hiddenSecureLimitTip()
  2608. tip.showInView(superView: self.listView.superview!)
  2609. }
  2610. }
  2611. }
  2612. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  2613. if let itemID = toolbarItem.itemIdentifier {
  2614. if isMainToolItem(itemID) {
  2615. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  2616. Swift.debugPrint("KMDocumentHomeToolbarItemIdentifier ...")
  2617. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  2618. self.changePDFViewGoToPreviousPageAction()
  2619. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  2620. self.changePDFViewGotoNextPageAction()
  2621. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  2622. Swift.debugPrint("KMDocumentViewDisplayToolbarItemIdentifier ...")
  2623. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  2624. toolbarItem.isSelected = !toolbarItem.isSelected
  2625. self.toggleLeftPane()
  2626. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  2627. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  2628. toolbarItem.isSelected = !toolbarItem.isSelected
  2629. self.toggleRightPane()
  2630. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  2631. Swift.debugPrint("KMDocumentRedactToolbarItemIdentifier ...")
  2632. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  2633. Swift.debugPrint("KMDocumentScanOCRToolbarItemIdentifier ...")
  2634. }
  2635. } else {
  2636. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  2637. let windowC = KMToolbarCustomWindowController()
  2638. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  2639. self.km_beginSheet(windowC: windowC)
  2640. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  2641. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  2642. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  2643. self.trackEvent_print()
  2644. self.showPrintWindow()
  2645. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  2646. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  2647. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  2648. Swift.debugPrint("KMToolbarViewSettingIdentifier ...")
  2649. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  2650. Swift.debugPrint("KMToolbarSnapshotIdentifier ...")
  2651. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  2652. Swift.debugPrint("KMToolbarTTSIdentifier ...")
  2653. }
  2654. }
  2655. }
  2656. }
  2657. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  2658. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  2659. KMPrint("KMToolbarToolWatermarkItemIdentifier \(index)")
  2660. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  2661. KMPrint("KMToolbarToolBackgroundItemIdentifier \(index)")
  2662. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  2663. KMPrint("KMToolbarToolHeaderFooterItemIdentifier \(index)")
  2664. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  2665. KMPrint("KMToolbarToolBatesItemIdentifier \(index)")
  2666. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  2667. KMPrint("KMToolbarComparisonItemIdentifier \(index)")
  2668. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  2669. KMPrint("KMToolbarToolFormAlignIdentifier \(index)")
  2670. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  2671. KMPrint("KMToolbarConversionImageItemIdentifier \(index)")
  2672. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  2673. KMPrint("KMToolbarConversionExportImageItemIdentifier \(index)")
  2674. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  2675. KMPrint("KMToolbarConversionCreatePDFItemIdentifier \(index)")
  2676. self.createPdf(index: index)
  2677. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  2678. KMPrint("KMToolbarCropIdentifier \(index)")
  2679. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  2680. KMPrint("KMToolbarToolSecureItemIdentifier \(index)")
  2681. }
  2682. }
  2683. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String) {
  2684. Swift.debugPrint("Search Result " + searchString)
  2685. }
  2686. }
  2687. // MARK: -
  2688. // MARK: - Mouse
  2689. extension KMMainViewController {
  2690. override func mouseDown(with event: NSEvent) {
  2691. super.mouseDown(with: event)
  2692. KMPrint("KMMainViewController mouseDown")
  2693. self.leftSideViewCancelSelect()
  2694. self.pageNumberDisplayView.isEdit = false
  2695. }
  2696. }
  2697. //MARK: LeftSideViewController
  2698. extension KMMainViewController {
  2699. func leftSideViewCancelSelect() {
  2700. // switch self.leftSideViewController.type.methodType {
  2701. // case .Thumbnail:
  2702. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  2703. // break
  2704. // case .Outline:
  2705. //// self.leftSideViewController.outlineViewController.cancelSelect()
  2706. // break
  2707. // case .BookMark:
  2708. //// self.leftSideViewController.bookViewController.cancelSelect()
  2709. // break
  2710. // case .Search:
  2711. //// self.leftSideViewController.searchViewController.cancelSelect()
  2712. // break
  2713. // case .Annotation:
  2714. //// self.leftSideViewController.annotationViewController.cancelSelect()
  2715. // break
  2716. // default:
  2717. if self.listView.isEditing() {
  2718. if self.listView.editingAreas() != nil &&
  2719. self.listView.editingAreas().count != 0 {
  2720. let areas = self.listView.editingAreas().first
  2721. if areas is CPDFEditTextArea {
  2722. self.listView.clearEditingSelectCharItem()
  2723. self.listView.updateEditing([])
  2724. KMPrint("取消选中")
  2725. }
  2726. }
  2727. }
  2728. KMPrint("其他")
  2729. // }
  2730. }
  2731. }
  2732. extension KMMainViewController: KMReadModelViewDelegate {
  2733. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2734. self.listView.goToFirstPage(nil)
  2735. }
  2736. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  2737. self.listView.goToPreviousPage(nil)
  2738. }
  2739. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2740. self.listView.goToNextPage(nil)
  2741. }
  2742. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2743. self.listView.goToLastPage(nil)
  2744. }
  2745. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  2746. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  2747. }
  2748. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  2749. var scale: Double = 1.0
  2750. switch type {
  2751. case .fitWidth:
  2752. self.listView.autoScales = !self.listView.autoScales
  2753. scale = self.listView.scaleFactor
  2754. break
  2755. case .actualSize:
  2756. if self.listView.scaleFactor != 1.0 {
  2757. self.listView.scaleFactor = 1.0
  2758. self.listView.autoScales = false
  2759. }
  2760. scale = self.listView.scaleFactor
  2761. break
  2762. case .autoSize:
  2763. self.listView.autoScales = true
  2764. self.listView.autoScales = false
  2765. scale = self.listView.scaleFactor
  2766. break
  2767. case ._10:
  2768. scale = 0.1
  2769. break
  2770. case ._25:
  2771. scale = 0.25
  2772. break
  2773. case ._50:
  2774. scale = 0.5
  2775. break
  2776. case ._100:
  2777. scale = 1.0
  2778. break
  2779. case ._150:
  2780. scale = 1.5
  2781. break
  2782. case ._200:
  2783. scale = 2.0
  2784. break
  2785. case ._400:
  2786. scale = 4.0
  2787. break
  2788. case ._800:
  2789. scale = 8.0
  2790. break
  2791. default:
  2792. break
  2793. }
  2794. self.listView.scaleFactor = scale
  2795. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2796. }
  2797. func cancelReadModel(view: KMReadModelView, sender: Any) {
  2798. if self.isReadMode {
  2799. self.closeReadModel()
  2800. }
  2801. }
  2802. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  2803. // if self.readModelViewWidthConstraint.constant != width {
  2804. self.readModelViewWidthConstraint.constant = width
  2805. // }
  2806. }
  2807. }
  2808. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  2809. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  2810. self.listView.go(toPageIndex: pageIndex, animated: true)
  2811. }
  2812. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  2813. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  2814. self.tipCurrentPageBoxWidthConstraint.constant = width
  2815. }
  2816. }
  2817. func commitEditingIfNeed() {
  2818. let isEdited = self.listView?.isEdited() ?? false
  2819. if isEdited || self.isPDFTextImageEdited {
  2820. self.listView.commitEditing()
  2821. }
  2822. }
  2823. }
  2824. // MARK: - Analytics (埋点)
  2825. extension KMMainViewController {
  2826. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  2827. if (type == .Annatiton) {
  2828. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Annotation", parameters: [
  2829. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2830. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2831. } else if (type == .editPDF) {
  2832. KMAnalytics.trackEvent(eventName: "Btn_Tbr_EditPDF", parameters: [
  2833. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2834. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2835. } else if (type == .Page) {
  2836. KMAnalytics.trackEvent(eventName: "Btn_Tbr_PageEdit", parameters: [
  2837. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2838. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2839. } else if (type == .Conversion) {
  2840. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Converter", parameters: [
  2841. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2842. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2843. } else if (type == .Tool) {
  2844. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Tools", parameters: [
  2845. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2846. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2847. }
  2848. }
  2849. func trackEvent_aiTranslate() -> Void {
  2850. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  2851. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2852. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2853. }
  2854. func trackEvent_print() -> Void {
  2855. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  2856. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2857. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2858. }
  2859. func trackEvent_share() -> Void {
  2860. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  2861. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2862. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2863. }
  2864. func trackEvent_upgrade() -> Void {
  2865. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  2866. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2867. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2868. }
  2869. func trackEvent(annotationType type: CAnnotationType) -> Void {
  2870. if (type == .highlight) {
  2871. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  2872. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2873. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2874. } else if (type == .underline) {
  2875. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  2876. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2877. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2878. } else if (type == .strikeOut) {
  2879. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  2880. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2881. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2882. } else if (type == .ink) {
  2883. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  2884. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2885. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2886. } else if (type == .freeText) {
  2887. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  2888. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2889. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2890. } else if (type == .anchored) {
  2891. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  2892. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2893. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2894. } else if (type == .square) {
  2895. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  2896. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2897. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2898. } else if (type == .link) {
  2899. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  2900. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2901. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2902. } else if (type == .stamp) {
  2903. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  2904. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2905. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2906. } else if (type == .signSignature) {
  2907. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  2908. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2909. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2910. } else if (type == .addText) {
  2911. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  2912. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  2913. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2914. } else if (type == .addImage) {
  2915. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  2916. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  2917. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2918. } else {
  2919. }
  2920. }
  2921. func trackEvent(toolMode mode: CToolMode) -> Void {
  2922. if (mode == .selectToolMode) {
  2923. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  2924. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2925. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2926. } else if (mode == .moveToolMode) {
  2927. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  2928. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2929. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2930. }
  2931. }
  2932. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  2933. if (type == .word) {
  2934. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toWord", parameters: [
  2935. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2936. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2937. } else if (type == .excel) {
  2938. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toExcel", parameters: [
  2939. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2940. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2941. } else if (type == .ppt) {
  2942. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toPPT", parameters: [
  2943. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2944. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2945. } else if (type == .rtf) {
  2946. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toRTF", parameters: [
  2947. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2948. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2949. } else if (type == .csv) {
  2950. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toCSV", parameters: [
  2951. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2952. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2953. } else if (type == .html) {
  2954. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toHTML", parameters: [
  2955. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2956. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2957. } else if (type == .conversion_text) {
  2958. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toText", parameters: [
  2959. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2960. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2961. } else if (type == .conversion_image) {
  2962. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toImage", parameters: [
  2963. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  2964. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2965. } else if (type == .compress) {
  2966. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Compress", parameters: [
  2967. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2968. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2969. } else if (type == .merge) {
  2970. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Merge", parameters: [
  2971. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2972. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2973. } else if (type == .secure) {
  2974. } else if (type == .crop) {
  2975. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Crop", parameters: [
  2976. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2977. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2978. }
  2979. }
  2980. func trackEvent_setPassword() -> Void {
  2981. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  2982. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2983. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2984. }
  2985. func trackEvent_removePassword() -> Void {
  2986. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  2987. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2988. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2989. }
  2990. }