KMMainViewController+Action.swift 155 KB

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