KMMainViewController+Action.swift 215 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355
  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.searchResults = self.searchResults
  18. // self.leftSideViewController.searchViewController.reloadData()
  19. } else {
  20. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  21. var findArray : [[CPDFSelection]]
  22. if isCase {
  23. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  24. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  25. } else {
  26. findArray = self.listView.document.findString(searchString) ?? []
  27. }
  28. } else {
  29. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  30. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  31. } else {
  32. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  33. }
  34. }
  35. self.searchResults.removeAll()
  36. for selections in findArray {
  37. for selection in selections {
  38. let mode : KMSearchMode = KMSearchMode()
  39. mode.selection = selection
  40. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  41. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  42. self.searchResults.insert(mode, at: self.searchResults.count)
  43. }
  44. }
  45. // self.leftSideViewController.searchViewController.searchResults = self.searchResults
  46. // self.leftSideViewController.searchViewController.reloadData()
  47. self.leftSideViewController.searchResults = self.searchResults
  48. }
  49. if self.leftSideViewController.findPaneState == .singular {
  50. self.leftSideViewController.displayFindViewAnimating(true)
  51. } else {
  52. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  53. }
  54. }
  55. func removeSignatures(signatures:[CPDFSignature]) {
  56. for signature in signatures {
  57. self.listView.document.removeSignature(signature)
  58. }
  59. for i in 0..<self.listView.document.pageCount {
  60. let page : CPDFPage = self.listView.document.page(at: i)
  61. let annotations : [CPDFAnnotation] = page.annotations
  62. for j in 0..<annotations.count {
  63. let annotation = annotations[j]
  64. if annotation is CPDFSignatureWidgetAnnotation {
  65. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  66. }
  67. }
  68. }
  69. self.listView.setNeedsDisplayForVisiblePages()
  70. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  71. var mSignatures : [CPDFSignature] = []
  72. for sign in tSignatures {
  73. if sign.signers.count > 0 {
  74. mSignatures.append(sign)
  75. }
  76. }
  77. // self.leftSideViewController.signatureViewController.signatures = signatures
  78. // self.leftSideViewController.signatureViewController.reloadData()
  79. }
  80. //MARK: menu菜单
  81. func fontColorMenuItem()->NSMenuItem {
  82. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  83. return fontColorItem;
  84. }
  85. func fontSizeMenuItem()->NSMenuItem {
  86. let currentFontSize = self.listView.editingTextFontSize()
  87. let fontSizes = self.fontSizes()
  88. let submenu = NSMenu(title: "")
  89. for i in 0 ... fontSizes.count - 1 {
  90. let fontSize : String = fontSizes.object(at: i) as! String
  91. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  92. item.target = self
  93. item.tag = i
  94. submenu.addItem(item)
  95. if (Int(currentFontSize) == Int(fontSize)) {
  96. item.state = .on
  97. }
  98. }
  99. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  100. fontSizeItem.submenu = submenu
  101. return fontSizeItem;
  102. }
  103. func corpImageMenuItem()->NSMenuItem {
  104. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm Crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  105. return corpImageItem
  106. }
  107. func cancelCorpImageMenuItem()->NSMenuItem {
  108. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel Crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  109. return cancelCorpImageItem
  110. }
  111. func restoreCorpImageMenuItem()->NSMenuItem {
  112. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore Crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  113. return cancelCorpImageItem
  114. }
  115. func cutImageArea()->NSMenuItem {
  116. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  117. return deleteItem
  118. }
  119. func editAddBlanMenu(menu:NSMenu){
  120. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  121. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  122. }
  123. func addText() -> NSMenuItem {
  124. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  125. return addTextItem
  126. }
  127. func addImage() -> NSMenuItem {
  128. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  129. return addImageItem
  130. }
  131. func replaceImageArea()->NSMenuItem {
  132. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  133. return replaceItem
  134. }
  135. func exportImageArea()->NSMenuItem {
  136. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  137. return exportItem
  138. }
  139. func exportImageStampItem()->NSMenuItem {
  140. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  141. let menu = NSMenu()
  142. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  143. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  144. exportItem.submenu = menu
  145. return exportItem
  146. }
  147. func exportMenu() -> NSMenu {
  148. let menu = NSMenu()
  149. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  150. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  151. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  152. return menu
  153. }
  154. func cropMenu() -> NSMenu {
  155. let menu = NSMenu()
  156. let item1 = menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  157. let item2 = menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  158. let item3 = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  159. let item4 = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  160. return menu
  161. }
  162. func zoomSelectionMenuItem() -> NSMenuItem {
  163. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  164. return item
  165. }
  166. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  167. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  168. return item
  169. }
  170. func enterAnnotationStype() -> NSMenuItem {
  171. let stypItem = NSMenuItem(title: NSLocalizedString("Annotation", comment: ""), action: nil, target: self)
  172. let stypeMenu = NSMenu()
  173. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  174. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 0)
  175. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 1)
  176. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 2)
  177. stypeMenu.addItem(NSMenuItem.separator())
  178. }
  179. // stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  180. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Box", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  181. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  182. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  183. stypeMenu.addItem(NSMenuItem.separator())
  184. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  185. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  186. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  187. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  188. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  189. if self.isReadMode {
  190. } else {
  191. stypeMenu.addItem(NSMenuItem.separator())
  192. // _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  193. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  194. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  195. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  196. }
  197. stypItem.submenu = stypeMenu
  198. if self.listView.annotationType == .ink {
  199. stypeMenu.item(at: 0)?.state = .on
  200. } else if self.listView.annotationType == .freeText {
  201. stypeMenu.item(at: 1)?.state = .on
  202. } else if self.listView.annotationType == .anchored {
  203. stypeMenu.item(at: 2)?.state = .on
  204. } else if self.listView.annotationType == .square {
  205. stypeMenu.item(at: 3)?.state = .on
  206. } else if self.listView.annotationType == .circle {
  207. stypeMenu.item(at: 4)?.state = .on
  208. } else if self.listView.annotationType == .arrow {
  209. stypeMenu.item(at: 5)?.state = .on
  210. } else if self.listView.annotationType == .line {
  211. stypeMenu.item(at: 6)?.state = .on
  212. } else if self.listView.annotationType == .link {
  213. stypeMenu.item(at: 7)?.state = .on
  214. } else if self.listView.annotationType == .stamp {
  215. stypeMenu.item(at: 8)?.state = .on
  216. } else if self.listView.annotationType == .signSignature {
  217. stypeMenu.item(at: 9)?.state = .on
  218. }
  219. return stypItem
  220. }
  221. func setAnnotationToolStype() -> NSMenuItem {
  222. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  223. let stypeMenu = NSMenu()
  224. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.noteToolMode.rawValue)
  225. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  226. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  227. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  228. // stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  229. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  230. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  231. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  232. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  233. let item8 = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  234. let item9 = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  235. let item10 = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  236. let item11 = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  237. let item12 = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  238. let item13 = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  239. let item14 = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  240. let item15 = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  241. stypItem.submenu = stypeMenu
  242. if self.toolbarController.toolbarType == .Annatiton {
  243. stypeMenu.item(at: 0)?.state = .on
  244. } else if self.toolbarController.toolbarType == .Move {
  245. stypeMenu.item(at: 1)?.state = .on
  246. } else if self.toolbarController.toolbarType == .Magnify {
  247. stypeMenu.item(at: 2)?.state = .on
  248. } else if self.toolbarController.toolbarType == .Select {
  249. stypeMenu.item(at: 3)?.state = .on
  250. } else if self.toolbarController.toolbarType == .SelectZoom {
  251. stypeMenu.item(at: 4)?.state = .on
  252. }
  253. return stypItem
  254. }
  255. func addReadModelStype() -> NSMenuItem {
  256. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)
  257. if self.isReadMode {
  258. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)
  259. }
  260. return stypItem
  261. }
  262. func addOutlineStype() -> NSMenuItem {
  263. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  264. return stypItem
  265. }
  266. func setTTSStype() -> NSMenuItem {
  267. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  268. return stypItem
  269. }
  270. func setShareStype() -> NSMenuItem {
  271. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: #selector(showShareAction), target: self)
  272. var string = ""
  273. if listView.activeAnnotation != nil {
  274. string = listView.activeAnnotation.contents
  275. }
  276. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  277. return stypItem
  278. }
  279. func setLookUpStype() -> NSMenuItem {
  280. let str = String(format: "Look Up %@", listView?.currentSelection?.string() ?? "")
  281. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(lookUpAction), target: self)
  282. return stypItem
  283. }
  284. func setSearchBaiduStype() -> NSMenuItem {
  285. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  286. return stypItem
  287. }
  288. func setCutStype() -> NSMenuItem {
  289. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  290. return stypItem
  291. }
  292. func setDeleteStype() -> NSMenuItem {
  293. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  294. return stypItem
  295. }
  296. func setColorsStype() -> NSMenuItem {
  297. let stypItem = NSMenuItem(title: NSLocalizedString("Colors...", comment: ""), action: #selector(ColorsItemAction), target: self)
  298. return stypItem
  299. }
  300. func setLinesStype() -> NSMenuItem {
  301. let stypItem = NSMenuItem(title: NSLocalizedString("Lines...", comment: ""), action: #selector(LinesItemAction), target: self)
  302. return stypItem
  303. }
  304. func setEditNoteStype() -> NSMenuItem {
  305. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  306. return stypItem
  307. }
  308. func setRotateStype() -> NSMenuItem {
  309. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  310. let stypeMenu = NSMenu()
  311. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  312. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  313. stypItem.submenu = stypeMenu
  314. if self.toolbarController.toolbarType == .Annatiton {
  315. stypeMenu.item(at: 0)?.state = .on
  316. } else if self.toolbarController.toolbarType == .Move {
  317. stypeMenu.item(at: 1)?.state = .on
  318. }
  319. return stypItem
  320. }
  321. func setNextPageStype() -> NSMenuItem {
  322. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  323. stypItem.isEnabled = false
  324. if listView.canGoToNextPage() {
  325. stypItem.isEnabled = true
  326. }
  327. return stypItem
  328. }
  329. func setPreviousPageStype() -> NSMenuItem {
  330. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  331. stypItem.isEnabled = false
  332. if listView.canGoToPreviousPage() {
  333. stypItem.isEnabled = true
  334. }
  335. return stypItem
  336. }
  337. func setTranslateStype() -> NSMenuItem {
  338. let str = String(format: "Translate %@", listView?.currentSelection?.string() ?? "")
  339. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(TranslateItemAction), target: self)
  340. return stypItem
  341. }
  342. func setAutoScrollStype() -> NSMenuItem {
  343. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  344. return stypItem
  345. }
  346. func setSnapshotStype() -> NSMenuItem {
  347. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  348. let stypeMenu = NSMenu()
  349. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  350. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  351. stypItem.submenu = stypeMenu
  352. // if self.toolbarController.toolbarType == .Annatiton {
  353. // stypeMenu.item(at: 0)?.state = .on
  354. // } else if self.toolbarController.toolbarType == .Move {
  355. // stypeMenu.item(at: 1)?.state = .on
  356. // }
  357. return stypItem
  358. }
  359. func setServicesStype() -> NSMenuItem {
  360. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  361. let stypeMenu = NSMenu()
  362. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  363. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  364. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  365. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  366. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  367. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  368. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  369. stypItem.submenu = stypeMenu
  370. // if self.toolbarController.toolbarType == .Annatiton {
  371. // stypeMenu.item(at: 0)?.state = .on
  372. // } else if self.toolbarController.toolbarType == .Move {
  373. // stypeMenu.item(at: 1)?.state = .on
  374. // }
  375. return stypItem
  376. }
  377. func setCropStype() -> NSMenuItem {
  378. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  379. let stypeMenu = NSMenu()
  380. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  381. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  382. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  383. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  384. // if(NSIsEmptyRect(selectionRect)) {
  385. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  386. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  387. //
  388. // }
  389. stypItem.submenu = stypeMenu
  390. // if self.toolbarController.toolbarType == .Annatiton {
  391. // stypeMenu.item(at: 0)?.state = .on
  392. // } else if self.toolbarController.toolbarType == .Move {
  393. // stypeMenu.item(at: 1)?.state = .on
  394. // } else if self.toolbarController.toolbarType == .Magnify {
  395. // stypeMenu.item(at: 2)?.state = .on
  396. // } else if self.toolbarController.toolbarType == .Select {
  397. // stypeMenu.item(at: 3)?.state = .on
  398. // } else if self.toolbarController.toolbarType == .SelectZoom {
  399. // stypeMenu.item(at: 4)?.state = .on
  400. // }
  401. return stypItem
  402. }
  403. func addHighlightLinksStype() -> NSMenuItem {
  404. let highlightLink = KMPreferenceManager.shared.highlightLinks
  405. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  406. if highlightLink {
  407. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  408. }
  409. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  410. return highlightLinksItem
  411. }
  412. func addAnnotationForStyleMenu(menu:NSMenu) {
  413. if menu == nil {
  414. return
  415. }
  416. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  417. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  418. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  419. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  420. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  421. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  422. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  423. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  424. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  425. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  426. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)
  427. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  428. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  429. if listView.currentSelection.selectionType() != .image {
  430. menu.insertItem(height, at: menu.items.count)
  431. menu.insertItem(underline, at: menu.items.count)
  432. menu.insertItem(strickout, at: menu.items.count)
  433. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  434. }
  435. if self.isReadMode {
  436. } else {
  437. if listView.currentSelection.selectionType() != .image &&
  438. listView.currentSelection.selectionType() != .text {
  439. menu.insertItem(text, at: menu.items.count)
  440. menu.insertItem(note, at: menu.items.count)
  441. }
  442. }
  443. if self.isReadMode {
  444. } else {
  445. if listView.currentSelection.selectionType() != .image {
  446. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  447. menu.insertItem(rectangle, at: menu.items.count)
  448. menu.insertItem(oval, at: menu.items.count)
  449. }
  450. }
  451. if self.isReadMode {
  452. } else {
  453. if listView.currentSelection.selectionType() != .image &&
  454. listView.currentSelection.selectionType() != .text {
  455. menu.insertItem(line, at: menu.items.count)
  456. }
  457. }
  458. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  459. if self.isReadMode {
  460. } else {
  461. menu.insertItem(link, at: menu.items.count)
  462. }
  463. if self.isReadMode {
  464. } else {
  465. if listView.currentSelection.selectionType() != .image {
  466. menu.insertItem(outline, at: menu.items.count)
  467. }
  468. }
  469. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  470. if self.isReadMode {
  471. } else {
  472. if (listView.currentSelection.selectionType() != .image) {
  473. menu.insertItem(aiTranslation, at: menu.items.count)
  474. }
  475. }
  476. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  477. }
  478. func addBookmarkMenu() -> NSMenuItem {
  479. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  480. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  481. return bookMarkItem
  482. } else {
  483. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  484. return bookMarkItem
  485. }
  486. }
  487. func findStringMenu() -> NSMenuItem {
  488. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  489. menuItem.keyEquivalent = "f"
  490. return menuItem
  491. }
  492. func printingMenu() -> NSMenuItem {
  493. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  494. return menuItem
  495. }
  496. func fontSizes()->NSArray {
  497. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  498. }
  499. //MARK: menuItem Action
  500. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  501. let color = listView.editingSelectionFontColor()
  502. let panel = NSColorPanel.shared
  503. panel.setTarget(self)
  504. panel.setAction(#selector(fontColorChangeAction))
  505. panel.orderFront(nil)
  506. panel.showsAlpha = false
  507. panel.color = color ?? NSColor.black
  508. }
  509. @objc func fontColorChangeAction(sender: NSColorPanel) {
  510. self.listView.setEditingSelectionFontColor(sender.color)
  511. }
  512. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  513. let fontSize = self.fontSizes().object(at: sender.tag)
  514. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  515. }
  516. @objc func addImageText(sender: NSMenuItem) {
  517. let event = NSApp.currentEvent
  518. let clickLocation = event?.locationInWindow
  519. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  520. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  521. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  522. point = point2
  523. if sender.tag == 0 {
  524. KMPrint("添加文字")
  525. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  526. if !isSelect {
  527. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  528. }
  529. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  530. } else if sender.tag == 1 {
  531. KMPrint("添加图片")
  532. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  533. if !isSelect {
  534. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  535. }
  536. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  537. } else if sender.tag == 2 {
  538. KMPrint("粘贴")
  539. }
  540. }
  541. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  542. if self.rightSideViewController.eidtPDFImageProperty != nil {
  543. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  544. } else {
  545. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  546. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  547. }
  548. }
  549. }
  550. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  551. if self.rightSideViewController.eidtPDFImageProperty != nil {
  552. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  553. } else {
  554. self.listView.exitCrop(with: self.listView.selectImageAreas)
  555. self.listView.cropAreas = nil
  556. self.listView.isEditImage = false
  557. }
  558. }
  559. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  560. if self.rightSideViewController.eidtPDFImageProperty != nil {
  561. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  562. } else {
  563. self.listView.resetCrop(with: self.listView.selectImageAreas)
  564. }
  565. }
  566. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  567. if self.listView.selectImageAreas != nil {
  568. self.listView.isEditImage = true
  569. self.listView.enterCrop(with: self.listView.selectImageAreas)
  570. self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  571. }
  572. }
  573. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  574. if self.listView.selectImageAreas == nil {
  575. return
  576. }
  577. let panel = NSOpenPanel()
  578. panel.allowsMultipleSelection = false
  579. panel.allowedFileTypes = ["png","jpg"]
  580. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  581. if response == .OK {
  582. let openPath = panel.url?.path
  583. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  584. if s {
  585. }
  586. }
  587. }
  588. }
  589. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  590. if self.listView.selectImageAreas == nil {
  591. return
  592. }
  593. let panel = NSSavePanel()
  594. // panel.nameFieldStringValue = "[新文件].png"
  595. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  596. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  597. // button.state = .on
  598. // panel.accessoryView = button
  599. panel.isExtensionHidden = true
  600. let response = panel.runModal()
  601. if response == .OK {
  602. let url = panel.url
  603. if FileManager.default.fileExists(atPath: url!.path) {
  604. try?FileManager.default.removeItem(atPath: url!.path)
  605. }
  606. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  607. if result {
  608. NSWorkspace.shared.activateFileViewerSelecting([url!])
  609. // if button.state == .on { /// 开启文档
  610. // NSWorkspace.shared.openFile(url!.path)
  611. // } else {
  612. //
  613. // }
  614. }
  615. }
  616. }
  617. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  618. }
  619. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  620. }
  621. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  622. }
  623. @objc func OpenItemAction(sender: NSMenuItem) {
  624. }
  625. @objc func cropAllPageItem(sender: NSMenuItem) {
  626. self.cropAll(nil)
  627. }
  628. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  629. self.crop(nil)
  630. }
  631. @objc func autoCropAllItem(sender: NSMenuItem) {
  632. self.autoCropAll(nil)
  633. }
  634. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  635. self.smartAutoCropAll(nil)
  636. }
  637. @objc func customCropModel(sender: NSMenuItem) {
  638. KMPrint("customCropModel ...")
  639. }
  640. @objc func rotateRightAction(sender: NSMenuItem) {
  641. }
  642. @objc func rotateLeftAction(sender: NSMenuItem) {
  643. }
  644. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  645. self.listView.toolMode = .noteToolMode
  646. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  647. var model : KMToolbarViewType = .None
  648. switch sender.tag {
  649. case 0:
  650. identifier = KMDocumentAnnotationToolbarItemIdentifier
  651. model = .Annatiton
  652. case 1:
  653. identifier = KMToolbarMoveToolModeItemIdentifier
  654. model = .Move
  655. case 2:
  656. identifier = KMToolbarMagnifyToolModeItemIdentifier
  657. model = .Magnify
  658. case 3:
  659. identifier = KMToolbarSelectToolModeItemIdentifier
  660. model = .Select
  661. case 4:
  662. identifier = KMToolbarZoomToSelectionItemIdentifier
  663. model = .SelectZoom
  664. default:
  665. break
  666. }
  667. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  668. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  669. }
  670. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  671. var itemId: String?
  672. if sender.tag == CAnnotationType.highlight.rawValue {
  673. itemId = KMToolbarHighlightAnnotationItemIdentifier
  674. } else if sender.tag == CAnnotationType.underline.rawValue {
  675. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  676. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  677. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  678. } else if sender.tag == CAnnotationType.ink.rawValue {
  679. itemId = KMToolbarInkAnnotationItemIdentifier
  680. } else if sender.tag == CAnnotationType.freeText.rawValue {
  681. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  682. } else if sender.tag == CAnnotationType.anchored.rawValue {
  683. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  684. } else if sender.tag == CAnnotationType.square.rawValue {
  685. itemId = KMToolbarSquareAnnotationItemIdentifier
  686. } else if sender.tag == CAnnotationType.circle.rawValue {
  687. itemId = KMToolbarCircleAnnotationItemIdentifier
  688. } else if sender.tag == CAnnotationType.arrow.rawValue {
  689. itemId = KMToolbarArrowAnnotationItemIdentifier
  690. } else if sender.tag == CAnnotationType.line.rawValue {
  691. itemId = KMToolbarLineAnnotationItemIdentifier
  692. } else if sender.tag == CAnnotationType.link.rawValue {
  693. itemId = KMToolbarLinkAnnotationItemIdentifier
  694. }
  695. if let data = itemId {
  696. self.toolbarController.clickItem(data)
  697. }
  698. }
  699. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  700. var annotationType : CAnnotationType = .unkown
  701. switch sender.tag {
  702. case 0:
  703. annotationType = .highlight
  704. case 1:
  705. annotationType = .underline
  706. case 2:
  707. annotationType = .strikeOut
  708. case 3:
  709. annotationType = .freeText
  710. case 4:
  711. annotationType = .anchored
  712. case 5:
  713. annotationType = .square
  714. case 6:
  715. annotationType = .circle
  716. case 7:
  717. annotationType = .line
  718. case 8:
  719. annotationType = .link
  720. case 9:
  721. // var newOutline : CPDFOutline = CPDFOutline()
  722. // newOutline.label = "11111111"
  723. // let des = self.listView.currentDestination
  724. // if "\(des?.point.x ?? 0)" != "nan" {
  725. // newOutline.destination = self.listView.currentDestination
  726. // } else {
  727. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  728. // newOutline.destination = destination
  729. // }
  730. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  731. // let parent = current.parent ?? CPDFOutline()
  732. // let index = current.index + 1
  733. // parent.insertChild(newOutline, at: index)
  734. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  735. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  736. }
  737. // self.leftSideViewController.outlineViewController.addItemAction()
  738. return
  739. case 10:
  740. annotationType = .unkown
  741. default:
  742. break
  743. }
  744. if (annotationType != .link) {
  745. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  746. self.listView.currentSelection = nil;
  747. return
  748. }
  749. // link
  750. let selection = self.listView.currentSelection
  751. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  752. DispatchQueue.main.async {
  753. Task { @MainActor in
  754. #if VERSION_DMG
  755. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  756. return
  757. }
  758. #endif
  759. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  760. self.listView.currentSelection = nil;
  761. if (annotation != nil) {
  762. self.listView.updateActiveAnnotations([annotation!])
  763. }
  764. }
  765. }
  766. }
  767. @objc func aiTranslationAction(sender: NSMenuItem) {
  768. let content = self.listView.currentSelection.string() ?? ""
  769. let origin = self.listView.currentSelection.bounds.origin
  770. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  771. self.aiTranslationWindow?.content = content
  772. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  773. self.aiTranslationWindow!.window?.center()
  774. }
  775. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  776. Task { @MainActor in
  777. #if VERSION_DMG
  778. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) {
  779. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  780. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  781. return
  782. }
  783. }
  784. #endif
  785. var point = mouseRightMenuEvent?.locationInWindow
  786. if (point == nil) {
  787. point = NSZeroPoint
  788. }
  789. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  790. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  791. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  792. var annotation: CPDFAnnotation?
  793. if self.isReadMode {
  794. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  795. self.listView.toolMode = .noteToolMode
  796. }
  797. switch sender.tag {
  798. case 0:
  799. self.listView.annotationType = CAnnotationType.ink
  800. case 1:
  801. // self.listView.annotationType = CAnnotationType.freeText
  802. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  803. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  804. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  805. if ((annotation) != nil) {
  806. self.listView.updateActiveAnnotations([annotation!])
  807. self.listView.edit(annotation)
  808. }
  809. case 2:
  810. // self.listView.annotationType = CAnnotationType.anchored
  811. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  812. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  813. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  814. self.listView.edit(annotation)
  815. case 3:
  816. // self.listView.annotationType = CAnnotationType.square
  817. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  818. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  819. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  820. case 4:
  821. // self.listView.annotationType = CAnnotationType.circle
  822. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  823. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  824. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  825. case 5:
  826. // self.listView.annotationType = CAnnotationType.arrow
  827. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  828. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  829. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  830. case 6:
  831. // self.listView.annotationType = CAnnotationType.line
  832. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  833. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  834. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  835. case 7:
  836. self.listView.annotationType = CAnnotationType.link
  837. self.openRightPane()
  838. case 8:
  839. self.listView.annotationType = CAnnotationType.stamp
  840. self.openRightPane()
  841. case 9:
  842. self.listView.annotationType = CAnnotationType.signSignature
  843. self.openRightPane()
  844. default:
  845. break
  846. }
  847. self.rightSideViewController.isHidden = true
  848. self.rightSideViewController.subViewType = .AnnotationProperts
  849. } else {
  850. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  851. if(self.toolbarController.toolbarType == .None) {
  852. self.toolbarController.toolbarType = .Annatiton
  853. }
  854. self.listView.toolMode = .noteToolMode
  855. }
  856. switch sender.tag {
  857. case 0:
  858. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  859. self.rightMouseEventing = true
  860. if(self.toolbarController.toolbarType == .None) {
  861. self.toolbarController.toolbarType = .Annatiton
  862. }
  863. self.listView.toolMode = .noteToolMode
  864. self.listView.annotationType = CAnnotationType.ink
  865. case 1:
  866. // self.listView.annotationType = CAnnotationType.freeText
  867. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  868. if (pagePoint.x - defaultSize.width > 0){
  869. pagePoint.x -= defaultSize.width;
  870. }else{
  871. pagePoint.x = 0;
  872. }
  873. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  874. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  875. // self.view.window?.makeFirstResponder()
  876. if ((annotation) != nil) {
  877. // self.listView.updateActiveAnnotations([annotation!])
  878. self.listView.edit(annotation)
  879. }
  880. case 2:
  881. // self.listView.annotationType = CAnnotationType.anchored
  882. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  883. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  884. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  885. self.listView.edit(annotation)
  886. case 3:
  887. // self.listView.annotationType = CAnnotationType.square
  888. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  889. if (pagePoint.x - defaultSize.width > 0){
  890. pagePoint.x -= defaultSize.width;
  891. }else{
  892. pagePoint.x = 0;
  893. }
  894. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  895. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  896. case 4:
  897. // self.listView.annotationType = CAnnotationType.circle
  898. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  899. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  900. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  901. case 5:
  902. // self.listView.annotationType = CAnnotationType.arrow
  903. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  904. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  905. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  906. case 6:
  907. // self.listView.annotationType = CAnnotationType.line
  908. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  909. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  910. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  911. case 7:
  912. self.listView.annotationType = CAnnotationType.link
  913. self.openRightPane()
  914. case 8:
  915. self.listView.annotationType = CAnnotationType.stamp
  916. self.openRightPane()
  917. case 9:
  918. self.listView.annotationType = CAnnotationType.signSignature
  919. self.openRightPane()
  920. case 10:
  921. self.addImgAnnotationToView(center: pagePoint)
  922. default:
  923. break
  924. }
  925. // self.rightSideViewController.view.isHidden = false
  926. self.rightSideViewController.isHidden = false
  927. // self.openRightPane()
  928. self.rightSideViewController.subViewType = .AnnotationProperts
  929. }
  930. if (annotation != nil) {
  931. self.listView.updateIsRightActiveAnnotations([annotation!])
  932. }
  933. }
  934. }
  935. func addImgAnnotationToView(center: NSPoint) {
  936. let accessoryCtr = KMImageAccessoryController()
  937. let openPanel = NSOpenPanel()
  938. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  939. openPanel.allowsMultipleSelection = false
  940. openPanel.accessoryView = accessoryCtr.view
  941. openPanel.isAccessoryViewDisclosed = true
  942. openPanel.beginSheetModal(for: self.view.window!) { result in
  943. if result == .OK {
  944. let fileURL = openPanel.urls.first
  945. let filePath = fileURL!.path
  946. if filePath.pathExtension == "pdf" {
  947. let pdf = CPDFDocument(url: fileURL)
  948. if pdf!.isEncrypted {
  949. NSSound.beep()
  950. return
  951. }
  952. }
  953. let img = NSImage(contentsOfFile: filePath)
  954. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  955. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  956. }
  957. }
  958. }
  959. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  960. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  961. let index = self.listView.currentPageIndex
  962. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  963. self.listView.setNeedsDisplayForVisiblePages()
  964. } else {
  965. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  966. self.listView.setNeedsDisplayForVisiblePages()
  967. }
  968. if self.isReadMode {
  969. } else {
  970. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  971. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  972. }
  973. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  974. if bookMark != nil {
  975. let item = KMBookMarkItem()
  976. item.bookMark = bookMark!
  977. item.label = (bookMark?.label)!
  978. item.index = UInt(bookMark!.pageIndex)
  979. // self.leftSideViewController.bookViewController.reloadData()
  980. // self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  981. } else {
  982. // self.leftSideViewController.bookViewController.reloadData()
  983. }
  984. }
  985. }
  986. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  987. self.leftSideViewController.refreshMethodType(methodType: .Search)
  988. }
  989. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  990. let rect = listView.currentSelectionRect()
  991. let page = listView.currentPage()
  992. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  993. copyPage.setBounds(rect, for: .cropBox)
  994. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  995. // let pdfDocument : PDFDocument = PDFDocument()
  996. // let newpage : PDFPage = PDFPage(image: image)!
  997. // pdfDocument.insert(newpage, at: 0)
  998. // 执行右键操作后,需要取消框选区域
  999. if self.listView.toolMode == .selectToolMode {
  1000. objc_sync_enter(self)
  1001. self.listView.selectionRect = NSZeroRect
  1002. self.listView.selectionPageIndex = UInt(NSNotFound)
  1003. objc_sync_exit(self)
  1004. }
  1005. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1006. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1007. if (result == .cancel) {
  1008. return
  1009. }
  1010. // 解除权限
  1011. self?.isSaveKeyChain = false
  1012. self?.listView.document.unlock(withPassword: password)
  1013. // 隐藏提示
  1014. self?.hiddenSecureLimitTip()
  1015. // 去打印
  1016. KMPrintWindowController.printImage(image: image)
  1017. }
  1018. return
  1019. }
  1020. KMPrintWindowController.printImage(image: image)
  1021. }
  1022. // MARK: Redact 【密文标记】
  1023. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1024. self.listView.remove(self.listView.activeAnnotation)
  1025. }
  1026. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1027. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1028. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1029. self.view.window?.beginSheet(windowController.window!)
  1030. self.currentWindowController = windowController
  1031. windowController.itemClick = { [weak self] index, value in
  1032. if (index == 1) { /// 取消
  1033. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1034. self?.currentWindowController = nil
  1035. return
  1036. }
  1037. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1038. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1039. annotaton.setBorderColor(windowController_redact.outsideColor)
  1040. annotaton.setInteriorColor(windowController_redact.fillColor)
  1041. if (windowController_redact.isOver) {
  1042. annotaton.setFontColor(windowController_redact.fontColor)
  1043. annotaton.setAlignment(windowController_redact.aligement)
  1044. annotaton.setFont(windowController_redact.font)
  1045. annotaton.setOverlayText(windowController_redact.overText)
  1046. }
  1047. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1048. self?.currentWindowController = nil
  1049. }
  1050. }
  1051. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1052. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1053. return
  1054. }
  1055. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1056. let model = CPDFAnnotationModel(annotationType: .redact)
  1057. model?.setColor(annotation.borderColor())
  1058. model?.setInteriorColor(annotation.interiorColor())
  1059. let overlayText: String = annotation.overlayText()
  1060. if (overlayText.isEmpty) {
  1061. model?.setIsOverlayText(false)
  1062. } else {
  1063. model?.setIsOverlayText(true)
  1064. model?.setOverlayText(overlayText)
  1065. model?.setFontColor(annotation.fontColor())
  1066. model?.setAlignment(annotation.alignment())
  1067. model?.setFontName(annotation.font().fontName)
  1068. model?.setFontSize(annotation.font().pointSize)
  1069. }
  1070. }
  1071. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1072. let anno = self.listView.activeAnnotation
  1073. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1074. return
  1075. }
  1076. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1077. windowController.pageCount = Int(self.listView.document.pageCount)
  1078. self.currentWindowController = windowController
  1079. self.view.window?.beginSheet(windowController.window!)
  1080. windowController.itemClick = { [weak self] index, value in
  1081. if (index == 1) {
  1082. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1083. self!.currentWindowController = nil
  1084. return
  1085. }
  1086. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1087. let pageType = windowController_mutilPageFlag.pageType
  1088. let pageString = windowController_mutilPageFlag.pageString
  1089. if (pageType == 4) { /// 自定义页面
  1090. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  1091. if (array.count == 0) {
  1092. let alert = NSAlert()
  1093. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1094. alert.runModal()
  1095. return
  1096. }
  1097. }
  1098. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1099. self!.currentWindowController = nil
  1100. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  1101. if (indexs.count == 0) {
  1102. return
  1103. }
  1104. for i in indexs {
  1105. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1106. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1107. self?.listView.add(redactAnno, to: page)
  1108. }
  1109. }
  1110. }
  1111. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1112. self.exeRedactConfirm(.redactOne) {}
  1113. }
  1114. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1115. self.exeRedactConfirm(.eraserOne) {}
  1116. }
  1117. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1118. }
  1119. @objc func exportStampImage(sender:NSMenuItem) {
  1120. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1121. var image : NSImage = NSImage()
  1122. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1123. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1124. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1125. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1126. }
  1127. let data = image.tiffRepresentation
  1128. if sender.tag == 0 {
  1129. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1130. imageRep.size = image.size
  1131. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1132. let savePanel = NSSavePanel()
  1133. savePanel.allowedFileTypes = ["png"]
  1134. savePanel.beginSheetModal(for: self.view.window!) { response in
  1135. if (response != .OK) {
  1136. return
  1137. }
  1138. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1139. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1140. }
  1141. }
  1142. } else {
  1143. let pdfdocument = CPDFDocument()
  1144. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1145. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1146. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1147. let savePanel = NSSavePanel()
  1148. savePanel.allowedFileTypes = ["pdf"]
  1149. savePanel.beginSheetModal(for: self.view.window!) { response in
  1150. if (response != .OK) {
  1151. return
  1152. }
  1153. if pdfdocument!.write(to: savePanel.url!) {
  1154. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1155. }
  1156. }
  1157. }
  1158. }
  1159. }
  1160. }
  1161. @objc func exportCorpImage(sender:NSMenuItem) {
  1162. let rect = NSIntegralRect(listView.currentSelectionRect())
  1163. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1164. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1165. page.setBounds(rect, for: .cropBox)
  1166. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1167. let data = image.tiffRepresentation
  1168. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1169. imageRep.size = rect.size
  1170. let savePanel = NSSavePanel()
  1171. switch sender.tag {
  1172. case 0:
  1173. savePanel.allowedFileTypes = ["png"]
  1174. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1175. savePanel.beginSheetModal(for: self.view.window!) { response in
  1176. if (response != .OK) {
  1177. return
  1178. }
  1179. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1180. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1181. }
  1182. }
  1183. case 1:
  1184. savePanel.allowedFileTypes = ["jpg"]
  1185. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1186. savePanel.beginSheetModal(for: self.view.window!) { response in
  1187. if (response != .OK) {
  1188. return
  1189. }
  1190. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1191. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1192. }
  1193. }
  1194. case 2:
  1195. savePanel.allowedFileTypes = ["pdf"]
  1196. let pdfdocument = CPDFDocument()
  1197. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1198. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1199. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1200. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1201. savePanel.beginSheetModal(for: self.view.window!) { response in
  1202. if (response != .OK) {
  1203. return
  1204. }
  1205. if pdfdocument!.write(to: savePanel.url!) {
  1206. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1207. }
  1208. }
  1209. }
  1210. default:
  1211. break
  1212. }
  1213. // 执行右键操作后,需要取消框选区域
  1214. if self.listView.toolMode == .selectToolMode {
  1215. objc_sync_enter(self)
  1216. self.listView.selectionRect = NSZeroRect
  1217. self.listView.selectionPageIndex = UInt(NSNotFound)
  1218. objc_sync_exit(self)
  1219. }
  1220. }
  1221. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1222. let rect = listView.currentSelectionRect()
  1223. let page = listView.currentPage()
  1224. if NSIsEmptyRect(rect) == false && page != nil {
  1225. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1226. var bounds = listView.bounds
  1227. var scale = 1.0
  1228. if isLegacy {
  1229. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1230. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1231. }
  1232. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1233. scale = NSHeight(bounds) / NSHeight(rect)
  1234. } else {
  1235. scale = NSWidth(bounds) / NSWidth(rect)
  1236. }
  1237. listView.setScaleFactor(scale, animated: false)
  1238. let scrollView = listView.scroll()
  1239. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1240. if ((scrollView?.hasVerticalScroller) != nil) {
  1241. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1242. }
  1243. if ((scrollView?.hasHorizontalScroller) != nil) {
  1244. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1245. }
  1246. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1247. scale = NSHeight(bounds) / NSHeight(rect)
  1248. } else {
  1249. scale = NSWidth(bounds) / NSWidth(rect)
  1250. }
  1251. listView.setScaleFactor(scale, animated: false)
  1252. }
  1253. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1254. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1255. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1256. };
  1257. }
  1258. // 执行右键操作后,需要取消框选区域
  1259. if self.listView.toolMode == .selectToolMode {
  1260. objc_sync_enter(self)
  1261. self.listView.selectionRect = NSZeroRect
  1262. self.listView.selectionPageIndex = UInt(NSNotFound)
  1263. objc_sync_exit(self)
  1264. }
  1265. }
  1266. // @IBAction func autoCropAll(sender:NSMenuItem) {
  1267. //
  1268. // }
  1269. private func cropPagesToRects(rects:NSPointerArray) {
  1270. }
  1271. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1272. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1273. switch sender.tag {
  1274. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1275. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1276. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1277. var red: CGFloat = 0.0
  1278. var green: CGFloat = 0.0
  1279. var blue: CGFloat = 0.0
  1280. var alpha: CGFloat = 0.0
  1281. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1282. if sender.tag == CAnnotationType.highlight.rawValue {
  1283. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1284. } else if sender.tag == CAnnotationType.underline.rawValue {
  1285. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1286. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1287. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1288. }
  1289. case CAnnotationType.ink.rawValue:
  1290. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1291. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1292. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1293. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1294. var red: CGFloat = 0.0
  1295. var green: CGFloat = 0.0
  1296. var blue: CGFloat = 0.0
  1297. var alpha: CGFloat = 0.0
  1298. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1299. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1300. case CAnnotationType.freeText.rawValue:
  1301. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1302. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1303. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1304. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1305. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1306. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1307. var red: CGFloat = 0.0
  1308. var green: CGFloat = 0.0
  1309. var blue: CGFloat = 0.0
  1310. var alpha: CGFloat = 0.0
  1311. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1312. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1313. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1314. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1315. UserDefaults.standard.synchronize()
  1316. }
  1317. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1318. if (alignment == .left || alignment == .center || alignment == .right) {
  1319. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1320. UserDefaults.standard.synchronize()
  1321. }
  1322. case CAnnotationType.anchored.rawValue:
  1323. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1324. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1325. var red: CGFloat = 0.0
  1326. var green: CGFloat = 0.0
  1327. var blue: CGFloat = 0.0
  1328. var alpha: CGFloat = 0.0
  1329. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1330. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1331. case CAnnotationType.square.rawValue:
  1332. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1333. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1334. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1335. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1336. var red: CGFloat = 0.0
  1337. var green: CGFloat = 0.0
  1338. var blue: CGFloat = 0.0
  1339. var alpha: CGFloat = 0.0
  1340. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1341. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1342. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1343. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1344. case CAnnotationType.circle.rawValue:
  1345. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1346. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1347. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1348. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1349. var red: CGFloat = 0.0
  1350. var green: CGFloat = 0.0
  1351. var blue: CGFloat = 0.0
  1352. var alpha: CGFloat = 0.0
  1353. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1354. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1355. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1356. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1357. default:
  1358. break
  1359. }
  1360. }
  1361. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1362. self.showOrHideNotes()
  1363. }
  1364. //MARK: action
  1365. @objc func cropCurrentPage() {
  1366. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1367. var page: CPDFPage?
  1368. if ((self.listView.currentSelectionPage()) != nil) {
  1369. page = self.listView.currentSelectionPage()
  1370. } else {
  1371. page = self.listView.currentPage()
  1372. }
  1373. if (NSIsEmptyRect(rect)) {
  1374. rect = KMCropTools.getPageForegroundBox(page!)
  1375. }
  1376. let index: UInt = (page?.pageIndex())!
  1377. cropPage(at: index, in: rect)
  1378. // 执行右键操作后,需要取消框选区域
  1379. if self.listView.toolMode == .selectToolMode {
  1380. objc_sync_enter(self)
  1381. self.listView.selectionRect = NSZeroRect
  1382. self.listView.selectionPageIndex = UInt(NSNotFound)
  1383. objc_sync_exit(self)
  1384. }
  1385. }
  1386. func cropPage(at index: UInt, in rect: NSRect) {
  1387. let oldRect = self.listView.document.page(at: index)?.bounds(for: .cropBox)
  1388. let undoManager = self.listView.undoManager
  1389. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)!.cropPage(at: index, in: oldRect!)
  1390. let page = self.listView.document.page(at: index)
  1391. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox))!)
  1392. page?.setBounds(newRect, for: .cropBox)
  1393. /// 刷新预览视图
  1394. self.listView.layoutDocumentView()
  1395. self.listView.displayBox = .cropBox
  1396. }
  1397. @objc func cropAllPage() {
  1398. var size = NSZeroSize
  1399. for i in 0 ..< self.listView.document.pageCount {
  1400. let page = self.listView.document.page(at: i)
  1401. var rect = KMCropTools.getPageForegroundBox(page!)
  1402. size.width = fmax(size.width, NSWidth(rect))
  1403. size.height = fmax(size.height, NSHeight(rect))
  1404. }
  1405. var rectArray: Array<NSRect> = []
  1406. for i in 0 ..< self.listView.document.pageCount {
  1407. let page = self.listView.document.page(at: i)
  1408. var rect = KMCropTools.getPageForegroundBox(page!)
  1409. var bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1410. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1411. rect.origin.x = rect.maxX-size.width
  1412. }
  1413. rect.origin.y = rect.maxY-size.height
  1414. rect.size = size
  1415. if (NSWidth(rect) > NSWidth(bounds)) {
  1416. rect.size.width = NSWidth(bounds)
  1417. }
  1418. if (NSHeight(rect) > NSHeight(bounds)) {
  1419. rect.size.height = NSHeight(bounds)
  1420. }
  1421. if (NSMinX(rect) < NSMinX(bounds)) {
  1422. rect.origin.x = NSMinX(bounds)
  1423. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1424. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1425. }
  1426. if (NSMinY(rect) < NSMinY(bounds)) {
  1427. rect.origin.y = NSMinY(bounds)
  1428. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1429. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1430. }
  1431. rectArray.append(rect)
  1432. }
  1433. cropPages(to: rectArray)
  1434. }
  1435. func cropPages(to rects: Array<NSRect>) {
  1436. let currentPage = self.listView.currentPage()
  1437. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1438. var oldRectArray: Array<NSRect> = []
  1439. for i in 0 ..< self.listView.document.pageCount {
  1440. let page = self.listView.document.page(at: i)
  1441. var rect = NSIntersectionRect(rects[Int(i)], (page?.bounds(for: .mediaBox))!)
  1442. let oldRect = page?.bounds(for: .cropBox)
  1443. oldRectArray.append(oldRect!)
  1444. page?.setBounds(rect, for: .cropBox)
  1445. }
  1446. let undoManager = self.listView.undoManager
  1447. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1448. /// 刷新预览视图
  1449. self.listView.layoutDocumentView()
  1450. self.listView.displayBox = .cropBox
  1451. self.listView.go(to: currentPage)
  1452. self.listView.go(to: visibleRect, on: currentPage)
  1453. }
  1454. private func cropCustomArea() {
  1455. self.listView.toolMode = .selectToolMode
  1456. self.listView.autoScales = true
  1457. self.listView.autoScales = false
  1458. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  1459. if (self.listView.displaysPageBreaks) {
  1460. pageHeight += 8
  1461. }
  1462. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  1463. // if (scaleFactor < self.preView.scaleFactor) {
  1464. self.listView.scaleFactor = scaleFactor
  1465. // }
  1466. let tipView = KMCropTipView()
  1467. tipView.setString(string: "请框选裁剪区域")
  1468. tipView.frame = self.topTipBox.contentView!.frame
  1469. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  1470. self.addTopTip(tipView)
  1471. tipView.enterAction = {
  1472. () in
  1473. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1474. if (NSIsEmptyRect(rect)) {
  1475. return
  1476. }
  1477. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  1478. self.view.window?.beginSheet(window.window!)
  1479. self.cropSettingWindowController = window
  1480. window.itemClick = { [self]
  1481. (index: Int) in
  1482. if (index == 1) { /// 取消
  1483. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1484. self.cropSettingWindowController = nil
  1485. return
  1486. }
  1487. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  1488. let pageCount: Int = Int(self.listView.document.pageCount)
  1489. var pages: Array<Int> = []
  1490. if (pageRangeType == 0) { /// 当前页面
  1491. pages.append(self.listView.currentPageIndex)
  1492. } else if (pageRangeType == 1) { /// 全部页面
  1493. for i in 0 ..< pageCount {
  1494. pages.append(i)
  1495. }
  1496. } else if (pageRangeType == 2) { /// 奇数页面
  1497. var string: String = ""
  1498. for i in 0 ..< pageCount {
  1499. if (i % 2 == 1) {
  1500. continue
  1501. }
  1502. pages.append(i)
  1503. }
  1504. } else if (pageRangeType == 3) { /// 偶数页面
  1505. var string: String = ""
  1506. for i in 0 ..< pageCount {
  1507. if (i % 2 == 0) {
  1508. continue
  1509. }
  1510. pages.append(i)
  1511. }
  1512. } else { /// 自定义
  1513. for i in self.cropSettingWindowController.pageRangePages {
  1514. pages.append(i)
  1515. }
  1516. }
  1517. if (pages.count < 0) {
  1518. let alert = NSAlert()
  1519. alert.messageText = "请选择页面"
  1520. alert.runModal()
  1521. return
  1522. }
  1523. var pageSize: NSSize = NSZeroSize
  1524. if (self.cropSettingWindowController.pageSize == "None") {
  1525. } else {
  1526. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  1527. }
  1528. for i in pages {
  1529. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  1530. var rect = NSIntegralRect(self.listView.selectionRect)
  1531. if (NSIsEmptyRect(rect)) {
  1532. rect = KMCropTools.getPageForegroundBox(page)
  1533. }
  1534. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  1535. page.setBounds(newRect, for: .cropBox)
  1536. if (pageSize.width == 0 && pageSize.height == 0) {
  1537. } else {
  1538. // let tiffData = page.pdfListViewTIFFData(for: rect)
  1539. let index: UInt = (page.pageIndex())
  1540. // let newPage: CPDFPage = nil
  1541. // self.listView.document.removePage(at: index)
  1542. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  1543. // let result = self.preView.document.insertPageObject(newPage, at: index)
  1544. let result = self.listView.document.insertPage(pageSize, at: index)
  1545. }
  1546. }
  1547. /// 保存到临时路径
  1548. let toPath: String = self.listView.document.documentURL.path
  1549. let documentPath = NSTemporaryDirectory()
  1550. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1551. if (FileManager.default.fileExists(atPath: tempPath)) {
  1552. try?FileManager.default.removeItem(atPath: tempPath)
  1553. }
  1554. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  1555. if (result) {
  1556. if (FileManager.default.fileExists(atPath: toPath)) {
  1557. try?FileManager.default.removeItem(atPath: toPath)
  1558. }
  1559. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1560. } else {
  1561. try?FileManager.default.removeItem(atPath: tempPath)
  1562. }
  1563. DispatchQueue.main.async {
  1564. self.listView.toolMode = .textToolMode
  1565. /// 刷新预览视图
  1566. self.listView.layoutDocumentView()
  1567. self.listView.displayBox = .cropBox
  1568. }
  1569. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1570. self.cropSettingWindowController = nil
  1571. self.addTopTip(nil)
  1572. }
  1573. }
  1574. }
  1575. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1576. if (limit) {
  1577. var doucumentURL : URL = self.listView.document.documentURL
  1578. if doucumentURL != nil {
  1579. let docDir = NSTemporaryDirectory()
  1580. let documentName : String = doucumentURL.path.lastPathComponent
  1581. let path = docDir.stringByAppendingPathComponent(documentName)
  1582. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1583. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1584. let writeSuccess = data != nil
  1585. if writeSuccess == false {
  1586. __NSBeep()
  1587. return;
  1588. }
  1589. doucumentURL = URL(fileURLWithPath: path)
  1590. }
  1591. let array = [doucumentURL]
  1592. let picker = NSSharingServicePicker.init(items: array)
  1593. if sender.shareButton.window != nil {
  1594. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1595. } else {
  1596. 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)
  1597. }
  1598. return
  1599. }
  1600. var doucumentURL : URL = self.listView.document.documentURL
  1601. if doucumentURL != nil {
  1602. let docDir = NSTemporaryDirectory()
  1603. let documentName : String = doucumentURL.path.lastPathComponent
  1604. let path = docDir.stringByAppendingPathComponent(documentName)
  1605. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1606. if writeSuccess == false {
  1607. __NSBeep()
  1608. return;
  1609. }
  1610. doucumentURL = URL(fileURLWithPath: path)
  1611. }
  1612. let array = [doucumentURL]
  1613. let picker = NSSharingServicePicker.init(items: array)
  1614. if sender.shareButton.window != nil {
  1615. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1616. } else {
  1617. 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)
  1618. }
  1619. }
  1620. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1621. if (limit) {
  1622. let document = self.listView.document ?? CPDFDocument()
  1623. var path = document!.documentURL.path
  1624. if path != nil {
  1625. let docDir = NSTemporaryDirectory()
  1626. let documentName : String = path.lastPathComponent
  1627. path = docDir.stringByAppendingPathComponent(documentName)
  1628. }
  1629. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1630. var tfileName = path.deletingPathExtension.lastPathComponent
  1631. let tStdFileSuffix = "_flatten"
  1632. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1633. path = pathFolder + "/" + tfileName
  1634. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path))
  1635. let success = data != nil
  1636. if success {
  1637. let url = URL(fileURLWithPath: path)
  1638. let picker = NSSharingServicePicker.init(items: [url])
  1639. if sender.shareButton.window != nil {
  1640. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1641. } else {
  1642. 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)
  1643. }
  1644. }
  1645. return
  1646. }
  1647. let document = self.listView.document ?? CPDFDocument()
  1648. var path = document!.documentURL.path
  1649. if path != nil {
  1650. let docDir = NSTemporaryDirectory()
  1651. let documentName : String = path.lastPathComponent
  1652. path = docDir.stringByAppendingPathComponent(documentName)
  1653. }
  1654. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1655. var tfileName = path.deletingPathExtension.lastPathComponent
  1656. let tStdFileSuffix = "_flatten"
  1657. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1658. path = pathFolder + "/" + tfileName
  1659. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  1660. if success {
  1661. let url = URL(fileURLWithPath: path)
  1662. let picker = NSSharingServicePicker.init(items: [url])
  1663. if sender.shareButton.window != nil {
  1664. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1665. } else {
  1666. 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)
  1667. }
  1668. }
  1669. }
  1670. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  1671. if (limit) {
  1672. let document = self.listView.document ?? CPDFDocument()
  1673. var path = document!.documentURL.path
  1674. if path != nil {
  1675. let docDir = NSTemporaryDirectory()
  1676. let documentName : String = path.lastPathComponent
  1677. path = docDir.stringByAppendingPathComponent(documentName)
  1678. }
  1679. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1680. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1681. var writeSuccess = data != nil
  1682. if writeSuccess == false {
  1683. __NSBeep()
  1684. return;
  1685. }
  1686. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1687. for i in 0 ... newDocument.pageCount-1 {
  1688. let page = newDocument.page(at: i)
  1689. var annotations : [CPDFAnnotation] = []
  1690. for annotation in page!.annotations {
  1691. annotations.append(annotation)
  1692. }
  1693. for annotation in annotations {
  1694. annotation.page.removeAnnotation(annotation)
  1695. }
  1696. }
  1697. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1698. if writeSuccess {
  1699. let url = URL(fileURLWithPath: path)
  1700. let picker = NSSharingServicePicker.init(items: [url])
  1701. if sender.shareButton.window != nil {
  1702. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1703. } else {
  1704. 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)
  1705. }
  1706. }
  1707. return
  1708. }
  1709. let document = self.listView.document ?? CPDFDocument()
  1710. var path = document!.documentURL.path
  1711. if path != nil {
  1712. let docDir = NSTemporaryDirectory()
  1713. let documentName : String = path.lastPathComponent
  1714. path = docDir.stringByAppendingPathComponent(documentName)
  1715. }
  1716. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1717. if writeSuccess == false {
  1718. __NSBeep()
  1719. return;
  1720. }
  1721. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1722. for i in 0 ... newDocument.pageCount-1 {
  1723. let page = newDocument.page(at: i)
  1724. var annotations : [CPDFAnnotation] = []
  1725. for annotation in page!.annotations {
  1726. annotations.append(annotation)
  1727. }
  1728. for annotation in annotations {
  1729. annotation.page.removeAnnotation(annotation)
  1730. }
  1731. }
  1732. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1733. if writeSuccess {
  1734. let url = URL(fileURLWithPath: path)
  1735. let picker = NSSharingServicePicker.init(items: [url])
  1736. if sender.shareButton.window != nil {
  1737. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1738. } else {
  1739. 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)
  1740. }
  1741. }
  1742. }
  1743. // 开启/关闭左边栏
  1744. @objc func toggleLeftPane() -> Void {
  1745. // if lastLeftPanWidth >= functionWidth {
  1746. leftPanelOpen = true
  1747. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1748. // } else {
  1749. // leftPanelOpen = false
  1750. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1751. // }
  1752. }
  1753. // 开启左边栏
  1754. @objc func openLeftPane() -> Void {
  1755. leftPanelOpen = true
  1756. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1757. }
  1758. // 关闭左边栏
  1759. @objc func closeLeftPane() -> Void {
  1760. leftPanelOpen = false
  1761. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1762. }
  1763. // 开启/关闭右边栏
  1764. @objc func toggleRightPane() -> Void {
  1765. if lastRightPanWidth > 5 {
  1766. self.rightPanelIsOpen = false
  1767. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1768. } else {
  1769. self.rightPanelIsOpen = true
  1770. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1771. }
  1772. }
  1773. @objc func openRightPane() -> Void {
  1774. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1775. if self.rightPanelIsOpen {
  1776. return
  1777. }
  1778. self.rightPanelIsOpen = true
  1779. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  1780. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1781. }
  1782. }
  1783. @objc func closeRightPane() -> Void {
  1784. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1785. self.rightPanelIsOpen = false
  1786. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  1787. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1788. }
  1789. }
  1790. func rename(_ sender: NSNotification) -> Void {
  1791. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1792. return
  1793. }
  1794. let tabController = sender.object as? CTTabController
  1795. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1796. let outputSavePanel = NSSavePanel()
  1797. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1798. outputSavePanel.allowedFileTypes = ["pdf"]
  1799. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1800. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1801. let result = outputSavePanel.runModal()
  1802. if result == .OK {
  1803. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1804. let fileURL = pdfDocument?.documentURL
  1805. let fileManager = FileManager.default
  1806. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1807. var result = true
  1808. do {
  1809. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1810. } catch {
  1811. result = false
  1812. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1813. }
  1814. if (result) {
  1815. tabController?.title = outputSavePanel.url!.lastPathComponent
  1816. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1817. self.isSaveKeyChain = false
  1818. newPdfDocument.unlock(withPassword: self.document?.password)
  1819. if (newPdfDocument.pageCount > 0) {
  1820. self.setDocument = newPdfDocument
  1821. }
  1822. }
  1823. }
  1824. } else {
  1825. outputSavePanel.close()
  1826. }
  1827. }
  1828. }
  1829. func showInFinder(_ sender: Any) -> Void {
  1830. if sender is NSNotification {
  1831. let tabController = (sender as! NSNotification).object as? CTTabController
  1832. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1833. let file: URL = (self.myDocument?.fileURL)!
  1834. if FileManager.default.fileExists(atPath: file.path) {
  1835. NSWorkspace.shared.activateFileViewerSelecting([file])
  1836. }
  1837. }
  1838. } else {
  1839. let file: URL = (self.myDocument?.fileURL)!
  1840. if FileManager.default.fileExists(atPath: file.path) {
  1841. NSWorkspace.shared.activateFileViewerSelecting([file])
  1842. }
  1843. }
  1844. }
  1845. func showOrHideNotes() {
  1846. self.listView.hideNotes = !self.listView.hideNotes
  1847. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  1848. //BOTA 注释列表显示隐藏
  1849. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1850. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1851. }
  1852. func closeTab(_ sender: NSNotification) -> Void {
  1853. let tabController = sender.object as? CTTabController
  1854. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1855. print("closeTab")
  1856. self.leftSideViewController.clearAnnotationFilterData()
  1857. self.leftSideViewController.clearNotification()
  1858. }
  1859. }
  1860. // MARK: -
  1861. // MARK: 显示窗口
  1862. internal func showCompressWindow(url: URL? = nil) {
  1863. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  1864. KMPrint("压缩窗口已显示")
  1865. return
  1866. }
  1867. let windowController = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  1868. self.view.window?.beginSheet(windowController.window!)
  1869. self.currentWindowController = windowController
  1870. windowController.password = self.listView?.document?.password ?? ""
  1871. // if let _url = url {
  1872. // windowController.oriDocumentUrl = self.listView.document.documentURL
  1873. // windowController.documentURL = _url
  1874. // } else {
  1875. windowController.documentURL = self.listView.document.documentURL
  1876. // }
  1877. windowController.itemClick = { [weak self] in
  1878. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1879. self?.currentWindowController = nil
  1880. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1881. }
  1882. windowController.batchAction = { [weak self] view, filePaths in
  1883. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1884. self?.currentWindowController = nil
  1885. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1886. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1887. batchWindowController.window?.makeKeyAndOrderFront("")
  1888. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path)
  1889. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1890. batchWindowController.window?.makeKeyAndOrderFront("")
  1891. }
  1892. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  1893. if (result) {
  1894. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1895. self?.currentWindowController = nil
  1896. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1897. if (openDocument) {
  1898. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1899. } else {
  1900. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1901. }
  1902. } else {
  1903. let alert = NSAlert()
  1904. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1905. alert.runModal()
  1906. }
  1907. }
  1908. }
  1909. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1910. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1911. KMPrint("转档窗口已显示")
  1912. return
  1913. }
  1914. var convertT: KMConvertType = .Word
  1915. var windowController: KMConvertBaseWindowController?
  1916. if (type == .word) { /// Word
  1917. convertT = .Word
  1918. } else if (type == .excel) {
  1919. convertT = .Excel
  1920. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1921. if (type == .ppt) {
  1922. convertT = .PPT
  1923. } else if (type == .rtf) {
  1924. convertT = .RTF
  1925. } else if (type == .html) {
  1926. convertT = .HTML
  1927. } else if (type == .conversion_text) {
  1928. convertT = .Text
  1929. }
  1930. } else if (type == .csv) {
  1931. convertT = .CSV
  1932. } else if (type == .conversion_image) {
  1933. windowController = KMConvertImageWindowController()
  1934. }
  1935. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  1936. var url: URL?
  1937. if (documentUrl != nil) {
  1938. url = documentUrl
  1939. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1940. } else {
  1941. url = self.listView.document.documentURL
  1942. }
  1943. self.showAllConvertWindow(convertT: convertT)
  1944. // let model = KMDocumentModel(url: url!)
  1945. // if (self.listView.document.password != nil) {
  1946. // let _ = model.unlock(self.listView.document.password)
  1947. // }
  1948. // model.currentIndex = self.listView.currentPageIndex
  1949. // windowController?.documentModel = model
  1950. //
  1951. // windowController?.itemClick = { [weak self] index in
  1952. // if (identifier != nil) {
  1953. // self?.toolbarController.cancelSelected(identifier!)
  1954. // }
  1955. //
  1956. // if (self?.currentWindowController == nil) {
  1957. // return
  1958. // }
  1959. // self?.view.window?.endSheet(self!.currentWindowController.window!)
  1960. // self?.currentWindowController = nil
  1961. // }
  1962. //
  1963. // self.view.window?.beginSheet((windowController?.window)!)
  1964. // self.currentWindowController = windowController
  1965. }
  1966. //MARK: 转档 -
  1967. func showAllConvertWindow(convertT: KMConvertType) {
  1968. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1969. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1970. var type: KMConvertWithPDFType = .WordAdvance
  1971. switch convertT {
  1972. case .Word:
  1973. break
  1974. case .Excel:
  1975. type = .Excel
  1976. case .PPT:
  1977. type = .PowerPoint
  1978. case .RTF:
  1979. type = .RTF
  1980. case .CSV:
  1981. type = .CSV
  1982. case .HTML:
  1983. type = .HTML
  1984. case .Text:
  1985. type = .Text
  1986. case .JPEG:
  1987. type = .JPEG
  1988. case .PNG:
  1989. type = .PNG
  1990. case .GIF:
  1991. type = .GIF
  1992. case .JPG:
  1993. type = .JPG
  1994. case .TIFF:
  1995. type = .TIFF
  1996. case .TGA:
  1997. type = .TGA
  1998. case .BMP:
  1999. type = .BMP
  2000. case .JP2:
  2001. type = .JPEG2000
  2002. case .AdvancedWord:
  2003. break
  2004. default:
  2005. break
  2006. }
  2007. // let document = self.document
  2008. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2009. var needShowHint = false
  2010. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2011. needShowHint = true
  2012. } else {
  2013. var needContinue = false
  2014. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2015. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2016. let ss = self.document?.documentURL.path
  2017. if arr.contains(ss!) {
  2018. needContinue = false
  2019. }else {
  2020. needContinue = true
  2021. }
  2022. }else {
  2023. needContinue = true
  2024. }
  2025. if needContinue {
  2026. let ss = self.document?.documentURL.path
  2027. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2028. file.password = document?.password ?? ""
  2029. KMBatchOperateManager.defaultManager.files?.append(file)
  2030. }
  2031. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2032. batchWindowController.switchToConvertType(convertType: type)
  2033. }
  2034. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2035. if needShowHint {
  2036. batchWindowController.showIsConvertingHint()
  2037. } else {
  2038. }
  2039. }
  2040. }
  2041. self.km_beginSheet(windowC: convertWC)
  2042. }
  2043. //MARK: 转档 - OCR
  2044. func showOCRWindow() {
  2045. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  2046. self.km_beginSheet(windowC: com)
  2047. }
  2048. //MARK: 数字签名
  2049. func showDigitalSignWindow(withFilePathURL fileURL: URL) {
  2050. var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
  2051. var password: String = ""
  2052. if digitalSignController == nil {
  2053. password = listView.document?.password ?? ""
  2054. digitalSignController = KMPDFDigitalSignViewController()
  2055. }
  2056. digitalSignController?.currentPageIndex = Int(currentPageIndex)
  2057. digitalSignController?.url = listView.document.documentURL
  2058. digitalSignController?.password = password
  2059. digitalSignController?.scaleFactor = listView.scaleFactor
  2060. digitalSignController?.titleChangeBlock = { [weak self] title, index in
  2061. currentPageIndex = UInt(index)
  2062. }
  2063. digitalSignController?.buttonActionBlock = { [unowned self] type, isChanged in
  2064. if type == .cancel {
  2065. // self.toolbarController?.digitalSignModeButtonAction(nil)
  2066. if let page = self.listView.document?.page(at: currentPageIndex) {
  2067. self.listView.go(to: page)
  2068. }
  2069. self.digitalSignController?.view.removeFromSuperview()
  2070. self.digitalSignController = nil
  2071. }
  2072. }
  2073. if let digitalSignView = digitalSignController?.view, let splitViewSuperview = mianSplitView.superview {
  2074. digitalSignView.frame = splitViewSuperview.bounds
  2075. digitalSignView.autoresizingMask = [.width, .height]
  2076. splitViewSuperview.addSubview(digitalSignView)
  2077. }
  2078. }
  2079. //MARK: 导出图片
  2080. func extractImageAction(num: Int) {
  2081. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2082. let alert = NSAlert()
  2083. alert.alertStyle = .critical
  2084. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2085. alert.runModal()
  2086. return
  2087. }
  2088. // if sender is KMToolbarItem {
  2089. // (sender as! KMToolbarItem).isSelected = false
  2090. // }
  2091. // if !IAPProductsManager.defaultManager.isAvailableAllFunction {
  2092. // KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2093. // return
  2094. // }
  2095. let document = self.listView.document
  2096. var fileURL = document?.documentURL
  2097. if num == 1 {
  2098. let pageCount = self.document?.pageCount ?? 0
  2099. var indeSet = NSMutableIndexSet()
  2100. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2101. if indeSet.count == 0 {
  2102. return
  2103. }
  2104. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2105. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2106. let outputSavePanel = NSSavePanel()
  2107. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2108. outputSavePanel.allowsOtherFileTypes = true
  2109. outputSavePanel.isExtensionHidden = true
  2110. outputSavePanel.canCreateDirectories = true
  2111. outputSavePanel.nameFieldStringValue = tFileName
  2112. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2113. if result == NSApplication.ModalResponse.OK {
  2114. DispatchQueue.main.async {
  2115. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2116. let tDestFile = outputSavePanel.url!.path
  2117. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2118. let pdfconverter = PDFConvertObject()
  2119. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2120. self.dismissProgressSheet()
  2121. let fileManager = FileManager.default
  2122. if fileManager.fileExists(atPath: tDestFile) {
  2123. let workspace = NSWorkspace.shared
  2124. let url = URL(fileURLWithPath: tDestFile)
  2125. workspace.activateFileViewerSelecting([url])
  2126. }
  2127. }
  2128. }
  2129. })
  2130. return
  2131. }
  2132. if fileURL != nil {
  2133. self.myDocument?.save(nil)
  2134. } else {
  2135. let myDocument = self.myDocument
  2136. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2137. let writeSuccess = self.document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2138. if writeSuccess {
  2139. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2140. fileURL = self.document?.documentURL
  2141. } else {
  2142. NSSound.beep()
  2143. return
  2144. }
  2145. }
  2146. let extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2147. extract.docPath = fileURL?.path ?? ""
  2148. extract.password = document?.password ?? ""
  2149. extract.currentPage = self.listView.currentPageIndex
  2150. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2151. self.km_beginSheet(windowC: extract)
  2152. extract.selectCurrentPageBtn()
  2153. // self.showCreateStamp()
  2154. // self.showAddSignature()
  2155. }
  2156. //MARK: 创建文字图章示例实际上不会在这里使用
  2157. func showCreateStamp() {
  2158. let stampCreaterWindowController = KMStampCreaterWindowController()
  2159. stampCreaterWindowController.window?.backgroundColor = .clear
  2160. self.km_beginSheet(windowC: stampCreaterWindowController)
  2161. stampCreaterWindowController.closeCallBack = { result in
  2162. if result == 1 {
  2163. }
  2164. }
  2165. }
  2166. //MARK: 添加签名示例实际上不会在这里使用
  2167. func showAddSignature() {
  2168. var signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")//[[KMSignatureWindowController alloc] initWithWindowNibName:@"KMSignatureWindowController"];
  2169. // signatureWindowController.window?.backgroundColor = .clear
  2170. signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2171. }
  2172. }
  2173. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2174. // if progressController == nil {
  2175. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2176. // }
  2177. let progress = SKProgressController()
  2178. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2179. progress.window?.contentView?.wantsLayer = true
  2180. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2181. progress.progressField.textColor = NSColor.white
  2182. progress.message = NSLocalizedString("Converting...", comment: "")
  2183. progressController = progress
  2184. progressController?.message = message
  2185. if maxValue > 0 {
  2186. progressController?.indeterminate = false
  2187. progressController?.maxValue = Double(maxValue)
  2188. } else {
  2189. progressController?.indeterminate = true
  2190. }
  2191. self.km_beginSheet(windowC: progressController!)
  2192. }
  2193. func dismissProgressSheet() {
  2194. progressController?.stopAnimation()
  2195. self.km_endSheet()
  2196. progressController = nil
  2197. }
  2198. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2199. let newArr = NSMutableArray()
  2200. for item in files {
  2201. newArr.add(item.filePath)
  2202. }
  2203. return newArr as! [String]
  2204. }
  2205. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2206. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2207. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2208. if (result == .cancel) {
  2209. return
  2210. }
  2211. // 解除权限
  2212. self?.listView.document.unlock(withPassword: password)
  2213. // 隐藏提示
  2214. self?.hiddenSecureLimitTip()
  2215. // 去打印
  2216. if let data = self?.saveWatermarkFlag, !data {
  2217. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  2218. return
  2219. }
  2220. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  2221. _ = CPDFDocument(url: _url)
  2222. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  2223. } else {
  2224. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2225. }
  2226. }
  2227. return
  2228. }
  2229. if (!self.saveWatermarkFlag) {
  2230. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2231. return
  2232. }
  2233. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  2234. let _document = CPDFDocument(url: _url)
  2235. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  2236. } else {
  2237. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2238. }
  2239. }
  2240. // MARK: - Split View
  2241. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2242. }
  2243. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2244. if !isSinglePage && isHorizontal {
  2245. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  2246. }
  2247. if (!isSinglePage && !isHorizontal) {
  2248. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2249. }
  2250. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  2251. }
  2252. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  2253. if isSinglePage {
  2254. pdfSplitView.dividerStyle = .thin
  2255. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  2256. } else {
  2257. pdfSplitView.dividerStyle = .paneSplitter
  2258. pdfSplitView.isVertical = !isHorizontal
  2259. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  2260. if secondaryPdfView.document != nil {
  2261. // secondaryPdfView.frame = pdfSplitSecondView.frame
  2262. // pdfSplitSecondView.contentView = secondaryPdfView
  2263. } else {
  2264. openSecondaryPdfView = KMSecondaryViewController.init()
  2265. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  2266. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  2267. openSecondaryPdfView?.delegate = self
  2268. }
  2269. }
  2270. }
  2271. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  2272. if (pdfSplitView.isVertical) {
  2273. return Float(NSWidth(rect))
  2274. } else {
  2275. return Float(NSHeight(rect))
  2276. }
  2277. }
  2278. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  2279. let document = CPDFDocument.init(url: url)
  2280. if document != nil {
  2281. secondaryPdfView.frame = pdfSplitSecondView.frame
  2282. pdfSplitSecondView.contentView = secondaryPdfView
  2283. secondaryPdfView.document = nil
  2284. secondaryPdfView.document = document
  2285. return true
  2286. } else {
  2287. return false
  2288. }
  2289. }
  2290. func updateNextAndPreViousButtonState() {
  2291. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2292. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2293. if self.listView.canGoToNextPage() {
  2294. item?.unEnabled = false
  2295. } else {
  2296. item?.unEnabled = true
  2297. }
  2298. if self.listView.canGoToPreviousPage() {
  2299. toItem?.unEnabled = false
  2300. } else {
  2301. toItem?.unEnabled = true
  2302. }
  2303. }
  2304. func updateBackAndForwardButtonState() {
  2305. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2306. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2307. if self.listView.km_canGoBack() {
  2308. item?.unEnabled = false
  2309. } else {
  2310. item?.unEnabled = true
  2311. }
  2312. if self.listView.km_canGoForward() {
  2313. toItem?.unEnabled = false
  2314. } else {
  2315. toItem?.unEnabled = true
  2316. }
  2317. }
  2318. func updateZoomInOutButtonState() {
  2319. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  2320. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  2321. if self.listView.canZoomIn {
  2322. item.unEnabled = false
  2323. } else {
  2324. item.unEnabled = true
  2325. }
  2326. if self.listView.canZoomOut {
  2327. toItem.unEnabled = false
  2328. } else {
  2329. toItem.unEnabled = true
  2330. }
  2331. }
  2332. }
  2333. // MARK: -
  2334. // MARK: - KMSecondaryViewControllerDelegate
  2335. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  2336. func receivedFileUrl(_ url: URL!) {
  2337. let state = self.displaySecondaryPDFView(withUrl: url)
  2338. if !state {
  2339. let alert = NSAlert()
  2340. alert.alertStyle = .critical
  2341. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  2342. alert.runModal()
  2343. return
  2344. }
  2345. }
  2346. }
  2347. // MARK: -
  2348. // MARK: - KMMainToolbarControllerDelegate
  2349. extension KMMainViewController : KMMainToolbarControllerDelegate {
  2350. func changeModelAction(mode: CToolMode) {
  2351. self.listView.toolMode = mode
  2352. if mode == .editPDFToolMode {
  2353. self.childToolbarController.updateType(newType: .editPDF)
  2354. }
  2355. }
  2356. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  2357. switch selectedTag {
  2358. case 2:
  2359. if self.listView.scaleFactor != 1.0 {
  2360. self.listView.scaleFactor = 1.0
  2361. self.listView.autoScales = false
  2362. }
  2363. break
  2364. case 1:
  2365. let pageHeight = self.listView.currentPage()!.size.height
  2366. let pdfviewHeight = self.listView.bounds.size.height
  2367. self.listView.scaleFactor = pdfviewHeight/pageHeight
  2368. self.listView.autoScales = false
  2369. break
  2370. case 0:
  2371. // self.listView.autoScales = !self.listView.autoScales
  2372. self.listView.autoScales = true
  2373. break
  2374. case 3:
  2375. self.listView.scaleFactor = 0.1
  2376. break
  2377. case 4:
  2378. self.listView.scaleFactor = 0.25
  2379. break
  2380. case 5:
  2381. self.listView.scaleFactor = 0.5
  2382. break
  2383. case 6:
  2384. self.listView.scaleFactor = 0.75
  2385. break
  2386. case 7:
  2387. self.listView.scaleFactor = 1.0
  2388. break
  2389. case 8:
  2390. self.listView.scaleFactor = 1.5
  2391. break
  2392. case 9:
  2393. self.listView.scaleFactor = 2.0
  2394. break
  2395. case 10:
  2396. self.listView.scaleFactor = 4.0
  2397. break
  2398. case 11:
  2399. self.listView.scaleFactor = 8.0
  2400. break
  2401. case 12:
  2402. self.listView.scaleFactor = 10.0
  2403. break
  2404. default:
  2405. break
  2406. }
  2407. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2408. }
  2409. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  2410. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2411. if scale > 100 {
  2412. scale = 100
  2413. }
  2414. if (scale <= 0.101) {
  2415. self.listView.scaleFactor = self.listView.minScaleFactor()
  2416. } else {
  2417. self.listView.scaleFactor = scale
  2418. }
  2419. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2420. DispatchQueue.main.async {
  2421. self.updateZoomInOutButtonState()
  2422. }
  2423. }
  2424. func changePDFViewZoomInAction() {
  2425. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2426. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2427. switch scale {
  2428. case 0...0.25:
  2429. scale += 0.25
  2430. case 0.25...3:
  2431. scale += 0.25
  2432. case 3.1...10:
  2433. scale += 0.4
  2434. case 10.1...100:
  2435. scale += 1
  2436. default:
  2437. scale += 1
  2438. }
  2439. self.listView.scaleFactor = scale
  2440. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2441. // self.listView.zoomIn(nil)
  2442. }
  2443. func changePDFViewZoomOutAction() {
  2444. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2445. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2446. switch scale {
  2447. case 0...0.25:
  2448. scale = 0
  2449. case 0.25...3:
  2450. scale -= 0.25
  2451. case 3.1...10:
  2452. scale -= 0.4
  2453. case 10.1...100:
  2454. scale -= 1
  2455. default:
  2456. scale -= 1
  2457. }
  2458. self.listView.scaleFactor = scale
  2459. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2460. // self.listView.zoomOut(nil)
  2461. // self.updateZoomInOutButtonState()
  2462. }
  2463. func changePDFViewGotoNextPageAction() {
  2464. self.listView.km_goBack(nil)
  2465. if (self.listView.canGoToNextPage()) {
  2466. self.listView.goToNextPage(nil)
  2467. }
  2468. self.updateNextAndPreViousButtonState()
  2469. }
  2470. func changePDFViewGoToPreviousPageAction() {
  2471. if (self.listView.canGoToPreviousPage()) {
  2472. self.listView.goToPreviousPage(nil)
  2473. }
  2474. self.updateNextAndPreViousButtonState()
  2475. }
  2476. func changePDFViewGotoBackAction() {
  2477. self.listView.km_goBack(nil)
  2478. self.updateBackAndForwardButtonState()
  2479. }
  2480. func changePDFViewGoToForwardAction() {
  2481. self.listView.km_goForward(nil)
  2482. self.updateBackAndForwardButtonState()
  2483. }
  2484. func aiTranslationPDFFileAction() {
  2485. #if VERSION_DMG
  2486. #else
  2487. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  2488. KMLoginWindowController.show(window: NSApp.mainWindow!)
  2489. return
  2490. }
  2491. #endif
  2492. self.trackEvent_aiTranslate()
  2493. self._aiTranslationPDFFileAction()
  2494. // Task { @MainActor in
  2495. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2496. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  2497. // if (isClose) {
  2498. // return
  2499. // }
  2500. // if (isSub) {
  2501. // self._aiTranslationPDFFileAction()
  2502. // return
  2503. // }
  2504. // }
  2505. // return
  2506. // }
  2507. //
  2508. // self._aiTranslationPDFFileAction()
  2509. // }
  2510. }
  2511. private func _aiTranslationPDFFileAction() {
  2512. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2513. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2514. let alert = NSAlert()
  2515. alert.alertStyle = .critical
  2516. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2517. alert.runModal()
  2518. return
  2519. } else if isExceedsLimit {
  2520. let alert = NSAlert()
  2521. alert.alertStyle = .critical
  2522. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2523. alert.runModal()
  2524. return
  2525. }
  2526. let alert = NSAlert()
  2527. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2528. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2529. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2530. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2531. if (result == .alertFirstButtonReturn) {
  2532. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  2533. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  2534. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  2535. } else if result == .alertSecondButtonReturn {
  2536. return
  2537. }
  2538. }
  2539. }
  2540. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2541. self.trackEvent_share()
  2542. }
  2543. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2544. if (!self.saveWatermarkFlag) {
  2545. self.shareDocument(sender: viewController)
  2546. return
  2547. }
  2548. Task { @MainActor in
  2549. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2550. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2551. if (isClose) {
  2552. return
  2553. }
  2554. if (isSubscribeSuccess) {
  2555. self.shareDocument(sender: viewController)
  2556. return
  2557. }
  2558. if (isWaterMarkExport) {
  2559. self.shareDocument(sender: viewController, limit: true)
  2560. return
  2561. }
  2562. }
  2563. return
  2564. }
  2565. self.shareDocument(sender: viewController)
  2566. }
  2567. }
  2568. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2569. // if (!self.saveWatermarkFlag) {
  2570. // self.shareFlatten(sender: viewController)
  2571. // return
  2572. // }
  2573. Task { @MainActor in
  2574. #if VERSION_DMG
  2575. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2576. let _ = KMComparativeTableViewController.show(window: self.view.window!, .shareFlatten)
  2577. return
  2578. }
  2579. #endif
  2580. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2581. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2582. if (isClose) {
  2583. return
  2584. }
  2585. if (isSubscribeSuccess) {
  2586. self.shareFlatten(sender: viewController)
  2587. return
  2588. }
  2589. if (isWaterMarkExport) {
  2590. self.shareFlatten(sender: viewController, limit: true)
  2591. return
  2592. }
  2593. }
  2594. return
  2595. }
  2596. self.shareFlatten(sender: viewController)
  2597. }
  2598. }
  2599. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2600. if (!self.saveWatermarkFlag) {
  2601. self.shareOriginalPDF(sender: viewController)
  2602. return
  2603. }
  2604. Task { @MainActor in
  2605. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2606. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2607. if (isClose) {
  2608. return
  2609. }
  2610. if (isSubscribeSuccess) {
  2611. self.shareOriginalPDF(sender: viewController)
  2612. return
  2613. }
  2614. if (isWaterMarkExport) {
  2615. self.shareOriginalPDF(sender: viewController, limit: true)
  2616. return
  2617. }
  2618. }
  2619. return
  2620. }
  2621. self.shareOriginalPDF(sender: viewController)
  2622. }
  2623. }
  2624. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2625. if(0 == selectedTag) {
  2626. // self.documentAIViewController?.enteredIncreaseAllPage()
  2627. // self.documentAIViewController?.updateToolState(false)
  2628. } else {
  2629. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  2630. // self.documentAIViewController?.recognitionPartModel(with: .english)
  2631. // self.documentAIViewController?.updateToolState(true)
  2632. }
  2633. // 0 : Scan 1:OCR Text
  2634. }
  2635. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2636. if beforeType == .editPDF {
  2637. // self.asyncSaveDocument { params in
  2638. //
  2639. // }
  2640. }
  2641. // 埋点
  2642. self.trackEvent(toolType: type)
  2643. if(type != .Page) {
  2644. if (hasEnterPageEdit()) {
  2645. self.exitPageEdit()
  2646. }
  2647. }
  2648. if(type != .ScanOCR) {
  2649. // if ((self.documentAIViewController?.view.superview) != nil) {
  2650. // self.listView.isHidden = false
  2651. // self.documentAIViewController?.creatRecognitionDocument()
  2652. // self.documentAIViewController?.view .removeFromSuperview()
  2653. // self.documentAIViewController = nil;
  2654. // self.listView.layoutDocumentView()
  2655. // }
  2656. }
  2657. if (type == .Page) {
  2658. if (hasEnterPageEdit()) {
  2659. self.exitPageEdit()
  2660. } else {
  2661. self.enterPageEdit(pages)
  2662. }
  2663. } else if(type == .ScanOCR) {
  2664. // if((self.documentAIViewController?.view.superview) != nil) {
  2665. // let alert = NSAlert()
  2666. // alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  2667. // alert.addButton(withTitle: "YES")
  2668. // alert.addButton(withTitle: "NO")
  2669. // let result = alert.runModal()
  2670. // if (result == .alertFirstButtonReturn) { /// 取消
  2671. // self.listView.isHidden = false
  2672. // self.documentAIViewController?.creatRecognitionDocument()
  2673. // self.documentAIViewController?.view .removeFromSuperview()
  2674. // self.documentAIViewController = nil;
  2675. // self.listView.layoutDocumentView()
  2676. // } else {
  2677. // self.toolbarController.toolbarType = .ScanOCR
  2678. // }
  2679. // } else {
  2680. // self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  2681. // self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  2682. // self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  2683. // self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  2684. // self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  2685. // }
  2686. } else if type == .editPDF {
  2687. self.listView.annotationType = .editTextImage
  2688. } else if type == .Annatiton {
  2689. self.rightSideViewController.subViewType = .AnnotationProperts
  2690. } else if type == .redact {
  2691. self.enterRedact()
  2692. }
  2693. }
  2694. func clickChildTool(type: KMToolbarType, index: Int) {
  2695. if (type == .secure) {
  2696. if (index == 1) {
  2697. self.trackEvent_setPassword()
  2698. } else if (index == 2) {
  2699. self.trackEvent_removePassword()
  2700. }
  2701. } else {
  2702. self.trackEvent(toolBarType: type)
  2703. }
  2704. Task { @MainActor in
  2705. if (type == .compress) { /// 压缩
  2706. // #if VERSION_DMG
  2707. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2708. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  2709. // self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2710. // return
  2711. // }
  2712. // #endif
  2713. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2714. // self.view.window?.contentView?.superview?.beginLoading()
  2715. let document = self.listView.document
  2716. let secureOptions = self.secureOptions
  2717. let removeSecureFlag = self.removeSecureFlag
  2718. // DispatchQueue.global().async { [unowned self] in
  2719. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  2720. // DispatchQueue.main.async {
  2721. // self.view.window?.contentView?.superview?.endLoading()
  2722. // }
  2723. return
  2724. }
  2725. // DispatchQueue.main.async {
  2726. // self.view.window?.contentView?.superview?.endLoading()
  2727. self.showCompressWindow(url: _url)
  2728. // }
  2729. // }
  2730. return
  2731. }
  2732. if (self.needSaveDocument()) {
  2733. self.saveDocumentWithProgressAlert { [unowned self] params in
  2734. self.showCompressWindow()
  2735. }
  2736. return
  2737. }
  2738. self.showCompressWindow()
  2739. return
  2740. }
  2741. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  2742. var identifier: String?
  2743. if (type == .word) { /// Word
  2744. identifier = KMToolbarConversionWordItemIdentifier
  2745. } else if (type == .excel) {
  2746. identifier = KMToolbarConversionExcelItemIdentifier
  2747. } else if (type == .ppt) {
  2748. identifier = KMToolbarConversionPPTItemIdentifier
  2749. } else if (type == .rtf) {
  2750. identifier = KMToolbarConversionRTFItemIdentifier
  2751. } else if (type == .html) {
  2752. identifier = KMToolbarConversionHTMLItemIdentifier
  2753. } else if (type == .conversion_text) {
  2754. identifier = KMToolbarConversionTextItemIdentifier
  2755. } else if (type == .csv) {
  2756. identifier = KMToolbarConversionCSVItemIdentifier
  2757. } else if (type == .conversion_image) {
  2758. identifier = KMToolbarConversionImageItemIdentifier
  2759. }
  2760. #if VERSION_DMG
  2761. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2762. // if (identifier != nil) {
  2763. // self.toolbarController.cancelSelected(identifier!)
  2764. // }
  2765. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .convert)
  2766. // return
  2767. // }
  2768. #endif
  2769. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2770. // guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2771. // return
  2772. // }
  2773. // self.showConvertWindow(type: type, documentUrl: _url, identifier: identifier)
  2774. // return
  2775. // }
  2776. if (self.needSaveDocument()) {
  2777. self.saveDocumentWithProgressAlert { [unowned self] params in
  2778. self.showConvertWindow(type: type, identifier: identifier)
  2779. }
  2780. return
  2781. }
  2782. self.showConvertWindow(type: type, identifier: identifier)
  2783. return
  2784. }
  2785. if (type == .merge) { /// 合并
  2786. // #if VERSION_DMG
  2787. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2788. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  2789. //
  2790. // self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  2791. // return
  2792. // }
  2793. // #endif
  2794. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  2795. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2796. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2797. if (result == .cancel) {
  2798. return
  2799. }
  2800. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2801. return
  2802. }
  2803. self.showMergeWindow(url: _url, password)
  2804. }
  2805. return
  2806. }
  2807. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2808. if (result == .cancel) {
  2809. return
  2810. }
  2811. if (self.needSaveDocument()) {
  2812. self.saveDocumentWithProgressAlert { [unowned self] params in
  2813. self.showMergeWindow(password)
  2814. }
  2815. return
  2816. }
  2817. self.showMergeWindow(password)
  2818. }
  2819. return
  2820. }
  2821. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2822. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2823. return
  2824. }
  2825. self.showMergeWindow(url: _url, password)
  2826. return
  2827. }
  2828. if (self.needSaveDocument()) {
  2829. self.saveDocumentWithProgressAlert { [unowned self] params in
  2830. self.showMergeWindow(self.listView.document.password)
  2831. }
  2832. return
  2833. }
  2834. self.showMergeWindow(self.listView.document.password)
  2835. return
  2836. }
  2837. if (type == .crop) {
  2838. #if VERSION_DMG
  2839. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2840. let _ = KMComparativeTableViewController.show(window: self.view.window!, .crop)
  2841. return
  2842. }
  2843. #endif
  2844. self.recordSaveWatermarkFlag(type: .crop)
  2845. if (index == 1) {
  2846. self.cropCurrentPage()
  2847. return
  2848. }
  2849. if (index == 2) {
  2850. self.cropAllPage()
  2851. return
  2852. }
  2853. //// 自定义裁剪区域
  2854. // self.cropCustomArea()
  2855. } else if (type == .bates || type == .headerAndFooter) {
  2856. if (index == 1) {
  2857. var windowController: KMBaseWindowController = KMBaseWindowController()
  2858. if (type == .bates) {
  2859. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2860. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2861. let file = KMFileAttribute()
  2862. file.filePath = (self.document?.documentURL.path)!
  2863. self.showBatchWindow(type: .AddBates, files: [file])
  2864. }
  2865. windowController.isBates = true
  2866. } else if (type == .headerAndFooter) {
  2867. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2868. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2869. let file = KMFileAttribute()
  2870. file.filePath = (self.document?.documentURL.path)!
  2871. self.showBatchWindow(type: .AddHeaderFooter, files: [file])
  2872. }
  2873. } else if (type == .background) {
  2874. // controller = KMBackgroundController()
  2875. } else if (type == .watermark) {
  2876. // controller = KMWatermarkViewController()
  2877. }
  2878. windowController.pdfDocument = self.listView.document
  2879. windowController.cancelAction = { [unowned self] controller in
  2880. self.view.window?.endSheet((self.currentWindowController.window)!)
  2881. self.currentWindowController = nil
  2882. }
  2883. self.currentWindowController = windowController
  2884. await self.view.window?.beginSheet(windowController.window!)
  2885. return
  2886. }
  2887. if (index == 1) { /// 取消
  2888. self.toolbarController.exitWatermarkAdjective()
  2889. // self.rightSideViewController.view.isHidden = true
  2890. self.rightSideViewController.isHidden = true
  2891. self.rightSideViewController.subViewType = .None
  2892. self.closeRightPane()
  2893. return
  2894. } else if index == 3 {
  2895. let file = KMFileAttribute()
  2896. file.filePath = (self.document?.documentURL.path)!
  2897. if type == .bates {
  2898. self.showBatchWindow(type: .AddBates, files: [file])
  2899. } else {
  2900. self.showBatchWindow(type: .AddHeaderFooter, files: [file])
  2901. }
  2902. } else if index == 4 {
  2903. let file = KMFileAttribute()
  2904. file.filePath = (self.document?.documentURL.path)!
  2905. if type == .bates {
  2906. self.showBatchWindow(type: .RemoveBates, files: [file])
  2907. } else {
  2908. self.showBatchWindow(type: .RemoveHeaderFooter, files: [file])
  2909. }
  2910. } else if (index == 2) { //// 移除
  2911. if type == .headerAndFooter {
  2912. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2913. let savePanel = NSSavePanel()
  2914. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2915. savePanel.allowedFileTypes = ["pdf"]
  2916. savePanel.accessoryView = savePanelAccessoryViewController.view
  2917. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2918. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2919. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2920. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2921. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2922. }
  2923. } else {
  2924. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2925. }
  2926. }
  2927. }
  2928. }
  2929. } else if type == .bates {
  2930. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2931. let savePanel = NSSavePanel()
  2932. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2933. savePanel.allowedFileTypes = ["pdf"]
  2934. savePanel.accessoryView = savePanelAccessoryViewController.view
  2935. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2936. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2937. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2938. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2939. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2940. }
  2941. } else {
  2942. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2943. }
  2944. }
  2945. }
  2946. }
  2947. }
  2948. return
  2949. } else if (index == 2) { /// 应用
  2950. let model = self.rightSideViewController.model
  2951. if (type == .bates || type == .headerAndFooter) {
  2952. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2953. let alert = NSAlert()
  2954. alert.alertStyle = .critical
  2955. alert.messageText = "没有找到模型"
  2956. alert.runModal()
  2957. return
  2958. }
  2959. if ((model as! KMBatesModel).hasVaild == false) {
  2960. let alert = NSAlert()
  2961. alert.alertStyle = .critical
  2962. alert.messageText = "没有找到内容"
  2963. alert.runModal()
  2964. return
  2965. }
  2966. }
  2967. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2968. result in
  2969. DispatchQueue.main.async {
  2970. self.listView.layoutDocumentView()
  2971. self.listView.setNeedsDisplayForVisiblePages()
  2972. }
  2973. if (result) {
  2974. let alert = NSAlert()
  2975. alert.alertStyle = .warning
  2976. alert.messageText = "成功"
  2977. alert.runModal()
  2978. } else {
  2979. let alert = NSAlert()
  2980. alert.alertStyle = .critical
  2981. alert.messageText = "失败"
  2982. alert.runModal()
  2983. }
  2984. }
  2985. return
  2986. } else if index == 5 {
  2987. self.rightSideViewController.isHidden = false
  2988. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2989. self.openRightPane()
  2990. }
  2991. } else if (type == .redact) { /// 标记密文
  2992. if (index == 1) { /// 取消
  2993. if (self.hasAddRedact) {
  2994. let alert = NSAlert()
  2995. 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: "")
  2996. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2997. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2998. let result = alert.runModal()
  2999. if (result == .alertFirstButtonReturn) {
  3000. self.listView.toolMode = .moveToolMode
  3001. self.toolbarController.exitRedact()
  3002. }
  3003. return
  3004. }
  3005. self.listView.toolMode = .moveToolMode
  3006. self.toolbarController.exitRedact()
  3007. return
  3008. }
  3009. if (index == 2) { /// 擦除
  3010. self.exeRedactConfirm(.eraserAll) {}
  3011. return
  3012. }
  3013. if (index == 3) { /// 应用
  3014. self.exeRedactConfirm(.redactAll) {}
  3015. return
  3016. }
  3017. if (index == 4) { /// 文本&图像
  3018. self.listView.toolMode = .redactToolMode
  3019. return
  3020. }
  3021. if (index == 5) { /// 页面
  3022. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3023. await self.view.window?.beginSheet(windowController.window!)
  3024. self.currentWindowController = windowController
  3025. windowController.itemClick = { [weak self] index, value in
  3026. if (index == 1) {
  3027. let topBarView = self?.toolbarController.fetchTopBarView()
  3028. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  3029. return
  3030. }
  3031. (topBarView as! KMRedactTopToolBar).selectItem(0)
  3032. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3033. self?.currentWindowController = nil
  3034. return
  3035. }
  3036. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3037. let pageType = windowController_pageRange.pageType
  3038. let pageString = windowController_pageRange.pageString
  3039. if (pageType == 5) { /// 自定义页面
  3040. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  3041. if (array.count == 0) {
  3042. let alert = NSAlert()
  3043. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3044. alert.runModal()
  3045. return
  3046. }
  3047. }
  3048. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3049. self!.currentWindowController = nil
  3050. var indexs: IndexSet = []
  3051. if (pageType == 1) { /// 当前页面
  3052. indexs.insert((self?.listView.currentPageIndex)!)
  3053. } else {
  3054. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  3055. }
  3056. if (indexs.count == 0) {
  3057. return
  3058. }
  3059. for i in indexs {
  3060. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3061. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3062. redactAnno.bounds = page.bounds
  3063. self?.listView.add(redactAnno, to: page)
  3064. }
  3065. }
  3066. return
  3067. }
  3068. } else if (type == .secure) { /// 安全
  3069. #if VERSION_DMG
  3070. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  3071. let _ = KMComparativeTableViewController.show(window: self.view.window!, .secure)
  3072. return
  3073. }
  3074. #endif
  3075. if (index == 1) { /// 设置密码
  3076. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3077. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  3078. if (result == .cancel) {
  3079. return
  3080. }
  3081. self?.isSaveKeyChain = false
  3082. self?.listView.document.unlock(withPassword: password)
  3083. self?.hiddenSecureLimitTip()
  3084. self?.showSecureWindow((self?.listView.document.documentURL)!)
  3085. }
  3086. return
  3087. }
  3088. self.showSecureWindow(self.listView.document.documentURL)
  3089. return
  3090. } else if index == 2 {
  3091. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3092. let alert = NSAlert()
  3093. alert.alertStyle = .warning
  3094. alert.messageText = NSLocalizedString("Warning", comment: "")
  3095. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3096. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3097. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3098. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3099. if returnCode == .alertSecondButtonReturn {
  3100. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3101. KMBaseWindowController.checkPassword(url: self.document!.documentURL!) { [unowned self] success, resultPassword in
  3102. if success {
  3103. self.document?.unlock(withPassword: resultPassword)
  3104. self.clickChildTool(type: .secure, index: 2)
  3105. // /// 删除安全性设置
  3106. // if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3107. // self.isSaveKeyChain = false
  3108. // self.listView.document.unlock(withPassword: password)
  3109. // self.hiddenSecureLimitTip()
  3110. // self.recordRemoveSecureFlag()
  3111. // self.recordSaveWatermarkFlag(type: .removePassword)
  3112. //
  3113. // let tip = KMRemovePasswordResultTipView()
  3114. // tip.result = .success
  3115. // tip.showInView(superView: (self.listView.superview)!)
  3116. // } else {
  3117. // self.recordRemoveSecureFlag()
  3118. // self.recordSaveWatermarkFlag(type: .removePassword)
  3119. // let tip = KMRemovePasswordResultTipView()
  3120. // tip.result = .success
  3121. // self.hiddenSecureLimitTip()
  3122. //
  3123. // tip.showInView(superView: self.listView.superview!)
  3124. // }
  3125. }
  3126. }
  3127. }
  3128. }
  3129. }
  3130. } else {
  3131. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3132. controller.pdfDocument = self.document
  3133. self.currentWindowController = controller
  3134. controller.batchAction = { [unowned self] controller, files in
  3135. self.view.window?.endSheet((self.currentWindowController.window)!)
  3136. self.currentWindowController = nil
  3137. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3138. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3139. batchWindowController.window?.makeKeyAndOrderFront("")
  3140. let batchOperateFile = KMBatchOperateFile(filePath: files.first?.filePath ?? "")
  3141. batchWindowController.switchToOperateType(.RemovePassword, files: [batchOperateFile])
  3142. batchWindowController.window?.makeKeyAndOrderFront("")
  3143. }
  3144. controller.cancelAction = { [unowned self] controller in
  3145. self.view.window?.endSheet((self.currentWindowController.window)!)
  3146. self.currentWindowController = nil
  3147. }
  3148. controller.doneAction = { [unowned self] controller in
  3149. self.view.window?.endSheet((self.currentWindowController.window)!)
  3150. self.currentWindowController = nil
  3151. KMBaseWindowController.checkPassword(url: self.document!.documentURL!) { [unowned self] success, resultPassword in
  3152. if success {
  3153. /// 删除安全性设置
  3154. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3155. self.isSaveKeyChain = false
  3156. self.listView.document.unlock(withPassword: password)
  3157. self.hiddenSecureLimitTip()
  3158. self.recordRemoveSecureFlag()
  3159. self.recordSaveWatermarkFlag(type: .removePassword)
  3160. let tip = KMRemovePasswordResultTipView()
  3161. tip.result = .success
  3162. tip.showInView(superView: (self.listView.superview)!)
  3163. } else {
  3164. self.recordRemoveSecureFlag()
  3165. self.recordSaveWatermarkFlag(type: .removePassword)
  3166. let tip = KMRemovePasswordResultTipView()
  3167. tip.result = .success
  3168. self.hiddenSecureLimitTip()
  3169. tip.showInView(superView: self.listView.superview!)
  3170. }
  3171. }
  3172. }
  3173. }
  3174. await NSWindow.currentWindow().beginSheet(controller.window!)
  3175. }
  3176. return
  3177. }
  3178. } else if type == .comparison {
  3179. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3180. self.currentWindowController = controller
  3181. controller.filePath = (self.document?.documentURL.path)!
  3182. controller.cancelAction = { [unowned self] controller in
  3183. self.view.window?.endSheet((self.currentWindowController.window)!)
  3184. self.currentWindowController = nil
  3185. }
  3186. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3187. DispatchQueue.main.async {
  3188. self.view.window?.endSheet((controller.window)!)
  3189. self.currentWindowController = nil
  3190. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3191. }
  3192. }
  3193. controller.coveringComplete = { [unowned self] controller, document in
  3194. self.view.window?.endSheet((controller.window)!)
  3195. self.currentWindowController = nil
  3196. self.openCoveringCompareVC(with: document)
  3197. }
  3198. if index == 1 {
  3199. controller.fileType = .content
  3200. } else {
  3201. controller.fileType = .coverting
  3202. }
  3203. await NSWindow.currentWindow().beginSheet(controller.window!)
  3204. } else if type == .watermark {
  3205. if index == 1 {
  3206. let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  3207. self.currentWindowController = controller
  3208. controller.pdfDocument = self.document
  3209. controller.cancelAction = { [unowned self] controller in
  3210. self.view.window?.endSheet((self.currentWindowController.window)!)
  3211. self.currentWindowController = nil
  3212. }
  3213. controller.operateCallBack = { [unowned self] controller, watermark, countType in
  3214. let file = KMFileAttribute()
  3215. file.filePath = (self.document?.documentURL.path)!
  3216. self.showBatchWindow(type: .AddWatermark, files: [file])
  3217. }
  3218. await NSWindow.currentWindow().beginSheet(controller.window!)
  3219. } else if index == 2 {
  3220. let watermarks = self.listView.document.watermarks()
  3221. if (watermarks == nil || watermarks!.count <= 0) {
  3222. let alert = NSAlert()
  3223. alert.alertStyle = .warning
  3224. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  3225. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  3226. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  3227. alert.runModal()
  3228. return
  3229. }
  3230. let alert = NSAlert()
  3231. alert.alertStyle = .warning
  3232. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  3233. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  3234. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  3235. let result = alert.runModal()
  3236. if (result != .alertFirstButtonReturn) {
  3237. return
  3238. }
  3239. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  3240. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  3241. result in
  3242. DispatchQueue.main.async {
  3243. self.listView.layoutDocumentView()
  3244. self.listView.setNeedsDisplayForVisiblePages()
  3245. }
  3246. if (result) {
  3247. let alert = NSAlert()
  3248. alert.alertStyle = .warning
  3249. alert.messageText = "成功"
  3250. alert.runModal()
  3251. } else {
  3252. let alert = NSAlert()
  3253. alert.alertStyle = .critical
  3254. alert.messageText = "失败"
  3255. alert.runModal()
  3256. }
  3257. }
  3258. } else if index == 3 {
  3259. let file = KMFileAttribute()
  3260. file.filePath = (self.document?.documentURL.path)!
  3261. self.showBatchWindow(type: .AddWatermark, files: [file])
  3262. } else if index == 4 {
  3263. let file = KMFileAttribute()
  3264. file.filePath = (self.document?.documentURL.path)!
  3265. self.showBatchWindow(type: .RemoveWatermark, files: [file])
  3266. } else if index == 5 {
  3267. self.rightSideViewController.isHidden = false
  3268. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3269. self.openRightPane()
  3270. return
  3271. }
  3272. } else if type == .background {
  3273. if index == 1 {
  3274. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  3275. self.currentWindowController = controller
  3276. controller.pdfDocument = self.document
  3277. controller.cancelAction = { [unowned self] controller in
  3278. self.view.window?.endSheet((self.currentWindowController.window)!)
  3279. self.currentWindowController = nil
  3280. }
  3281. controller.operateCallBack = { [unowned self] controller, background, countType in
  3282. let file = KMFileAttribute()
  3283. file.filePath = (self.document?.documentURL.path)!
  3284. self.showBatchWindow(type: .AddBackground, files: [file])
  3285. }
  3286. await NSWindow.currentWindow().beginSheet(controller.window!)
  3287. } else if index == 2 {
  3288. guard let document = self.document else { return }
  3289. if !document.allowsPrinting || !document.allowsCopying {
  3290. let alert = NSAlert()
  3291. alert.alertStyle = .critical
  3292. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3293. alert.runModal()
  3294. return
  3295. }
  3296. guard let documentURL = document.documentURL else { return }
  3297. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3298. let savePanel = NSSavePanel()
  3299. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  3300. savePanel.allowedFileTypes = ["pdf"]
  3301. savePanel.accessoryView = savePanelAccessoryViewController.view
  3302. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3303. guard result == .OK else { return }
  3304. KMAddBackgroundView.saveAsPDFRemoveAllBackground(PDFDocument: document, password: document.password, toPath: savePanel.url!.path, completionHandler: { [unowned self] success in
  3305. if success == 1 {
  3306. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3307. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { _, _, _ in }
  3308. } else {
  3309. NSWorkspace.shared.selectFile(savePanel.url!.path, inFileViewerRootedAtPath: "")
  3310. }
  3311. }
  3312. })
  3313. }
  3314. } else if index == 3 {
  3315. let file = KMFileAttribute()
  3316. file.filePath = (self.document?.documentURL.path)!
  3317. self.showBatchWindow(type: .AddBackground, files: [file])
  3318. } else if index == 4 {
  3319. let file = KMFileAttribute()
  3320. file.filePath = (self.document?.documentURL.path)!
  3321. self.showBatchWindow(type: .RemoveBackground, files: [file])
  3322. } else if index == 5 {
  3323. self.rightSideViewController.isHidden = false
  3324. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3325. self.openRightPane()
  3326. return
  3327. }
  3328. }
  3329. }
  3330. }
  3331. func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  3332. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3333. batchWindowController.window?.makeKeyAndOrderFront("")
  3334. var array: [KMBatchOperateFile] = []
  3335. for file in files! {
  3336. let batchOperateFile = KMBatchOperateFile(filePath: file.filePath)
  3337. array.append(batchOperateFile)
  3338. }
  3339. batchWindowController.switchToOperateType(type, files: array)
  3340. batchWindowController.window?.makeKeyAndOrderFront("")
  3341. }
  3342. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  3343. if let itemID = toolbarItem.itemIdentifier {
  3344. if isMainToolItem(itemID) {
  3345. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  3346. self.browserWindowController?.browser.selectTabContents(at: 0, userGesture: true)
  3347. self.toolbarController.findItem(KMDocumentHomeToolbarItemIdentifier)?.isSelected = false
  3348. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  3349. self.changePDFViewGoToPreviousPageAction()
  3350. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  3351. self.changePDFViewGotoNextPageAction()
  3352. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3353. Swift.debugPrint("KMDocumentViewDisplayToolbarItemIdentifier ...")
  3354. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  3355. toolbarItem.isSelected = !toolbarItem.isSelected
  3356. self.toggleLeftPane()
  3357. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  3358. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3359. toolbarItem.isSelected = !toolbarItem.isSelected
  3360. self.toggleRightPane()
  3361. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  3362. self.listView.toolMode = .redactToolMode
  3363. self.enterRedact()
  3364. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  3365. showOCRWindow()
  3366. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  3367. Swift.debugPrint("KMDocumentDigitalSignToolbarItemIdentifier ...")
  3368. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  3369. }
  3370. } else {
  3371. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  3372. let windowC = KMToolbarCustomWindowController()
  3373. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  3374. self.km_beginSheet(windowC: windowC)
  3375. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  3376. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  3377. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  3378. self.trackEvent_print()
  3379. self.showPrintWindow()
  3380. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  3381. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  3382. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  3383. windowC.callBack = { [weak self] string in
  3384. // if (string.length > 0) {
  3385. // [blockSelf.pdfView addTextFieldWithSubType:KMSelfSignAnnotationFreeTextSubType_Profile string:string];
  3386. // }
  3387. self?.km_endSheet()
  3388. }
  3389. self.km_beginSheet(windowC: windowC)
  3390. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  3391. Swift.debugPrint("KMToolbarViewSettingIdentifier ...")
  3392. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  3393. self.listView.takeSnapshot(nil)
  3394. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  3395. Swift.debugPrint("KMToolbarTTSIdentifier ...")
  3396. self.showTTSWindow()
  3397. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  3398. self.showOCRWindow()
  3399. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  3400. Swift.debugPrint("KMAnnotationImageToolbarItemIdentifier ...")
  3401. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  3402. Swift.debugPrint("KMAnnotationTableToolbarItemIdentifier ...")
  3403. }
  3404. }
  3405. }
  3406. }
  3407. func showTTSWindow() {
  3408. var lastPDFView: CPDFView?
  3409. let ttsView = KMTTSWindowController.share
  3410. if (ttsView.window?.isVisible ?? false) {
  3411. lastPDFView = ttsView.pdfView
  3412. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  3413. lastPDFView = nil
  3414. ttsView.window?.orderOut(nil)
  3415. } else {
  3416. ttsView.pdfView = self.listView
  3417. ttsView.showWindow(nil)
  3418. }
  3419. } else {
  3420. ttsView.pdfView = self.listView
  3421. ttsView.showWindow(nil)
  3422. }
  3423. // weak var blockSelf = self
  3424. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  3425. if isCloseWindow {
  3426. // for item in blockSelf?.toolbar.items ?? [] {
  3427. // if item.itemIdentifier == KMToolbarTTSViewItemIdentifier {
  3428. // item.isSelected = false
  3429. // }
  3430. // }
  3431. }
  3432. }
  3433. if let currentSelection = self.listView.currentSelection {
  3434. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  3435. ttsView.startSpeakingPDFSelection(currentSelection)
  3436. }
  3437. }
  3438. if let lastPDFView = lastPDFView {
  3439. lastPDFView.setHighlightedSelections([])
  3440. ttsView.stopSpeaking()
  3441. }
  3442. }
  3443. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3444. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  3445. KMPrint("KMToolbarToolWatermarkItemIdentifier \(index)")
  3446. self.clickChildTool(type: .watermark, index: index)
  3447. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  3448. self.clickChildTool(type: .background, index: index)
  3449. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  3450. KMPrint("KMToolbarToolHeaderFooterItemIdentifier \(index)")
  3451. self.clickChildTool(type: .headerAndFooter, index: index)
  3452. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  3453. KMPrint("KMToolbarToolBatesItemIdentifier \(index)")
  3454. self.clickChildTool(type: .bates, index: index)
  3455. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  3456. KMPrint("KMToolbarComparisonItemIdentifier \(index)")
  3457. self.clickChildTool(type: .comparison, index: index)
  3458. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  3459. KMPrint("KMToolbarToolFormAlignIdentifier \(index)")
  3460. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  3461. KMPrint("KMToolbarConversionImageItemIdentifier \(index)")
  3462. convertToImg(index: index)
  3463. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  3464. extractImageAction(num: index)
  3465. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  3466. self.createPdf(index: index)
  3467. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  3468. if index == 2 { // 裁剪当前页面
  3469. self.cropCurrentPage()
  3470. } else if index == 3 { // Auto Crop – Separate
  3471. self.cropAllPage()
  3472. } else if index == 4 { // Auto Crop – Combined
  3473. self.cropAllPage()
  3474. } else if index == 5 { // Select Area
  3475. self.toolbarController.clickItem(KMToolbarSelectToolModeItemIdentifier)
  3476. }
  3477. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  3478. KMPrint("KMToolbarToolSecureItemIdentifier \(index)")
  3479. self.clickChildTool(type: .secure, index: index)
  3480. }
  3481. }
  3482. func convertToImg(index: Int) {
  3483. var convertT: KMConvertType = .JPEG
  3484. switch index {
  3485. case 7:
  3486. convertT = .JPEG
  3487. case 8:
  3488. convertT = .JPG
  3489. case 9:
  3490. convertT = .PNG
  3491. case 10:
  3492. convertT = .GIF
  3493. case 11:
  3494. convertT = .TIFF
  3495. case 12:
  3496. convertT = .TGA
  3497. case 13:
  3498. convertT = .BMP
  3499. default:
  3500. convertT = .JPEG
  3501. }
  3502. showAllConvertWindow(convertT: convertT)
  3503. }
  3504. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String) {
  3505. Swift.debugPrint("Search Result " + searchString)
  3506. }
  3507. }
  3508. // MARK: -
  3509. // MARK: - Mouse
  3510. extension KMMainViewController {
  3511. override func mouseDown(with event: NSEvent) {
  3512. super.mouseDown(with: event)
  3513. KMPrint("KMMainViewController mouseDown")
  3514. self.leftSideViewCancelSelect()
  3515. self.pageNumberDisplayView.isEdit = false
  3516. }
  3517. }
  3518. //MARK: LeftSideViewController
  3519. extension KMMainViewController {
  3520. func leftSideViewCancelSelect() {
  3521. // switch self.leftSideViewController.type.methodType {
  3522. // case .Thumbnail:
  3523. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  3524. // break
  3525. // case .Outline:
  3526. //// self.leftSideViewController.outlineViewController.cancelSelect()
  3527. // break
  3528. // case .BookMark:
  3529. //// self.leftSideViewController.bookViewController.cancelSelect()
  3530. // break
  3531. // case .Search:
  3532. //// self.leftSideViewController.searchViewController.cancelSelect()
  3533. // break
  3534. // case .Annotation:
  3535. //// self.leftSideViewController.annotationViewController.cancelSelect()
  3536. // break
  3537. // default:
  3538. if self.listView.isEditing() {
  3539. if self.listView.editingAreas() != nil &&
  3540. self.listView.editingAreas().count != 0 {
  3541. let areas = self.listView.editingAreas().first
  3542. if areas is CPDFEditTextArea {
  3543. self.listView.clearEditingSelectCharItem()
  3544. self.listView.updateEditing([])
  3545. KMPrint("取消选中")
  3546. }
  3547. }
  3548. }
  3549. KMPrint("其他")
  3550. // }
  3551. }
  3552. }
  3553. extension KMMainViewController: KMReadModelViewDelegate {
  3554. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3555. self.listView.goToFirstPage(nil)
  3556. }
  3557. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  3558. self.listView.goToPreviousPage(nil)
  3559. }
  3560. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3561. self.listView.goToNextPage(nil)
  3562. }
  3563. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3564. self.listView.goToLastPage(nil)
  3565. }
  3566. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  3567. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  3568. }
  3569. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  3570. var scale: Double = 1.0
  3571. switch type {
  3572. case .fitWidth:
  3573. self.listView.autoScales = !self.listView.autoScales
  3574. scale = self.listView.scaleFactor
  3575. break
  3576. case .actualSize:
  3577. if self.listView.scaleFactor != 1.0 {
  3578. self.listView.scaleFactor = 1.0
  3579. self.listView.autoScales = false
  3580. }
  3581. scale = self.listView.scaleFactor
  3582. break
  3583. case .autoSize:
  3584. self.listView.autoScales = true
  3585. self.listView.autoScales = false
  3586. scale = self.listView.scaleFactor
  3587. break
  3588. case ._10:
  3589. scale = 0.1
  3590. break
  3591. case ._25:
  3592. scale = 0.25
  3593. break
  3594. case ._50:
  3595. scale = 0.5
  3596. break
  3597. case ._100:
  3598. scale = 1.0
  3599. break
  3600. case ._150:
  3601. scale = 1.5
  3602. break
  3603. case ._200:
  3604. scale = 2.0
  3605. break
  3606. case ._400:
  3607. scale = 4.0
  3608. break
  3609. case ._800:
  3610. scale = 8.0
  3611. break
  3612. default:
  3613. break
  3614. }
  3615. self.listView.scaleFactor = scale
  3616. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3617. }
  3618. func cancelReadModel(view: KMReadModelView, sender: Any) {
  3619. if self.isReadMode {
  3620. self.closeReadModel()
  3621. }
  3622. }
  3623. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  3624. // if self.readModelViewWidthConstraint.constant != width {
  3625. self.readModelViewWidthConstraint.constant = width
  3626. // }
  3627. }
  3628. }
  3629. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  3630. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  3631. self.listView.go(toPageIndex: pageIndex, animated: true)
  3632. }
  3633. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  3634. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  3635. self.tipCurrentPageBoxWidthConstraint.constant = width
  3636. }
  3637. }
  3638. func commitEditingIfNeed() {
  3639. let isEdited = self.listView?.isEdited() ?? false
  3640. if isEdited || self.isPDFTextImageEdited {
  3641. self.listView.commitEditing()
  3642. }
  3643. }
  3644. }
  3645. // MARK: - Analytics (埋点)
  3646. extension KMMainViewController {
  3647. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  3648. if (type == .Annatiton) {
  3649. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Annotation", parameters: [
  3650. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3651. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3652. } else if (type == .editPDF) {
  3653. KMAnalytics.trackEvent(eventName: "Btn_Tbr_EditPDF", parameters: [
  3654. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3655. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3656. } else if (type == .Page) {
  3657. KMAnalytics.trackEvent(eventName: "Btn_Tbr_PageEdit", parameters: [
  3658. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3659. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3660. } else if (type == .Conversion) {
  3661. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Converter", parameters: [
  3662. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3663. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3664. } else if (type == .Tool) {
  3665. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Tools", parameters: [
  3666. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3667. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3668. }
  3669. }
  3670. func trackEvent_aiTranslate() -> Void {
  3671. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  3672. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3673. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3674. }
  3675. func trackEvent_print() -> Void {
  3676. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  3677. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3678. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3679. }
  3680. func trackEvent_share() -> Void {
  3681. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  3682. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3683. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3684. }
  3685. func trackEvent_upgrade() -> Void {
  3686. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  3687. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3688. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3689. }
  3690. func trackEvent(annotationType type: CAnnotationType) -> Void {
  3691. if (type == .highlight) {
  3692. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  3693. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3694. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3695. } else if (type == .underline) {
  3696. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  3697. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3698. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3699. } else if (type == .strikeOut) {
  3700. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  3701. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3702. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3703. } else if (type == .ink) {
  3704. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  3705. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3706. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3707. } else if (type == .freeText) {
  3708. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  3709. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3710. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3711. } else if (type == .anchored) {
  3712. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  3713. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3714. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3715. } else if (type == .square) {
  3716. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  3717. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3718. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3719. } else if (type == .link) {
  3720. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  3721. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3722. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3723. } else if (type == .stamp) {
  3724. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  3725. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3726. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3727. } else if (type == .signSignature) {
  3728. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  3729. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3730. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3731. } else if (type == .addText) {
  3732. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  3733. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3734. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3735. } else if (type == .addImage) {
  3736. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  3737. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3738. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3739. } else {
  3740. }
  3741. }
  3742. func trackEvent(toolMode mode: CToolMode) -> Void {
  3743. if (mode == .selectToolMode) {
  3744. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3745. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3746. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3747. } else if (mode == .moveToolMode) {
  3748. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3749. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3750. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3751. }
  3752. }
  3753. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3754. if (type == .word) {
  3755. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toWord", parameters: [
  3756. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3757. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3758. } else if (type == .excel) {
  3759. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toExcel", parameters: [
  3760. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3761. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3762. } else if (type == .ppt) {
  3763. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toPPT", parameters: [
  3764. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3765. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3766. } else if (type == .rtf) {
  3767. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toRTF", parameters: [
  3768. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3769. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3770. } else if (type == .csv) {
  3771. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toCSV", parameters: [
  3772. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3773. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3774. } else if (type == .html) {
  3775. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toHTML", parameters: [
  3776. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3777. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3778. } else if (type == .conversion_text) {
  3779. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toText", parameters: [
  3780. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3781. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3782. } else if (type == .conversion_image) {
  3783. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toImage", parameters: [
  3784. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3785. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3786. } else if (type == .compress) {
  3787. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Compress", parameters: [
  3788. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3789. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3790. } else if (type == .merge) {
  3791. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Merge", parameters: [
  3792. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3793. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3794. } else if (type == .secure) {
  3795. } else if (type == .crop) {
  3796. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Crop", parameters: [
  3797. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3798. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3799. }
  3800. }
  3801. func trackEvent_setPassword() -> Void {
  3802. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3803. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3804. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3805. }
  3806. func trackEvent_removePassword() -> Void {
  3807. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3808. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3809. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3810. }
  3811. }
  3812. extension KMMainViewController {
  3813. //文件对比
  3814. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  3815. let compareContentView = KMCompareContentView()
  3816. compareContentView.oldDocument = oldDocument
  3817. compareContentView.document = document
  3818. compareContentView.compareResults = results
  3819. compareContentView.saveHandle = { [unowned self] view in
  3820. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3821. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  3822. self.currentWindowController = saveController
  3823. saveController.cancelHandle = { [unowned self] controller in
  3824. self.view.window!.endSheet(controller.window!)
  3825. self.currentWindowController = nil
  3826. }
  3827. saveController.saveHandle = { [unowned self] controller, saveType in
  3828. let folderPath = controller.fileSaveFolderPath
  3829. if folderPath != nil {
  3830. if !FileManager.default.fileExists(atPath: folderPath) {
  3831. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  3832. }
  3833. var savePath: String
  3834. switch saveType {
  3835. case 0:
  3836. let filePath = oldDocument.documentURL.path
  3837. let fileName = filePath.deletingPathExtension.lastPathComponent
  3838. savePath = "\(folderPath)/\(fileName.deletingPathExtension)_compare\(filePath.extension)"
  3839. savePath = self.getValidFilePath(savePath)
  3840. oldDocument.write(to: URL(fileURLWithPath: savePath))
  3841. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3842. case 1:
  3843. let filePath = document.documentURL.path
  3844. let fileName = filePath.deletingPathExtension.lastPathComponent
  3845. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3846. savePath = self.getValidFilePath(savePath)
  3847. document.write(to: URL(fileURLWithPath: savePath))
  3848. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3849. case 2:
  3850. let filePath = oldDocument.documentURL.path
  3851. let fileName = filePath.deletingPathExtension.lastPathComponent
  3852. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  3853. savePath = self.getValidFilePath(savePath)
  3854. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  3855. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3856. default:
  3857. break
  3858. }
  3859. }
  3860. self.view.window!.endSheet(controller.window!)
  3861. self.currentWindowController = nil
  3862. }
  3863. NSWindow.currentWindow().beginSheet(saveController.window!)
  3864. }
  3865. }
  3866. compareContentView.closeHandle = { [unowned self] view in
  3867. // self.view.window!.endSheet(controller.window!)
  3868. view.removeFromSuperview()
  3869. }
  3870. self.PDFContendView.addSubview(compareContentView)
  3871. compareContentView.frame = self.PDFContendView.bounds
  3872. compareContentView.autoresizingMask = [.width,.height]
  3873. }
  3874. func getValidFilePath(_ oldPath: String) -> String {
  3875. let fileManager = FileManager.default
  3876. do {
  3877. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  3878. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  3879. return oldPath
  3880. }
  3881. var i = 1
  3882. var newPath = oldPath
  3883. while fileManager.fileExists(atPath: newPath) {
  3884. if fileType == FileAttributeType.typeDirectory.rawValue {
  3885. newPath = oldPath + "(\(i))"
  3886. } else {
  3887. let fileExtension = (oldPath as NSString).pathExtension
  3888. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3889. }
  3890. i += 1
  3891. }
  3892. return newPath
  3893. } catch {
  3894. print("Error getting file attributes: \(error)")
  3895. return oldPath
  3896. }
  3897. }
  3898. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  3899. let coveringView = KMCompareCoveringView()
  3900. coveringView.pdfDocument = pdfDocument
  3901. coveringView.closeHandle = { [unowned self] view in
  3902. view.removeFromSuperview()
  3903. }
  3904. coveringView.saveHandle = { [unowned self] view in
  3905. let savePanel = NSSavePanel()
  3906. savePanel.nameFieldStringValue = "untitled"
  3907. savePanel.allowedFileTypes = ["pdf"]
  3908. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  3909. if result == .OK {
  3910. pdfDocument.write(to: savePanel.url!)
  3911. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3912. }
  3913. }
  3914. }
  3915. self.PDFContendView.addSubview(coveringView)
  3916. coveringView.frame = self.PDFContendView.bounds
  3917. coveringView.autoresizingMask = [.width,.height]
  3918. }
  3919. }