KMMainViewController+Action.swift 245 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. let isEditing = self.listView.isEditing() ?? false
  11. if isEditing {
  12. if searchString.isEmpty {
  13. self.listView.setHighlightedSelection(nil, animated: false)
  14. self.leftSideViewController.searchResults = []
  15. if display {
  16. if self.leftSideViewController.findPaneState == .singular {
  17. self.leftSideViewController.displayFindViewAnimating(true)
  18. } else {
  19. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  20. }
  21. }
  22. return
  23. }
  24. let isWholeWord = self.leftSideViewController.mwcFlags.wholeWordSearch == 1
  25. var opt = CPDFSearchOptions()
  26. if isCase == false {
  27. opt.insert(.caseSensitive)
  28. }
  29. if isWholeWord {
  30. opt.insert(.matchWholeWord)
  31. }
  32. let datas = self.srHanddler.pdfView?.document.findEditAllPageString(searchString, with: opt) ?? []
  33. if let sel = datas.first?.first {
  34. self.srHanddler.showSelection(sel)
  35. }
  36. self.searchResults.removeAll()
  37. var _selections: [CPDFSelection] = []
  38. for selections in datas {
  39. for selection in selections {
  40. let mode : KMSearchMode = KMSearchMode()
  41. mode.selection = selection
  42. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  43. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  44. self.searchResults.insert(mode, at: self.searchResults.count)
  45. _selections.append(selection)
  46. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  47. }
  48. }
  49. if needShowAll {
  50. self.listView.setHighlightedSelections(_selections)
  51. }
  52. if _selections.isEmpty {
  53. self.listView.setHighlightedSelection(nil, animated: false)
  54. }
  55. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  56. self.leftSideViewController.searchResults = self.searchResults
  57. if display {
  58. if self.leftSideViewController.findPaneState == .singular {
  59. self.leftSideViewController.displayFindViewAnimating(true)
  60. } else {
  61. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  62. }
  63. }
  64. return
  65. }
  66. let document = self.listView.document
  67. if let data = document?.isFinding, data {
  68. document?.cancelFindString()
  69. }
  70. if searchString == "" {
  71. self.searchResults = []
  72. self.leftSideViewController.searchResults = self.searchResults
  73. self.listView.setHighlightedSelections([])
  74. self.listView.setHighlightedSelection(nil, animated: false)
  75. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  76. } else {
  77. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  78. var findArray : [[CPDFSelection]]
  79. if isCase {
  80. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  81. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  82. } else {
  83. findArray = self.listView.document.findString(searchString) ?? []
  84. }
  85. } else {
  86. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  87. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  88. } else {
  89. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  90. }
  91. }
  92. self.searchResults.removeAll()
  93. var _selections: [CPDFSelection] = []
  94. for selections in findArray {
  95. for selection in selections {
  96. let mode : KMSearchMode = KMSearchMode()
  97. mode.selection = selection
  98. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  99. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  100. self.searchResults.insert(mode, at: self.searchResults.count)
  101. _selections.append(selection)
  102. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  103. }
  104. }
  105. if needShowAll {
  106. self.listView.setHighlightedSelections(_selections)
  107. }
  108. if _selections.isEmpty {
  109. self.listView.setHighlightedSelection(nil, animated: false)
  110. }
  111. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  112. self.leftSideViewController.searchResults = self.searchResults
  113. }
  114. if display {
  115. if self.leftSideViewController.findPaneState == .singular {
  116. self.leftSideViewController.displayFindViewAnimating(true)
  117. } else {
  118. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  119. }
  120. }
  121. }
  122. func removeSignatures(signatures:[CPDFSignature]) {
  123. for signature in signatures {
  124. self.listView.document.removeSignature(signature)
  125. }
  126. for i in 0..<self.listView.document.pageCount {
  127. let page : CPDFPage = self.listView.document.page(at: i)
  128. let annotations : [CPDFAnnotation] = page.annotations
  129. for j in 0..<annotations.count {
  130. let annotation = annotations[j]
  131. if annotation is CPDFSignatureWidgetAnnotation {
  132. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  133. }
  134. }
  135. }
  136. self.listView.setNeedsDisplayForVisiblePages()
  137. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  138. var mSignatures : [CPDFSignature] = []
  139. for sign in tSignatures {
  140. if sign.signers.count > 0 {
  141. mSignatures.append(sign)
  142. }
  143. }
  144. }
  145. //MARK: menu菜单
  146. func fontColorMenuItem()->NSMenuItem {
  147. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  148. return fontColorItem;
  149. }
  150. func fontSizeMenuItem()->NSMenuItem {
  151. let currentFontSize = self.listView.editingTextFontSize()
  152. let fontSizes = self.fontSizes()
  153. let submenu = NSMenu(title: "")
  154. for i in 0 ... fontSizes.count - 1 {
  155. let fontSize : String = fontSizes.object(at: i) as! String
  156. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  157. item.target = self
  158. item.tag = i
  159. submenu.addItem(item)
  160. if (Int(currentFontSize) == Int(fontSize)) {
  161. item.state = .on
  162. }
  163. }
  164. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  165. fontSizeItem.submenu = submenu
  166. return fontSizeItem;
  167. }
  168. func corpImageMenuItem()->NSMenuItem {
  169. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  170. return corpImageItem
  171. }
  172. func cancelCorpImageMenuItem()->NSMenuItem {
  173. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  174. return cancelCorpImageItem
  175. }
  176. func restoreCorpImageMenuItem()->NSMenuItem {
  177. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  178. return cancelCorpImageItem
  179. }
  180. func cutImageArea()->NSMenuItem {
  181. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  182. return deleteItem
  183. }
  184. func editAddBlanMenu(menu:NSMenu){
  185. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  186. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  187. }
  188. func addText() -> NSMenuItem {
  189. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  190. return addTextItem
  191. }
  192. func addImage() -> NSMenuItem {
  193. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  194. return addImageItem
  195. }
  196. func replaceImageArea()->NSMenuItem {
  197. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  198. return replaceItem
  199. }
  200. func exportImageArea()->NSMenuItem {
  201. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  202. let menu = NSMenu()
  203. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  204. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(menuItemEditingClick_ExportImage), target: self, tag:1, at: 1)
  205. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 2)
  206. exportItem.submenu = menu
  207. return exportItem
  208. }
  209. func exportImageStampItem()->NSMenuItem {
  210. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  211. let menu = NSMenu()
  212. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  213. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  214. exportItem.submenu = menu
  215. return exportItem
  216. }
  217. func exportMenu() -> NSMenu {
  218. let menu = NSMenu()
  219. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  220. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  221. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  222. return menu
  223. }
  224. func cropMenu() -> NSMenu {
  225. let menu = NSMenu()
  226. _ = menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  227. _ = menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  228. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  229. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(smartAutoCropAll), target: self, at: 2)
  230. return menu
  231. }
  232. func zoomSelectionMenuItem() -> NSMenuItem {
  233. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  234. return item
  235. }
  236. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  237. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  238. return item
  239. }
  240. func enterAnnotationStype() -> NSMenuItem {
  241. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  242. let stypeMenu = NSMenu()
  243. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  244. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  245. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  246. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  247. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  248. stypeMenu.addItem(NSMenuItem.separator())
  249. }
  250. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  251. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  252. stypeMenu.addItem(NSMenuItem.separator())
  253. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  254. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  255. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  256. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  257. if viewManager.isPDFReadMode {
  258. } else {
  259. stypeMenu.addItem(NSMenuItem.separator())
  260. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  261. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  262. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  263. }
  264. stypItem.submenu = stypeMenu
  265. if self.listView.annotationType == .ink {
  266. stypeMenu.item(withTitle: NSLocalizedString("Freehand", comment: ""))?.state = .on
  267. } else if self.listView.annotationType == .freeText {
  268. stypeMenu.item(withTitle: NSLocalizedString("Text Note", comment: ""))?.state = .on
  269. } else if self.listView.annotationType == .anchored {
  270. stypeMenu.item(withTitle: NSLocalizedString("Anchored Note", comment: ""))?.state = .on
  271. } else if self.listView.annotationType == .square {
  272. stypeMenu.item(withTitle: NSLocalizedString("Rectangle", comment: ""))?.state = .on
  273. } else if self.listView.annotationType == .circle {
  274. stypeMenu.item(withTitle: NSLocalizedString("Circle", comment: ""))?.state = .on
  275. } else if self.listView.annotationType == .arrow {
  276. stypeMenu.item(withTitle: NSLocalizedString("Arrow", comment: ""))?.state = .on
  277. } else if self.listView.annotationType == .line {
  278. stypeMenu.item(withTitle: NSLocalizedString("Line", comment: ""))?.state = .on
  279. } else if self.listView.annotationType == .link {
  280. stypeMenu.item(at: 7)?.state = .on
  281. } else if self.listView.annotationType == .stamp {
  282. stypeMenu.item(withTitle: NSLocalizedString("Stamp", comment: ""))?.state = .on
  283. } else if self.listView.annotationType == .signSignature {
  284. stypeMenu.item(withTitle: NSLocalizedString("Signature", comment: ""))?.state = .on
  285. }
  286. return stypItem
  287. }
  288. func setAnnotationToolStype() -> NSMenuItem {
  289. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  290. let stypeMenu = NSMenu()
  291. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.textToolMode.rawValue)
  292. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  293. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  294. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  295. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  296. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  297. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  298. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  299. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.squiggly.rawValue)
  300. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  301. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  302. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  303. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  304. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  305. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  306. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  307. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  308. stypItem.submenu = stypeMenu
  309. return stypItem
  310. }
  311. func addReadModelStype() -> NSMenuItem {
  312. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openPDFReadMode), target: self)
  313. if viewManager.isPDFReadMode {
  314. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(exitPDFReadMode), target: self)
  315. }
  316. return stypItem
  317. }
  318. func addOutlineStype() -> NSMenuItem {
  319. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  320. return stypItem
  321. }
  322. func setTTSStype() -> NSMenuItem {
  323. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  324. return stypItem
  325. }
  326. func setShareStype() -> NSMenuItem {
  327. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  328. var string = ""
  329. if listView.activeAnnotation != nil {
  330. string = self.listView.activeAnnotation?.contents ?? ""
  331. }
  332. if string.count < 1{
  333. string = self.listView.currentSelection?.string() ?? ""
  334. }
  335. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  336. return stypItem
  337. }
  338. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  339. var number = 0
  340. var indexN = 0
  341. guard str.count > 0 else {return (0, 0)}
  342. for i in 0...str.count - 1 {
  343. let c: unichar = (str as NSString).character(at: i)
  344. if (c >= 0x4E00) {
  345. number += 2
  346. }else {
  347. number += 1
  348. }
  349. if number > 56{
  350. indexN = i
  351. number = 100
  352. break
  353. }
  354. }
  355. return (number, indexN)
  356. }
  357. func setLookUpStype() -> NSMenuItem {
  358. guard let str = listView.currentSelection?.string() else {
  359. return NSMenuItem.separator()
  360. }//String(format: "Look Up %@", listView.currentSelection?.string() ?? "")
  361. let dic = numberOfChars(str)
  362. var newStr = str
  363. if dic.num == 100{
  364. newStr = str.prefix(dic.indexN) + "..."
  365. }
  366. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  367. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  368. return stypItem
  369. }
  370. func setSearchBaiduStype() -> NSMenuItem {
  371. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  372. return stypItem
  373. }
  374. func setCutStype() -> NSMenuItem {
  375. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  376. return stypItem
  377. }
  378. func setDeleteStype() -> NSMenuItem {
  379. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  380. return stypItem
  381. }
  382. func setColorsStype() -> NSMenuItem {
  383. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  384. return stypItem
  385. }
  386. func setLinesStype() -> NSMenuItem {
  387. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  388. return stypItem
  389. }
  390. func setEditNoteStype() -> NSMenuItem {
  391. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  392. return stypItem
  393. }
  394. func setRotateStype() -> NSMenuItem {
  395. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  396. let stypeMenu = NSMenu()
  397. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  398. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  399. stypItem.submenu = stypeMenu
  400. return stypItem
  401. }
  402. func setNextPageStype() -> NSMenuItem {
  403. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  404. stypItem.isEnabled = false
  405. if listView.canGoToNextPage() {
  406. stypItem.isEnabled = true
  407. }
  408. return stypItem
  409. }
  410. func setPreviousPageStype() -> NSMenuItem {
  411. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  412. stypItem.isEnabled = false
  413. if listView.canGoToPreviousPage() {
  414. stypItem.isEnabled = true
  415. }
  416. return stypItem
  417. }
  418. func setTranslateStype() -> NSMenuItem {
  419. let str = listView.currentSelection?.string() ?? ""//String(format: "Translate %@", listView.currentSelection?.string() ?? "")
  420. let dic = numberOfChars(str)
  421. var newStr = str
  422. if dic.num == 100{
  423. newStr = str.prefix(dic.indexN) + "..."
  424. }
  425. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  426. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  427. return stypItem
  428. }
  429. func setAutoScrollStype() -> NSMenuItem {
  430. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  431. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  432. return stypItem
  433. }
  434. func setSnapshotStype() -> NSMenuItem {
  435. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  436. let stypeMenu = NSMenu()
  437. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  438. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  439. stypItem.submenu = stypeMenu
  440. return stypItem
  441. }
  442. func setServicesStype() -> NSMenuItem {
  443. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  444. let stypeMenu = NSMenu()
  445. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  446. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  447. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  448. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  449. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  450. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  451. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  452. stypItem.submenu = stypeMenu
  453. return stypItem
  454. }
  455. func setCropStype() -> NSMenuItem {
  456. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  457. let stypeMenu = NSMenu()
  458. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  459. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  460. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  461. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  462. if NSIsEmptyRect(listView.selectionRect){
  463. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  464. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  465. }
  466. stypItem.submenu = stypeMenu
  467. return stypItem
  468. }
  469. func setAITranslateStype() -> NSMenuItem {
  470. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  471. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  472. return stypItem
  473. }
  474. func setAIProofreadStype() -> NSMenuItem {
  475. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  476. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  477. return stypItem
  478. }
  479. func setAIRewriteStype() -> NSMenuItem {
  480. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  481. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  482. return stypItem
  483. }
  484. func addHighlightLinksStype() -> NSMenuItem {
  485. let highlightLink = KMPreferenceManager.shared.highlightLinks
  486. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  487. if highlightLink {
  488. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  489. }
  490. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  491. return highlightLinksItem
  492. }
  493. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  494. if item == nil {
  495. return
  496. }
  497. let menu = NSMenu()
  498. item?.submenu = menu
  499. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  500. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  501. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  502. let wavyLine = NSMenuItem(title: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  503. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  504. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  505. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  506. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  507. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  508. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  509. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  510. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  511. if listView.currentSelection.selectionType() != .image {
  512. menu.insertItem(height, at: menu.items.count)
  513. menu.insertItem(underline, at: menu.items.count)
  514. menu.insertItem(strickout, at: menu.items.count)
  515. menu.insertItem(wavyLine, at: menu.items.count)
  516. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  517. }
  518. if viewManager.isPDFReadMode {
  519. } else {
  520. if listView.currentSelection.selectionType() != .image &&
  521. listView.currentSelection.selectionType() != .text {
  522. menu.insertItem(text, at: menu.items.count)
  523. menu.insertItem(note, at: menu.items.count)
  524. }
  525. }
  526. if viewManager.isPDFReadMode {
  527. } else {
  528. if listView.currentSelection.selectionType() != .image {
  529. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  530. menu.insertItem(rectangle, at: menu.items.count)
  531. menu.insertItem(oval, at: menu.items.count)
  532. }
  533. }
  534. if viewManager.isPDFReadMode {
  535. } else {
  536. if listView.currentSelection.selectionType() != .image &&
  537. listView.currentSelection.selectionType() != .text {
  538. menu.insertItem(line, at: menu.items.count)
  539. }
  540. }
  541. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  542. if viewManager.isPDFReadMode {
  543. } else {
  544. menu.insertItem(link, at: menu.items.count)
  545. }
  546. if viewManager.isPDFReadMode {
  547. } else {
  548. if listView.currentSelection.selectionType() != .image {
  549. menu.insertItem(outline, at: menu.items.count)
  550. }
  551. }
  552. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  553. if viewManager.isPDFReadMode {
  554. } else {
  555. if (listView.currentSelection.selectionType() != .image) {
  556. }
  557. }
  558. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  559. }
  560. func addBookmarkMenu() -> NSMenuItem {
  561. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  562. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  563. return bookMarkItem
  564. } else {
  565. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  566. return bookMarkItem
  567. }
  568. }
  569. func findStringMenu() -> NSMenuItem {
  570. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  571. menuItem.keyEquivalent = "f"
  572. return menuItem
  573. }
  574. func printingMenu() -> NSMenuItem {
  575. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  576. return menuItem
  577. }
  578. func fontSizes()->NSArray {
  579. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  580. }
  581. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  582. if interactionMode == .presentation {
  583. listView.goToPreviousPage(nil)
  584. return true
  585. }
  586. return false
  587. }
  588. func useNativeFullScreen() -> Bool {
  589. var isFull = false
  590. let sel = NSSelectorFromString("toggleFullscreen:")
  591. if NSWindow.instancesRespond(to: sel) && UserDefaults.standard.bool(forKey: "SKUseLegacyFullScreenKey"){
  592. isFull = true
  593. }
  594. return isFull
  595. }
  596. func forceSubwindowsOnTop(_ flag: Bool) {
  597. }
  598. //MARK: menuItem Action
  599. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  600. let color = listView.editingSelectionFontColor()
  601. let panel = NSColorPanel.shared
  602. panel.setTarget(self)
  603. panel.setAction(#selector(fontColorChangeAction))
  604. panel.orderFront(nil)
  605. panel.showsAlpha = false
  606. panel.color = color ?? NSColor.black
  607. }
  608. @objc func fontColorChangeAction(sender: NSColorPanel) {
  609. self.listView.setEditingSelectionFontColor(sender.color)
  610. }
  611. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  612. let fontSize = self.fontSizes().object(at: sender.tag)
  613. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  614. }
  615. @objc func addImageText(sender: NSMenuItem) {
  616. let event = NSApp.currentEvent
  617. let clickLocation = event?.locationInWindow
  618. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  619. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  620. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  621. point = point2
  622. if sender.tag == 0 {
  623. KMPrint("添加文字")
  624. } else if sender.tag == 1 {
  625. } else if sender.tag == 2 {
  626. KMPrint("粘贴")
  627. }
  628. }
  629. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  630. if self.rightSideViewController.eidtPDFImageProperty != nil {
  631. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  632. } else {
  633. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  634. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  635. }
  636. }
  637. }
  638. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  639. if self.rightSideViewController.eidtPDFImageProperty != nil {
  640. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  641. } else {
  642. self.listView.exitCrop(with: self.listView.selectImageAreas)
  643. self.listView.cropAreas = nil
  644. self.listView.isEditImage = false
  645. }
  646. }
  647. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  648. if self.rightSideViewController.eidtPDFImageProperty != nil {
  649. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  650. } else {
  651. self.listView.resetCrop(with: self.listView.selectImageAreas)
  652. }
  653. }
  654. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  655. self.editPDFHanddler.cropAction()
  656. }
  657. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  658. if self.listView.selectImageAreas == nil {
  659. return
  660. }
  661. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  662. let panel = NSOpenPanel()
  663. panel.allowsMultipleSelection = false
  664. panel.allowedFileTypes = ["png","jpg"]
  665. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  666. if response == .OK {
  667. let openPath = panel.url?.path
  668. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  669. if s {
  670. }
  671. }
  672. }
  673. }
  674. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  675. if self.listView.selectImageAreas == nil {
  676. return
  677. }
  678. let panel = NSSavePanel()
  679. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  680. panel.isExtensionHidden = true
  681. let response = panel.runModal()
  682. if response == .OK {
  683. let url = panel.url
  684. if FileManager.default.fileExists(atPath: url!.path) {
  685. try?FileManager.default.removeItem(atPath: url!.path)
  686. }
  687. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  688. if result {
  689. NSWorkspace.shared.activateFileViewerSelecting([url!])
  690. }
  691. }
  692. }
  693. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  694. }
  695. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  696. }
  697. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  698. }
  699. @objc func OpenItemAction(sender: NSMenuItem) {
  700. }
  701. @objc func cropAllPageItem(sender: NSMenuItem) {
  702. self.cropAll(nil)
  703. }
  704. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  705. self.crop(nil)
  706. }
  707. @objc func autoCropAllItem(sender: NSMenuItem) {
  708. self.autoCropAll(nil)
  709. }
  710. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  711. self.smartAutoCropAll(nil)
  712. }
  713. @objc func customCropModel(sender: NSMenuItem) {
  714. let pdfDoc: CPDFDocument = self.listView.document
  715. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  716. let alert = NSAlert()
  717. alert.alertStyle = .critical
  718. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  719. alert.runModal()
  720. return
  721. }
  722. let window = NSWindow.currentWindow()
  723. let currentPage = pdfDoc.index(for: self.listView.currentPage())
  724. let cropVC = KMPDFCropWindowController(document: pdfDoc, pwd: "", currentPage: Int(currentPage), cropSize: NSMakeRect(100, 100, 50, 80), selectPageString: "\(currentPage)")
  725. window.km_beginSheet(windowC: cropVC)
  726. cropVC.cropWindowCloseBlock = { [weak self] doc in
  727. window.km_quick_endSheet()
  728. let isSuccessful = doc.write(to: self?.listView.document?.documentURL)
  729. if isSuccessful {
  730. if let documen = CPDFDocument(url: self?.document?.documentURL) {
  731. if documen.isLocked {
  732. documen.unlock(withPassword: pdfDoc.password)
  733. }
  734. self?.setDocument = documen
  735. }
  736. }
  737. }
  738. }
  739. @objc func rotateRightAction(sender: NSMenuItem) {
  740. }
  741. @objc func rotateLeftAction(sender: NSMenuItem) {
  742. }
  743. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  744. self.listView.toolMode = .noteToolMode
  745. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  746. var model : KMToolbarViewType = .None
  747. switch sender.tag {
  748. case 0:
  749. identifier = KMDocumentAnnotationToolbarItemIdentifier
  750. model = .Annatiton
  751. case 1:
  752. identifier = KMToolbarMoveToolModeItemIdentifier
  753. model = .Move
  754. case 2:
  755. identifier = KMToolbarMagnifyToolModeItemIdentifier
  756. model = .Magnify
  757. case 3:
  758. identifier = KMToolbarSelectToolModeItemIdentifier
  759. model = .Select
  760. case 4:
  761. identifier = KMToolbarZoomToSelectionItemIdentifier
  762. model = .SelectZoom
  763. default:
  764. break
  765. }
  766. }
  767. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  768. var itemId: String?
  769. if sender.tag == CAnnotationType.highlight.rawValue {
  770. itemId = KMToolbarHighlightAnnotationItemIdentifier
  771. } else if sender.tag == CAnnotationType.underline.rawValue {
  772. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  773. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  774. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  775. } else if sender.tag == CAnnotationType.squiggly.rawValue {
  776. itemId = KMToolbarSquigglyAnnotationItemIdentifier
  777. } else if sender.tag == CAnnotationType.ink.rawValue {
  778. itemId = KMToolbarInkAnnotationItemIdentifier
  779. } else if sender.tag == CAnnotationType.freeText.rawValue {
  780. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  781. } else if sender.tag == CAnnotationType.anchored.rawValue {
  782. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  783. } else if sender.tag == CAnnotationType.square.rawValue {
  784. itemId = KMToolbarSquareAnnotationItemIdentifier
  785. } else if sender.tag == CAnnotationType.circle.rawValue {
  786. itemId = KMToolbarCircleAnnotationItemIdentifier
  787. } else if sender.tag == CAnnotationType.arrow.rawValue {
  788. itemId = KMToolbarArrowAnnotationItemIdentifier
  789. } else if sender.tag == CAnnotationType.line.rawValue {
  790. itemId = KMToolbarLineAnnotationItemIdentifier
  791. } else if sender.tag == CAnnotationType.link.rawValue {
  792. itemId = KMToolbarLinkAnnotationItemIdentifier
  793. }
  794. }
  795. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  796. var annotationType : CAnnotationType = .unkown
  797. switch sender.tag {
  798. case 0:
  799. annotationType = .highlight
  800. case 1:
  801. annotationType = .underline
  802. case 2:
  803. if sender.title == NSLocalizedString("Squiggly", comment: "") {
  804. annotationType = .squiggly
  805. } else {
  806. annotationType = .strikeOut
  807. }
  808. case 3:
  809. annotationType = .freeText
  810. case 4:
  811. annotationType = .anchored
  812. case 5:
  813. annotationType = .square
  814. case 6:
  815. annotationType = .circle
  816. case 7:
  817. annotationType = .line
  818. case 8:
  819. annotationType = .link
  820. case 9:
  821. if self.model.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  822. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  823. }
  824. return
  825. case 10:
  826. annotationType = .unkown
  827. default:
  828. break
  829. }
  830. if (annotationType != .link) {
  831. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  832. self.listView.currentSelection = nil;
  833. return
  834. }
  835. // link
  836. let selection = self.listView.currentSelection
  837. DispatchQueue.main.async {
  838. Task { @MainActor in
  839. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  840. self.listView.currentSelection = nil;
  841. if (annotation != nil) {
  842. self.listView.updateActiveAnnotations([annotation!])
  843. }
  844. }
  845. }
  846. }
  847. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  848. Task { @MainActor in
  849. let idx = sender.tag
  850. if idx == 10 {
  851. if IAPProductsManager.default().isAvailableAllFunction() == false {
  852. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  853. return
  854. }
  855. }
  856. var point = mouseRightMenuEvent?.locationInWindow
  857. if (point == nil) {
  858. point = NSZeroPoint
  859. }
  860. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  861. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  862. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  863. var annotation: CPDFAnnotation?
  864. if viewManager.isPDFReadMode {
  865. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  866. self.listView.toolMode = .noteToolMode
  867. }
  868. switch sender.tag {
  869. case 0:
  870. self.listView.annotationType = CAnnotationType.ink
  871. case 1:
  872. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  873. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  874. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  875. if ((annotation) != nil) {
  876. self.listView.updateActiveAnnotations([annotation!])
  877. self.listView.edit(annotation)
  878. }
  879. case 2:
  880. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  881. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  882. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  883. self.listView.edit(annotation)
  884. case 3:
  885. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  886. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  887. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  888. case 4:
  889. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  890. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  891. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  892. case 5:
  893. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  894. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  895. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  896. case 6:
  897. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  898. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  899. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  900. case 7:
  901. self.listView.annotationType = CAnnotationType.link
  902. self.openRightPane()
  903. case 8:
  904. self.listView.annotationType = CAnnotationType.stamp
  905. self.openRightPane()
  906. case 9:
  907. self.listView.annotationType = CAnnotationType.signSignature
  908. self.openRightPane()
  909. default:
  910. break
  911. }
  912. self.rightSideViewController.isHidden = true
  913. self.rightSideViewController.subViewType = .AnnotationProperts
  914. } else {
  915. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  916. self.listView.toolMode = .noteToolMode
  917. }
  918. switch sender.tag {
  919. case 0:
  920. self.listView.toolMode = .noteToolMode
  921. self.listView.annotationType = CAnnotationType.ink
  922. case 1:
  923. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  924. if (pagePoint.x - defaultSize.width > 0){
  925. pagePoint.x -= defaultSize.width;
  926. }else{
  927. pagePoint.x = 0;
  928. }
  929. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  930. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  931. if ((annotation) != nil) {
  932. self.listView.edit(annotation)
  933. }
  934. case 2:
  935. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  936. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  937. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  938. self.listView.edit(annotation)
  939. case 3:
  940. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  941. if (pagePoint.x - defaultSize.width > 0){
  942. pagePoint.x -= defaultSize.width;
  943. }else{
  944. pagePoint.x = 0;
  945. }
  946. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  947. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  948. case 4:
  949. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  950. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  951. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  952. case 5:
  953. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  954. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  955. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  956. case 6:
  957. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  958. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  959. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  960. case 7:
  961. self.listView.annotationType = CAnnotationType.link
  962. self.openRightPane()
  963. case 8:
  964. self.listView.annotationType = CAnnotationType.stamp
  965. self.openRightPane()
  966. case 9:
  967. self.listView.annotationType = CAnnotationType.signSignature
  968. self.openRightPane()
  969. case 10:
  970. self.addImgAnnotationToView(center: pagePoint)
  971. default:
  972. break
  973. }
  974. self.rightSideViewController.isHidden = false
  975. self.rightSideViewController.subViewType = .AnnotationProperts
  976. if annotation != nil{
  977. self.listView.activeAnnotations.removeAllObjects()
  978. var newAnnonations : [CPDFAnnotation] = []
  979. newAnnonations.append(annotation!)
  980. self.listView.updateActiveAnnotations(newAnnonations)
  981. }
  982. }
  983. }
  984. }
  985. func addImgAnnotationToView(center: NSPoint) {
  986. let accessoryCtr = KMImageAccessoryController()
  987. let openPanel = NSOpenPanel()
  988. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  989. openPanel.allowsMultipleSelection = false
  990. openPanel.accessoryView = accessoryCtr.view
  991. openPanel.isAccessoryViewDisclosed = true
  992. openPanel.beginSheetModal(for: self.view.window!) { result in
  993. if result == .OK {
  994. let fileURL = openPanel.urls.first
  995. let filePath = fileURL!.path
  996. if filePath.pathExtension == "pdf" {
  997. let pdf = CPDFDocument(url: fileURL)
  998. if pdf!.isEncrypted {
  999. NSSound.beep()
  1000. return
  1001. }
  1002. }
  1003. let img = NSImage(contentsOfFile: filePath)
  1004. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  1005. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  1006. }
  1007. }
  1008. }
  1009. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  1010. if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  1011. let index = self.listView.currentPageIndex
  1012. self.listView.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  1013. self.listView.setNeedsDisplayForVisiblePages()
  1014. } else {
  1015. self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1016. self.listView.setNeedsDisplayForVisiblePages()
  1017. }
  1018. self.setDocumentEditedState(window: self.view.window)
  1019. if viewManager.isPDFReadMode {
  1020. } else {
  1021. self.leftSideViewController.showBookmarkTab()
  1022. }
  1023. }
  1024. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  1025. self.leftSideViewController.refreshMethodType(methodType: .Search)
  1026. }
  1027. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  1028. let rect = listView.currentSelectionRect()
  1029. let page = listView.currentPage()
  1030. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  1031. copyPage.setBounds(rect, for: .cropBox)
  1032. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  1033. // 执行右键操作后,需要取消框选区域
  1034. if self.listView.toolMode == .selectToolMode {
  1035. objc_sync_enter(self)
  1036. self.listView.selectionRect = NSZeroRect
  1037. self.listView.selectionPageIndex = UInt(NSNotFound)
  1038. objc_sync_exit(self)
  1039. }
  1040. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1041. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1042. if (result == .cancel) {
  1043. return
  1044. }
  1045. // 解除权限
  1046. self?.model.isSaveKeyChain = false
  1047. self?.listView.document.unlock(withPassword: password)
  1048. // 隐藏提示
  1049. self?.hiddenSecureLimitTip()
  1050. // 去打印
  1051. KMPrintWindowController.printImage(image: image)
  1052. }
  1053. return
  1054. }
  1055. KMPrintWindowController.printImage(image: image)
  1056. }
  1057. // MARK: - Measure
  1058. @objc func menuItemActionMeasureProperty(sender: NSMenuItem) {
  1059. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1060. return
  1061. }
  1062. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  1063. distanceMeasureInfoWindowController?.hideFloatingWindow()
  1064. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  1065. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1066. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  1067. areaMeasureInfoWindowController?.hideFloatingWindow()
  1068. }
  1069. self.listView.updateActiveAnnotations([anno])
  1070. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  1071. self.listView.setNeedsDisplayForVisiblePages()
  1072. }
  1073. @objc func menuItemActionMeasureEditNote(sender: NSMenuItem) {
  1074. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1075. return
  1076. }
  1077. self.listView.edit(anno)
  1078. }
  1079. @objc func menuItemActionMeasureSetting(sender: NSMenuItem) {
  1080. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1081. return
  1082. }
  1083. self.listView.updateActiveAnnotations([anno])
  1084. self.listView.setNeedsDisplayForVisiblePages()
  1085. if let data = anno as? CPDFLineAnnotation, data.isMeasure {
  1086. self.showMeasureDistanceSettingWindow(measureInfo: data.measureInfo)
  1087. } else if let data = anno as? CPDFPolylineAnnotation {
  1088. self.showMeasurePerimeterSettingWindow(measureInfo: data.measureInfo)
  1089. } else if let data = anno as? CPDFPolygonAnnotation {
  1090. self.showMeasureAreaSettingWindow(measureInfo: data.measureInfo)
  1091. }
  1092. }
  1093. @objc func menuItemActionMeasureDelete(sender: NSMenuItem) {
  1094. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1095. return
  1096. }
  1097. self.listView.remove(anno)
  1098. }
  1099. func showMeasureDistanceSettingWindow(measureInfo: CPDFDistanceMeasureInfo?, hideInfoWindow: Bool = true) {
  1100. guard let mInfo = measureInfo else {
  1101. return
  1102. }
  1103. let winC = CDistanceSettingWindowController(distanceMeasureInfo: mInfo)
  1104. if hideInfoWindow {
  1105. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  1106. }
  1107. winC.delegate = self
  1108. winC.startModal("")
  1109. }
  1110. func showMeasurePerimeterSettingWindow(measureInfo: CPDFPerimeterMeasureInfo?, hideInfoWindow: Bool = true) {
  1111. guard let mInfo = measureInfo else {
  1112. return
  1113. }
  1114. let winC = CDistanceSettingWindowController(perimeterMeasureInfo: mInfo)
  1115. if hideInfoWindow {
  1116. self.perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1117. }
  1118. winC.delegate = self
  1119. winC.startModal("")
  1120. }
  1121. func showMeasureAreaSettingWindow(measureInfo: CPDFAreaMeasureInfo?, hideInfoWindow: Bool = true) {
  1122. guard let mInfo = measureInfo else {
  1123. return
  1124. }
  1125. let winC = CAreaSettingWindowController(measureInfo: mInfo)
  1126. if hideInfoWindow {
  1127. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  1128. }
  1129. winC.delegate = self
  1130. winC.startModal("")
  1131. }
  1132. func splitView(withTag tag: Int) {
  1133. if tag == 0 {
  1134. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1135. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1136. } else if tag == 1 {
  1137. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1138. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1139. } else if tag == 2 {
  1140. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1141. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1142. }
  1143. self.listView.needsDisplay = true
  1144. }
  1145. // MARK: - 幻灯片
  1146. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1147. let view: NSView = self.view.window!.firstResponder as! NSView
  1148. if view.isDescendant(of: pdfSplitView){
  1149. self.view.window?.makeFirstResponder(nil)
  1150. }
  1151. self.mainWindow = self.view.window
  1152. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1153. fullScreenWindow.interactionParent = self.view.window
  1154. self.mainWindow?.delegate = nil
  1155. fullScreenWindow.fadeInBlocking()
  1156. self.browserWindowController?.window = fullScreenWindow
  1157. fullScreenWindow.makeKey()
  1158. let sel = NSSelectorFromString("setAnimationBehavior:")
  1159. if self.mainWindow?.responds(to: sel) ?? false{
  1160. self.mainWindow?.animationBehavior = .none
  1161. }
  1162. self.mainWindow?.orderOut(nil)
  1163. if self.mainWindow?.responds(to: sel) ?? false{
  1164. self.mainWindow?.animationBehavior = .default
  1165. }
  1166. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1167. fullScreenWindow.orderFront(nil)
  1168. }
  1169. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1170. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1171. return
  1172. }
  1173. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1174. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1175. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1176. fullScreenWindow.contentView?.addSubview(view)
  1177. self.listView.layoutDocumentView()
  1178. self.listView.requiresDisplay()
  1179. fullScreenWindow.makeFirstResponder(self.listView)
  1180. fullScreenWindow.recalculateKeyViewLoop()
  1181. fullScreenWindow.delegate = self.browserWindowController
  1182. fullScreenWindow.display()
  1183. fadeWindow.fadeOut()
  1184. }
  1185. // MARK: Redact 【密文标记】
  1186. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1187. self.listView.remove(self.listView.activeAnnotation)
  1188. }
  1189. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1190. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1191. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1192. self.view.window?.beginSheet(windowController.window!)
  1193. self.currentWindowController = windowController
  1194. windowController.itemClick = { [weak self] index, value in
  1195. if (index == 1) { /// 取消
  1196. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1197. self?.currentWindowController = nil
  1198. return
  1199. }
  1200. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1201. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1202. annotaton.setBorderColor(windowController_redact.outsideColor)
  1203. annotaton.setInteriorColor(windowController_redact.fillColor)
  1204. if (windowController_redact.isOver) {
  1205. annotaton.setFontColor(windowController_redact.fontColor)
  1206. annotaton.setAlignment(windowController_redact.aligement)
  1207. annotaton.setFont(windowController_redact.font)
  1208. annotaton.setOverlayText(windowController_redact.overText)
  1209. }
  1210. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1211. self?.currentWindowController = nil
  1212. }
  1213. }
  1214. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1215. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1216. return
  1217. }
  1218. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1219. let model = CPDFAnnotationModel(annotationType: .redact)
  1220. model?.setColor(annotation.borderColor())
  1221. model?.setInteriorColor(annotation.interiorColor())
  1222. let overlayText: String = annotation.overlayText()
  1223. if (overlayText.isEmpty) {
  1224. model?.setIsOverlayText(false)
  1225. } else {
  1226. model?.setIsOverlayText(true)
  1227. model?.setOverlayText(overlayText)
  1228. model?.setFontColor(annotation.fontColor())
  1229. model?.setAlignment(annotation.alignment())
  1230. model?.setFontName(annotation.font().fontName)
  1231. model?.setFontSize(annotation.font().pointSize)
  1232. }
  1233. }
  1234. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1235. let anno = self.listView.activeAnnotation
  1236. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1237. return
  1238. }
  1239. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1240. windowController.pageCount = Int(self.listView.document?.pageCount ?? 0)
  1241. self.currentWindowController = windowController
  1242. self.view.window?.beginSheet(windowController.window!)
  1243. windowController.itemClick = { [weak self] index, value in
  1244. if (index == 1) {
  1245. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1246. self!.currentWindowController = nil
  1247. return
  1248. }
  1249. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1250. let pageType = windowController_mutilPageFlag.pageType
  1251. let pageString = windowController_mutilPageFlag.pageString
  1252. if (pageType == 4) { /// 自定义页面
  1253. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  1254. if (array.count == 0) {
  1255. let alert = NSAlert()
  1256. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1257. alert.runModal()
  1258. return
  1259. }
  1260. }
  1261. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1262. self!.currentWindowController = nil
  1263. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  1264. if (indexs.count == 0) {
  1265. return
  1266. }
  1267. for i in indexs {
  1268. let page: CPDFPage = (self?.listView.document?.page(at: UInt(i)))!
  1269. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1270. self?.listView.add(redactAnno, to: page)
  1271. }
  1272. }
  1273. }
  1274. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1275. self.exeRedactConfirm(.redactOne) {}
  1276. }
  1277. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1278. self.exeRedactConfirm(.eraserOne) {}
  1279. }
  1280. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1281. }
  1282. @objc func exportStampImage(sender:NSMenuItem) {
  1283. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) || (self.listView.selectImageAreas != nil) {
  1284. var image : NSImage = NSImage()
  1285. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1286. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1287. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1288. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1289. } else {
  1290. image = self.listView.selectImageAreas.thumbnailImage(with: CGSize(width: 1920, height: 1920)) ?? NSImage()
  1291. }
  1292. let data = image.tiffRepresentation
  1293. if sender.tag == 0 {
  1294. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1295. imageRep.size = image.size
  1296. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1297. let savePanel = NSSavePanel()
  1298. savePanel.allowedFileTypes = ["png"]
  1299. savePanel.beginSheetModal(for: self.view.window!) { response in
  1300. if (response != .OK) {
  1301. return
  1302. }
  1303. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1304. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1305. }
  1306. }
  1307. } else {
  1308. let pdfdocument = CPDFDocument()
  1309. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1310. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1311. pdfdocument?.km_insertPage(image.size, withImage: signatureImagePath!, at: 0)
  1312. let savePanel = NSSavePanel()
  1313. savePanel.allowedFileTypes = ["pdf"]
  1314. savePanel.beginSheetModal(for: self.view.window!) { response in
  1315. if (response != .OK) {
  1316. return
  1317. }
  1318. if pdfdocument!.write(to: savePanel.url!) {
  1319. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1320. }
  1321. }
  1322. }
  1323. }
  1324. }
  1325. }
  1326. @objc func exportCorpImage(sender:NSMenuItem) {
  1327. let rect = NSIntegralRect(listView.currentSelectionRect())
  1328. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1329. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1330. page.setBounds(rect, for: .cropBox)
  1331. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1332. let data = image.tiffRepresentation
  1333. guard let data = data else { return }
  1334. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1335. imageRep.size = rect.size
  1336. let savePanel = NSSavePanel()
  1337. switch sender.tag {
  1338. case 0:
  1339. savePanel.allowedFileTypes = ["png"]
  1340. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1341. savePanel.beginSheetModal(for: self.view.window!) { response in
  1342. if (response != .OK) {
  1343. return
  1344. }
  1345. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1346. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1347. }
  1348. }
  1349. case 1:
  1350. savePanel.allowedFileTypes = ["jpg"]
  1351. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1352. savePanel.beginSheetModal(for: self.view.window!) { response in
  1353. if (response != .OK) {
  1354. return
  1355. }
  1356. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1357. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1358. }
  1359. }
  1360. case 2:
  1361. savePanel.allowedFileTypes = ["pdf"]
  1362. let pdfdocument = CPDFDocument()
  1363. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1364. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1365. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1366. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1367. savePanel.beginSheetModal(for: self.view.window!) { response in
  1368. if (response != .OK) {
  1369. return
  1370. }
  1371. if pdfdocument!.write(to: savePanel.url!) {
  1372. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1373. }
  1374. }
  1375. }
  1376. default:
  1377. break
  1378. }
  1379. // 执行右键操作后,需要取消框选区域
  1380. if self.listView.toolMode == .selectToolMode {
  1381. objc_sync_enter(self)
  1382. self.listView.selectionRect = NSZeroRect
  1383. self.listView.selectionPageIndex = UInt(NSNotFound)
  1384. objc_sync_exit(self)
  1385. }
  1386. }
  1387. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1388. let rect = listView.currentSelectionRect()
  1389. let page = listView.currentPage()
  1390. if NSIsEmptyRect(rect) == false && page != nil {
  1391. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1392. var bounds = listView.bounds
  1393. var scale = 1.0
  1394. if isLegacy {
  1395. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1396. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1397. }
  1398. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1399. scale = NSHeight(bounds) / NSHeight(rect)
  1400. } else {
  1401. scale = NSWidth(bounds) / NSWidth(rect)
  1402. }
  1403. listView.setScaleFactor(scale, animated: false)
  1404. let scrollView = listView.scroll()
  1405. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1406. if ((scrollView?.hasVerticalScroller) != nil) {
  1407. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1408. }
  1409. if ((scrollView?.hasHorizontalScroller) != nil) {
  1410. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1411. }
  1412. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1413. scale = NSHeight(bounds) / NSHeight(rect)
  1414. } else {
  1415. scale = NSWidth(bounds) / NSWidth(rect)
  1416. }
  1417. listView.setScaleFactor(scale, animated: false)
  1418. }
  1419. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1420. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1421. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1422. };
  1423. }
  1424. // 执行右键操作后,需要取消框选区域
  1425. if self.listView.toolMode == .selectToolMode {
  1426. objc_sync_enter(self)
  1427. self.listView.selectionRect = NSZeroRect
  1428. self.listView.selectionPageIndex = UInt(NSNotFound)
  1429. objc_sync_exit(self)
  1430. }
  1431. }
  1432. private func cropPagesToRects(rects:NSPointerArray) {
  1433. }
  1434. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1435. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1436. switch sender.tag {
  1437. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1438. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1439. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1440. var red: CGFloat = 0.0
  1441. var green: CGFloat = 0.0
  1442. var blue: CGFloat = 0.0
  1443. var alpha: CGFloat = 0.0
  1444. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1445. if sender.tag == CAnnotationType.highlight.rawValue {
  1446. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1447. } else if sender.tag == CAnnotationType.underline.rawValue {
  1448. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1449. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1450. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1451. }
  1452. case CAnnotationType.ink.rawValue:
  1453. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1454. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1455. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1456. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1457. var red: CGFloat = 0.0
  1458. var green: CGFloat = 0.0
  1459. var blue: CGFloat = 0.0
  1460. var alpha: CGFloat = 0.0
  1461. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1462. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1463. case CAnnotationType.freeText.rawValue:
  1464. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1465. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1466. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1467. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1468. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1469. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1470. var red: CGFloat = 0.0
  1471. var green: CGFloat = 0.0
  1472. var blue: CGFloat = 0.0
  1473. var alpha: CGFloat = 0.0
  1474. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1475. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1476. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1477. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1478. UserDefaults.standard.synchronize()
  1479. }
  1480. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1481. if (alignment == .left || alignment == .center || alignment == .right) {
  1482. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1483. UserDefaults.standard.synchronize()
  1484. }
  1485. case CAnnotationType.anchored.rawValue:
  1486. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1487. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1488. var red: CGFloat = 0.0
  1489. var green: CGFloat = 0.0
  1490. var blue: CGFloat = 0.0
  1491. var alpha: CGFloat = 0.0
  1492. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1493. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1494. case CAnnotationType.square.rawValue:
  1495. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1496. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1497. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1498. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1499. var red: CGFloat = 0.0
  1500. var green: CGFloat = 0.0
  1501. var blue: CGFloat = 0.0
  1502. var alpha: CGFloat = 0.0
  1503. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1504. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1505. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1506. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1507. case CAnnotationType.circle.rawValue:
  1508. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1509. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1510. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1511. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1512. var red: CGFloat = 0.0
  1513. var green: CGFloat = 0.0
  1514. var blue: CGFloat = 0.0
  1515. var alpha: CGFloat = 0.0
  1516. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1517. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1518. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1519. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1520. default:
  1521. break
  1522. }
  1523. }
  1524. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1525. self.showOrHideNotes()
  1526. }
  1527. //MARK: - action
  1528. @objc func cropCurrentPage() {
  1529. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1530. var page: CPDFPage?
  1531. if let data = self.listView.currentSelectionPage() {
  1532. page = data
  1533. } else {
  1534. page = self.listView.currentPage()
  1535. }
  1536. if (NSIsEmptyRect(rect)) {
  1537. rect = KMCropTools.getPageForegroundBox(page!)
  1538. }
  1539. let index: UInt = (page?.pageIndex()) ?? 0
  1540. self._cropPage(at: index, in: rect)
  1541. // 执行右键操作后,需要取消框选区域
  1542. if self.listView.toolMode == .selectToolMode {
  1543. objc_sync_enter(self)
  1544. self.listView.selectionRect = NSZeroRect
  1545. self.listView.selectionPageIndex = UInt(NSNotFound)
  1546. objc_sync_exit(self)
  1547. }
  1548. self.handlePageBoundsDidChange(page: page, action: CPDFPage.Action.crop)
  1549. }
  1550. @objc private func _cropPage(at index: UInt, in rect: NSRect) {
  1551. let oldRect = self.listView.document?.page(at: index)?.bounds(for: .cropBox) ?? .zero
  1552. let undoManager = self.listView.undoManager
  1553. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)?._cropPage(at: index, in: oldRect)
  1554. let page = self.listView.document.page(at: index)
  1555. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox)) ?? .zero)
  1556. page?.setBounds(newRect, for: .cropBox)
  1557. /// 刷新预览视图
  1558. self.listView.layoutDocumentView()
  1559. self.listView.displayBox = .cropBox
  1560. }
  1561. func beginProgressSheet(with message: String, maxValue: UInt) {
  1562. let progress = SKProgressController()
  1563. progress.window?.contentView?.wantsLayer = true
  1564. progress.message = NSLocalizedString("Converting...", comment: "")
  1565. self.progressC = progress
  1566. self.progressC?.message = message
  1567. if maxValue > 0 {
  1568. progressC?.indeterminate = false
  1569. progressC?.maxValue = Double(maxValue)
  1570. } else {
  1571. progressC?.indeterminate = true
  1572. }
  1573. self.view.km_beginSheet(windowC: progressC!)
  1574. }
  1575. // 白边距
  1576. @objc func smart_cropAllPage() {
  1577. var size = NSZeroSize
  1578. for i in 0 ..< self.listView.document.pageCount {
  1579. let page = self.listView.document.page(at: i)
  1580. let rect = KMCropTools.getPageForegroundBox(page!)
  1581. size.width = fmax(size.width, NSWidth(rect))
  1582. size.height = fmax(size.height, NSHeight(rect))
  1583. }
  1584. beginProgressSheet(with: KMLocalizedString("Cropping Pages"), maxValue: min(18, self.listView.document.pageCount))
  1585. var rectArray: Array<NSRect> = []
  1586. for i in 0 ..< self.listView.document.pageCount {
  1587. progressC?.increment(by: Double(i))
  1588. progressC?.doubleValue = Double(i)
  1589. let page = self.listView.document.page(at: i)
  1590. var rect = KMCropTools.getPageForegroundBox(page!)
  1591. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1592. rectArray.append(rect)
  1593. }
  1594. cropPages(to: rectArray)
  1595. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1596. }
  1597. // 自动
  1598. @objc func auto_cropAllPage() {
  1599. var size = NSZeroSize
  1600. for i in 0 ..< self.listView.document.pageCount {
  1601. let page = self.listView.document.page(at: i)
  1602. let rect = KMCropTools.getPageForegroundBox(page!)
  1603. size.width = fmax(size.width, NSWidth(rect))
  1604. size.height = fmax(size.height, NSHeight(rect))
  1605. }
  1606. beginProgressSheet(with: KMLocalizedString("Cropping Pages"), maxValue: min(18, self.listView.document.pageCount))
  1607. var rectArray: Array<NSRect> = []
  1608. for i in 0 ..< self.listView.document.pageCount {
  1609. progressC?.increment(by: Double(i))
  1610. progressC?.doubleValue = Double(i)
  1611. let page = self.listView.document.page(at: i)
  1612. var rect = KMCropTools.getPageForegroundBox(page!)
  1613. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1614. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1615. rect.origin.x = rect.maxX-size.width
  1616. }
  1617. rect.origin.y = rect.maxY-size.height
  1618. rect.size = size
  1619. if (NSWidth(rect) > NSWidth(bounds)) {
  1620. rect.size.width = NSWidth(bounds)
  1621. }
  1622. if (NSHeight(rect) > NSHeight(bounds)) {
  1623. rect.size.height = NSHeight(bounds)
  1624. }
  1625. if (NSMinX(rect) < NSMinX(bounds)) {
  1626. rect.origin.x = NSMinX(bounds)
  1627. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1628. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1629. }
  1630. if (NSMinY(rect) < NSMinY(bounds)) {
  1631. rect.origin.y = NSMinY(bounds)
  1632. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1633. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1634. }
  1635. rectArray.append(rect)
  1636. }
  1637. cropPages(to: rectArray)
  1638. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1639. }
  1640. @objc func cropAllPage() {
  1641. var rect = [NSIntegralRect(self.listView.currentSelectionRect() ?? .zero), .zero]
  1642. var rectArray: Array<NSRect> = []
  1643. let emptySelection = NSIsEmptyRect(rect.first ?? .zero)
  1644. if (emptySelection) {
  1645. guard let count = self.listView.document?.pageCount, count > 0 else {
  1646. KMPrint("listView | document is nil.", beep: true)
  1647. return
  1648. }
  1649. rect[0] = .zero
  1650. rect[1] = .zero
  1651. self.beginProgressSheet(withMessage: NSLocalizedString("Cropping Pages", comment: "Message for progress sheet"), maxValue: min(18, count))
  1652. if (count == 1) {
  1653. if let page = self.listView.document.page(at: 0) {
  1654. rect[0] = KMCropTools.getPageForegroundBox(page)
  1655. }
  1656. progressC?.increment(by: 1)
  1657. } else if (count < 19) {
  1658. for i in 0 ..< 19 {
  1659. if let page = self.listView.document.page(at: UInt(i)) {
  1660. rect[i % 2] = NSUnionRect(rect[i % 2], KMCropTools.getPageForegroundBox(page))
  1661. progressC?.increment(by: Double(i))
  1662. }
  1663. }
  1664. } else {
  1665. let start = [1, (count - 5) / 2, count - 6]
  1666. var cnt = 0
  1667. for j in 0 ..< 3 {
  1668. for i in 0 ..< 6 {
  1669. let k = Int(start[j] + UInt(i))
  1670. if let page = self.listView.document.page(at: UInt(k)) {
  1671. rect[k % 2] = NSUnionRect(rect[k % 2], KMCropTools.getPageForegroundBox(page))
  1672. cnt += 1
  1673. progressC?.increment(by: Double(cnt))
  1674. }
  1675. }
  1676. }
  1677. }
  1678. let w = fmax(NSWidth(rect[0]), NSWidth(rect[1]))
  1679. let h = fmax(NSHeight(rect[0]), NSHeight(rect[1]))
  1680. for j in 0 ..< 2 {
  1681. rect[j] = NSMakeRect(floor(NSMidX(rect[j]) - 0.5 * w), floor(NSMidY(rect[j]) - 0.5 * h), w, h)
  1682. }
  1683. rectArray.append(rect.first ?? .zero)
  1684. rectArray.append(rect.last ?? .zero)
  1685. } else {
  1686. rectArray.append(rect.first ?? .zero)
  1687. }
  1688. self.cropPages(to: rectArray)
  1689. // 执行右键操作后,需要取消框选区域
  1690. if self.listView.toolMode == .selectToolMode {
  1691. objc_sync_enter(self)
  1692. self.listView.selectionRect = NSZeroRect
  1693. self.listView.selectionPageIndex = UInt(NSNotFound)
  1694. objc_sync_exit(self)
  1695. }
  1696. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1697. }
  1698. func cropPages(to rects: Array<NSRect>) {
  1699. let currentPage = self.listView.currentPage()
  1700. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1701. var oldRectArray: Array<NSRect> = []
  1702. let rectCount = rects.count
  1703. for i in 0 ..< self.listView.document.pageCount {
  1704. let page = self.listView.document.page(at: i)
  1705. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page?.bounds(for: .mediaBox))!)
  1706. let oldRect = page?.bounds(for: .cropBox)
  1707. oldRectArray.append(oldRect!)
  1708. page?.setBounds(rect, for: .cropBox)
  1709. }
  1710. let undoManager = self.listView.undoManager
  1711. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1712. /// 刷新预览视图
  1713. self.listView.layoutDocumentView()
  1714. self.listView.displayBox = .cropBox
  1715. self.listView.go(to: currentPage)
  1716. self.listView.go(to: visibleRect, on: currentPage)
  1717. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1718. self.dismissProgressSheet()
  1719. }
  1720. }
  1721. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1722. if (limit) {
  1723. let document = self.listView.document ?? CPDFDocument()
  1724. if document?.documentURL == nil {
  1725. return
  1726. }
  1727. var doucumentURL : URL = self.listView.document.documentURL
  1728. if doucumentURL.path.count > 0 {
  1729. let docDir = NSTemporaryDirectory()
  1730. let documentName : String = doucumentURL.path.lastPathComponent
  1731. let path = docDir.stringByAppendingPathComponent(documentName)
  1732. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1733. let writeSuccess = data != nil
  1734. if writeSuccess == false {
  1735. __NSBeep()
  1736. return;
  1737. }
  1738. doucumentURL = URL(fileURLWithPath: path)
  1739. }
  1740. let array = [doucumentURL]
  1741. let picker = NSSharingServicePicker.init(items: array)
  1742. if sender.shareButton.window != nil {
  1743. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1744. } else {
  1745. 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)
  1746. }
  1747. return
  1748. }
  1749. let document = self.listView.document ?? CPDFDocument()
  1750. if document?.documentURL == nil {
  1751. return
  1752. }
  1753. var doucumentURL : URL = self.listView.document.documentURL
  1754. if doucumentURL.path.count > 0 {
  1755. let docDir = NSTemporaryDirectory()
  1756. let documentName : String = doucumentURL.path.lastPathComponent
  1757. let path = docDir.stringByAppendingPathComponent(documentName)
  1758. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1759. if writeSuccess == false {
  1760. __NSBeep()
  1761. return;
  1762. }
  1763. doucumentURL = URL(fileURLWithPath: path)
  1764. }
  1765. let array = [doucumentURL]
  1766. let picker = NSSharingServicePicker.init(items: array)
  1767. if sender.shareButton.window != nil {
  1768. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1769. } else {
  1770. 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)
  1771. }
  1772. }
  1773. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1774. if (limit) {
  1775. let document = self.listView.document ?? CPDFDocument()
  1776. var path: String?
  1777. if document?.documentURL != nil {
  1778. path = document?.documentURL.path ?? ""
  1779. }
  1780. if path?.count ?? 0 > 0 {
  1781. let docDir = NSTemporaryDirectory()
  1782. let documentName : String = path?.lastPathComponent ?? ""
  1783. path = docDir.stringByAppendingPathComponent(documentName)
  1784. }
  1785. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  1786. var tfileName = path?.deletingPathExtension.lastPathComponent
  1787. let tStdFileSuffix = "_flatten"
  1788. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  1789. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  1790. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path ?? ""))
  1791. let success = data != nil
  1792. if success {
  1793. let url = URL(fileURLWithPath: path ?? "")
  1794. let picker = NSSharingServicePicker.init(items: [url])
  1795. if sender.shareButton.window != nil {
  1796. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1797. } else {
  1798. 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)
  1799. }
  1800. }
  1801. return
  1802. }
  1803. let document = self.listView.document ?? CPDFDocument()
  1804. var path: String?
  1805. if document?.documentURL != nil {
  1806. path = document?.documentURL.path ?? ""
  1807. }
  1808. if path?.count ?? 0 > 0 {
  1809. let docDir = NSTemporaryDirectory()
  1810. let documentName : String = path?.lastPathComponent ?? ""
  1811. path = docDir.stringByAppendingPathComponent(documentName)
  1812. }
  1813. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  1814. var tfileName = path?.deletingPathExtension.lastPathComponent
  1815. let tStdFileSuffix = "_flatten"
  1816. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  1817. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  1818. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  1819. if success {
  1820. let url = URL(fileURLWithPath: path ?? "")
  1821. let picker = NSSharingServicePicker.init(items: [url])
  1822. if sender.shareButton.window != nil {
  1823. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1824. } else {
  1825. 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)
  1826. }
  1827. }
  1828. }
  1829. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  1830. guard let pdfDoc = self.listView.document else {
  1831. NSSound.beep()
  1832. return
  1833. }
  1834. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  1835. let alert = NSAlert()
  1836. alert.alertStyle = .critical
  1837. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1838. alert.runModal()
  1839. return
  1840. }
  1841. if (limit) {
  1842. let document = self.listView.document ?? CPDFDocument()
  1843. var path: String?
  1844. if document?.documentURL != nil {
  1845. path = document?.documentURL.path ?? ""
  1846. }
  1847. if path?.count ?? 0 > 0{
  1848. let docDir = NSTemporaryDirectory()
  1849. let documentName : String = path?.lastPathComponent ?? ""
  1850. path = docDir.stringByAppendingPathComponent(documentName)
  1851. }
  1852. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path ?? ""), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1853. var writeSuccess = data != nil
  1854. if writeSuccess == false {
  1855. __NSBeep()
  1856. return;
  1857. }
  1858. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  1859. let cnt = newDocument?.pageCount ?? 0
  1860. for i in 0 ..< cnt {
  1861. let page = newDocument?.page(at: i)
  1862. var annotations : [CPDFAnnotation] = []
  1863. for annotation in page!.annotations {
  1864. annotations.append(annotation)
  1865. }
  1866. for annotation in annotations {
  1867. annotation.page.removeAnnotation(annotation)
  1868. }
  1869. }
  1870. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? "")) ?? false
  1871. if writeSuccess {
  1872. let url = URL(fileURLWithPath: path ?? "")
  1873. let picker = NSSharingServicePicker.init(items: [url])
  1874. if sender.shareButton.window != nil {
  1875. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1876. } else {
  1877. 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)
  1878. }
  1879. }
  1880. return
  1881. }
  1882. let document = self.listView.document ?? CPDFDocument()
  1883. var path: String?
  1884. if document?.documentURL != nil {
  1885. path = document?.documentURL.path ?? ""
  1886. }
  1887. if path?.count ?? 0 > 0 {
  1888. let docDir = NSTemporaryDirectory()
  1889. let documentName : String = path?.lastPathComponent ?? ""
  1890. path = docDir.stringByAppendingPathComponent(documentName)
  1891. }
  1892. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  1893. if writeSuccess == false {
  1894. __NSBeep()
  1895. return;
  1896. }
  1897. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  1898. let cnt = newDocument?.pageCount ?? 0
  1899. for i in 0 ..< cnt {
  1900. let page = newDocument!.page(at: i)
  1901. var annotations : [CPDFAnnotation] = []
  1902. for annotation in page!.annotations {
  1903. annotations.append(annotation)
  1904. }
  1905. for annotation in annotations {
  1906. annotation.page.removeAnnotation(annotation)
  1907. }
  1908. }
  1909. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  1910. if writeSuccess ?? false {
  1911. let url = URL(fileURLWithPath: path ?? "")
  1912. let picker = NSSharingServicePicker.init(items: [url])
  1913. if sender.shareButton.window != nil {
  1914. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1915. } else {
  1916. 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)
  1917. }
  1918. }
  1919. }
  1920. // 开启/关闭左边栏
  1921. @objc func toggleLeftPane() -> Void {
  1922. self.model.leftPanelOpen = true
  1923. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1924. }
  1925. // 开启左边栏
  1926. @objc func openLeftPane() -> Void {
  1927. self.model.leftPanelOpen = true
  1928. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1929. }
  1930. // 关闭左边栏
  1931. @objc func closeLeftPane() -> Void {
  1932. self.model.leftPanelOpen = false
  1933. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1934. }
  1935. // 开启/关闭右边栏
  1936. @objc func toggleRightPane() -> Void {
  1937. if self.model.lastRightPanWidth > 5 {
  1938. self.model.rightPanelIsOpen = false
  1939. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  1940. } else {
  1941. self.model.rightPanelIsOpen = true
  1942. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  1943. }
  1944. }
  1945. @objc func openRightPane() -> Void {
  1946. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1947. if self.model.rightPanelIsOpen {
  1948. return
  1949. }
  1950. self.model.rightPanelIsOpen = true
  1951. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  1952. }
  1953. }
  1954. @objc func closeRightPane() -> Void {
  1955. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1956. self.model.rightPanelIsOpen = false
  1957. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  1958. cancelMeasureType()
  1959. }
  1960. }
  1961. func rename(_ sender: NSNotification) -> Void {
  1962. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1963. return
  1964. }
  1965. let tabController = sender.object as? CTTabController
  1966. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  1967. if let doc = self.myDocument, doc.isDocumentEdited {
  1968. Task {
  1969. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  1970. if resp != .alertFirstButtonReturn { // 取消
  1971. return
  1972. }
  1973. doc.updateChangeCount(.changeCleared)
  1974. self.document?.write(to: doc.fileURL)
  1975. Task { @MainActor in
  1976. self._renameForSavePanel(tabController)
  1977. }
  1978. }
  1979. return
  1980. }
  1981. self._renameForSavePanel(tabController)
  1982. }
  1983. }
  1984. func savePdfAlertView() {
  1985. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  1986. return
  1987. }
  1988. AutoSaveManager.manager.isSaveNoti = true
  1989. var num = 0
  1990. if self.listView.document != nil{
  1991. num = Int(self.listView.document.pageCount)
  1992. }
  1993. if Thread.current.isMainThread {
  1994. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1995. } else {
  1996. DispatchQueue.main.async {
  1997. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1998. }
  1999. }
  2000. }
  2001. func savePdfFinishAlertView() {
  2002. if !AutoSaveManager.manager.isSaveNoti{
  2003. return
  2004. }
  2005. AutoSaveManager.manager.isSaveNoti = false
  2006. if Thread.current.isMainThread {
  2007. self.dismissProgressSheet()
  2008. } else {
  2009. DispatchQueue.main.async {
  2010. self.dismissProgressSheet()
  2011. }
  2012. }
  2013. }
  2014. private func _renameForSavePanel(_ tabC: CTTabController?) {
  2015. let outputSavePanel = NSSavePanel()
  2016. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  2017. outputSavePanel.allowedFileTypes = ["pdf"]
  2018. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  2019. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  2020. let resp = outputSavePanel.runModal()
  2021. if resp == .OK {
  2022. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  2023. let fileURL = pdfDocument?.documentURL
  2024. let fileManager = FileManager.default
  2025. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  2026. var result = true
  2027. do {
  2028. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  2029. } catch {
  2030. result = false
  2031. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  2032. }
  2033. if (result) {
  2034. tabC?.title = outputSavePanel.url!.lastPathComponent
  2035. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  2036. self.model.isSaveKeyChain = false
  2037. newPdfDocument.unlock(withPassword: self.document?.password)
  2038. if (newPdfDocument.pageCount > 0) {
  2039. self.setDocument = newPdfDocument
  2040. }
  2041. }
  2042. }
  2043. } else {
  2044. outputSavePanel.close()
  2045. }
  2046. }
  2047. func showInFinder(_ sender: Any) -> Void {
  2048. if sender is NSNotification {
  2049. let tabController = (sender as! NSNotification).object as? CTTabController
  2050. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2051. if tabController?.title == path {
  2052. if let file = self.myDocument?.fileURL {
  2053. if FileManager.default.fileExists(atPath: file.path) {
  2054. NSWorkspace.shared.activateFileViewerSelecting([file])
  2055. }
  2056. }
  2057. }
  2058. } else {
  2059. guard let url = self.myDocument?.fileURL else { return }
  2060. let file: URL = url
  2061. if FileManager.default.fileExists(atPath: file.path) {
  2062. NSWorkspace.shared.activateFileViewerSelecting([file])
  2063. }
  2064. }
  2065. }
  2066. func showOrHideNotes() {
  2067. self.listView.hideNotes = !self.listView.hideNotes
  2068. for note in self.listView.notes as? [CPDFAnnotation] ?? [] {
  2069. if note.isForm() {
  2070. note.setAnnotationShouldDisplay(true)
  2071. note.setHidden(false)
  2072. }
  2073. }
  2074. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  2075. self.leftSideViewController.note_reloadDataIfNeed()
  2076. }
  2077. func closeTab(_ sender: NSNotification) -> Void {
  2078. }
  2079. @IBAction func toggleSplitPDF(_ sender: Any) {
  2080. if let menuItem = sender as? NSMenuItem {
  2081. splitView(withTag: menuItem.tag)
  2082. }
  2083. }
  2084. func handlePageBoundsDidChange(page: CPDFPage?, action: String) {
  2085. let displayChanged = action == CPDFPage.Action.crop || self.listView.displayBox == .cropBox
  2086. if (displayChanged) {
  2087. self.listView.layoutDocumentView()
  2088. }
  2089. if (page != nil) {
  2090. let idx = page!.pageIndex()
  2091. if (displayChanged) {
  2092. self.leftSideViewController.updateThumbnail(at: Int(idx))
  2093. }
  2094. } else {
  2095. if (displayChanged) {
  2096. self.leftSideViewController.allThumbnailsNeedUpdate()
  2097. }
  2098. }
  2099. self.leftSideViewController.updateSnapshotsIfNeed(for: page)
  2100. if UserDefaults.standard.bool(forKey: SKDisplayPageBoundsKey) {
  2101. }
  2102. }
  2103. func changeLineAttribute(_ sender: Any?) {
  2104. var inspector = sender as? KMLineInspector
  2105. if inspector == nil {
  2106. inspector = KMLineInspector.shared
  2107. }
  2108. let action = inspector?.currentLineChangeAction ?? .no
  2109. for annotation in self.listView.activeAnnotations {
  2110. guard let anno = annotation as? CPDFAnnotation else {
  2111. continue
  2112. }
  2113. if anno.hasBorder() {
  2114. switch (action) {
  2115. case .lineWidth:
  2116. anno.setLineWidth(inspector?.lineWidth ?? 0)
  2117. break
  2118. case .style:
  2119. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  2120. break
  2121. case .dashPattern:
  2122. anno.setDashPattern(inspector?.dashPattern ?? [])
  2123. break
  2124. case .startLineStyle:
  2125. if anno.isLine() {
  2126. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  2127. }
  2128. break
  2129. case .endLineStyle:
  2130. if anno.isLine() {
  2131. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  2132. }
  2133. break
  2134. case .no:
  2135. break
  2136. }
  2137. }
  2138. }
  2139. }
  2140. // MARK: -
  2141. // MARK: 显示窗口
  2142. internal func showCompressWindow(url: URL? = nil) {
  2143. self.compressWIndowControllerNew = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  2144. self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  2145. self.compressWIndowControllerNew?.password = self.listView.document?.password ?? ""
  2146. self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  2147. self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  2148. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2149. }
  2150. self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  2151. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2152. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2153. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2154. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2155. batchWindowController.window?.makeKeyAndOrderFront("")
  2156. }
  2157. self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  2158. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2159. if (result) {
  2160. if (openDocument) {
  2161. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2162. } else {
  2163. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2164. }
  2165. } else {
  2166. let alert = NSAlert()
  2167. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2168. alert.runModal()
  2169. }
  2170. }
  2171. }
  2172. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  2173. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  2174. KMPrint("转档窗口已显示")
  2175. return
  2176. }
  2177. var convertT: KMConvertType = .Word
  2178. var windowController: KMConvertBaseWindowController?
  2179. if (type == .word) { /// Word
  2180. convertT = .Word
  2181. windowController = KMConvertWordWindowController()
  2182. } else if (type == .excel) {
  2183. convertT = .Excel
  2184. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  2185. if (type == .ppt) {
  2186. convertT = .PPT
  2187. } else if (type == .rtf) {
  2188. convertT = .RTF
  2189. } else if (type == .html) {
  2190. convertT = .HTML
  2191. } else if (type == .conversion_text) {
  2192. convertT = .Text
  2193. }
  2194. } else if (type == .csv) {
  2195. convertT = .CSV
  2196. } else if (type == .conversion_image) {
  2197. windowController = KMConvertImageWindowController()
  2198. convertT = .JPEG
  2199. } else if type == .json {
  2200. convertT = .Json
  2201. }
  2202. var url: URL?
  2203. if (documentUrl != nil) {
  2204. url = documentUrl
  2205. windowController?.oriDocumentUrl = self.listView.document.documentURL
  2206. } else {
  2207. url = self.listView.document.documentURL
  2208. }
  2209. let model = KMDocumentModel(url: url!)
  2210. windowController?.documentModel = model
  2211. self.km_safe_beginSheet(windowC: windowController)
  2212. }
  2213. //MARK: 转档 -
  2214. func showAllConvertWindow(convertT: KMConvertType) {
  2215. self.ConvertTrackEvent(type: convertT)
  2216. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  2217. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2218. var type: KMConvertWithPDFType = .WordAdvance
  2219. switch convertT {
  2220. case .Word:
  2221. break
  2222. case .Excel:
  2223. type = .Excel
  2224. case .PPT:
  2225. type = .PowerPoint
  2226. case .RTF:
  2227. type = .RTF
  2228. case .CSV:
  2229. type = .CSV
  2230. case .HTML:
  2231. type = .HTML
  2232. case .Text:
  2233. type = .Text
  2234. case .JPEG:
  2235. type = .JPEG
  2236. case .PNG:
  2237. type = .PNG
  2238. case .GIF:
  2239. type = .GIF
  2240. case .JPG:
  2241. type = .JPG
  2242. case .TIFF:
  2243. type = .TIFF
  2244. case .TGA:
  2245. type = .TGA
  2246. case .BMP:
  2247. type = .BMP
  2248. case .JP2:
  2249. type = .JPEG2000
  2250. case .AdvancedWord:
  2251. break
  2252. case .Json:
  2253. type = .Json
  2254. break
  2255. default:
  2256. break
  2257. }
  2258. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2259. var needShowHint = false
  2260. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2261. needShowHint = true
  2262. } else {
  2263. var needContinue = false
  2264. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2265. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2266. let ss = self.document?.documentURL.path
  2267. if arr.contains(ss!) {
  2268. needContinue = false
  2269. }else {
  2270. needContinue = true
  2271. }
  2272. }else {
  2273. needContinue = true
  2274. }
  2275. if needContinue {
  2276. let ss = self.document?.documentURL.path
  2277. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2278. file.password = document?.password ?? ""
  2279. KMBatchOperateManager.defaultManager.files?.append(file)
  2280. }
  2281. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2282. batchWindowController.switchToConvertType(convertType: type)
  2283. }
  2284. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2285. if needShowHint {
  2286. batchWindowController.showIsConvertingHint()
  2287. } else {
  2288. }
  2289. }
  2290. }
  2291. self.km_beginSheet(windowC: convertWC)
  2292. }
  2293. func ConvertTrackEvent(type: KMConvertType) {
  2294. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  2295. switch type {
  2296. case .Word:
  2297. eventStr = "Btn_SubTbr_Converter_ToWord"
  2298. break
  2299. case .Excel:
  2300. eventStr = "Btn_SubTbr_Converter_ToExcel"
  2301. case .PPT:
  2302. eventStr = "Btn_SubTbr_Converter_ToPPT"
  2303. case .RTF:
  2304. eventStr = "Btn_SubTbr_Converter_ToRTF"
  2305. case .CSV:
  2306. eventStr = "Btn_SubTbr_Converter_ToCSV"
  2307. case .HTML:
  2308. eventStr = "Btn_SubTbr_Converter_ToHTML"
  2309. case .Text:
  2310. eventStr = "Btn_SubTbr_Converter_ToText"
  2311. case .JPEG:
  2312. eventStr = "Btn_SubTbr_Converter_ToImage"
  2313. case .PNG:
  2314. eventStr = "Btn_SubTbr_Converter_ToImage"
  2315. case .GIF:
  2316. eventStr = "Btn_SubTbr_Converter_ToImage"
  2317. case .JPG:
  2318. eventStr = "Btn_SubTbr_Converter_ToImage"
  2319. case .TIFF:
  2320. eventStr = "Btn_SubTbr_Converter_ToImage"
  2321. case .TGA:
  2322. eventStr = "Btn_SubTbr_Converter_ToImage"
  2323. case .BMP:
  2324. eventStr = "Btn_SubTbr_Converter_ToImage"
  2325. case .JP2:
  2326. eventStr = "Btn_SubTbr_Converter_ToImage"
  2327. case .AdvancedWord:
  2328. eventStr = "Btn_SubTbr_Converter_ToWord"
  2329. break
  2330. default:
  2331. break
  2332. }
  2333. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  2334. }
  2335. //MARK: 转档 - OCR
  2336. func showOCRWindow() {
  2337. if !IAPProductsManager.default().isAvailableAllFunction(){
  2338. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2339. winC?.showWindow(nil)
  2340. return
  2341. }
  2342. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  2343. com.currentIndexPage = self.listView.currentPageIndex
  2344. self.km_beginSheet(windowC: com)
  2345. }
  2346. //MARK: 导出图片
  2347. func extractImageAction(num: Int) {
  2348. if !IAPProductsManager.default().isAvailableAllFunction(){
  2349. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2350. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  2351. winC?.showWindow(nil)
  2352. return
  2353. }
  2354. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2355. let alert = NSAlert()
  2356. alert.alertStyle = .critical
  2357. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2358. alert.runModal()
  2359. return
  2360. }
  2361. let document = self.listView.document
  2362. var fileURL = document?.documentURL
  2363. if num == 1 {
  2364. let pageCount = document?.pageCount ?? 0
  2365. let indeSet = NSMutableIndexSet()
  2366. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2367. if indeSet.count == 0 {
  2368. return
  2369. }
  2370. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2371. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2372. let outputSavePanel = NSSavePanel()
  2373. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2374. outputSavePanel.allowsOtherFileTypes = true
  2375. outputSavePanel.isExtensionHidden = true
  2376. outputSavePanel.canCreateDirectories = true
  2377. outputSavePanel.nameFieldStringValue = tFileName
  2378. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2379. if result == NSApplication.ModalResponse.OK {
  2380. DispatchQueue.main.async {
  2381. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2382. let tDestFile = outputSavePanel.url!.path
  2383. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2384. let pdfconverter = PDFConvertObject()
  2385. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2386. self.dismissProgressSheet()
  2387. let fileManager = FileManager.default
  2388. if fileManager.fileExists(atPath: tDestFile) {
  2389. let workspace = NSWorkspace.shared
  2390. let url = URL(fileURLWithPath: tDestFile)
  2391. workspace.activateFileViewerSelecting([url])
  2392. }
  2393. }
  2394. }
  2395. })
  2396. return
  2397. }
  2398. if fileURL != nil {
  2399. self.myDocument?.save(nil)
  2400. } else {
  2401. let myDocument = self.myDocument
  2402. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2403. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2404. if writeSuccess {
  2405. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2406. fileURL = document?.documentURL
  2407. } else {
  2408. NSSound.beep()
  2409. return
  2410. }
  2411. }
  2412. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2413. extract?.docPath = fileURL?.path ?? ""
  2414. extract?.password = document?.password ?? ""
  2415. extract?.currentPage = self.listView.currentPageIndex
  2416. self.km_beginSheet(windowC: extract!)
  2417. extract?.selectCurrentPageBtn()
  2418. }
  2419. //MARK: 创建文字图章示例实际上不会在这里使用
  2420. func showCreateStamp() {
  2421. let stampCreaterWindowController = KMStampCreaterWindowController()
  2422. stampCreaterWindowController.window?.backgroundColor = .clear
  2423. self.km_beginSheet(windowC: stampCreaterWindowController)
  2424. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  2425. if result == 1 {
  2426. }
  2427. }
  2428. }
  2429. //MARK: 添加签名示例实际上不会在这里使用
  2430. func showAddSignature() {
  2431. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")
  2432. self.view.window?.beginSheet(signatureWindowController.window!, completionHandler: { returnCode in
  2433. })
  2434. }
  2435. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2436. let progress = SKProgressController()
  2437. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2438. progress.window?.contentView?.wantsLayer = true
  2439. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2440. progress.progressField.textColor = NSColor.white
  2441. progress.message = NSLocalizedString("Converting...", comment: "")
  2442. progressC = progress
  2443. progressC?.message = message
  2444. if maxValue > 0 {
  2445. progressC?.indeterminate = false
  2446. progressC?.maxValue = Double(maxValue)
  2447. progressC?.progressBar.doubleValue = 0.3
  2448. } else {
  2449. progressC?.indeterminate = true
  2450. }
  2451. self.view.km_beginSheet(windowC: progressC!)
  2452. }
  2453. func dismissProgressSheet() {
  2454. progressC?.stopAnimation()
  2455. self.view.km_endSheet()
  2456. progressC = nil
  2457. }
  2458. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2459. let newArr = NSMutableArray()
  2460. for item in files {
  2461. newArr.add(item.filePath)
  2462. }
  2463. return newArr as! [String]
  2464. }
  2465. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2466. self.saveDocument()
  2467. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2468. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2469. if (result == .cancel) {
  2470. return
  2471. }
  2472. // 解除权限
  2473. self?.listView.document.unlock(withPassword: password)
  2474. // 隐藏提示
  2475. self?.hiddenSecureLimitTip()
  2476. // 去打印
  2477. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  2478. }
  2479. return
  2480. }
  2481. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  2482. }
  2483. // MARK: - 图片注释
  2484. @IBAction func imageAnnotation(_ sender: Any) {
  2485. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  2486. changeAnnotationMode(sender)
  2487. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2488. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2489. return
  2490. }
  2491. let accessoryCtr = KMImageAccessoryController()
  2492. let openPanel = NSOpenPanel()
  2493. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2494. openPanel.allowsMultipleSelection = false
  2495. openPanel.accessoryView = accessoryCtr.view
  2496. openPanel.canSelectHiddenExtension = true
  2497. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2498. if result == .OK {
  2499. guard let url = openPanel.url else {
  2500. return
  2501. }
  2502. let filePath = url.path
  2503. if filePath.pathExtension.lowercased() == "pdf" {
  2504. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2505. NSSound.beep()
  2506. return
  2507. }
  2508. }
  2509. guard let image = NSImage(contentsOfFile: url.path) else {
  2510. let alert = NSAlert()
  2511. alert.alertStyle = .critical
  2512. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2513. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2514. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2515. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2516. if response == .alertFirstButtonReturn {
  2517. // Handle cancel button clicked
  2518. }
  2519. }
  2520. return
  2521. }
  2522. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  2523. if isDamageImage {
  2524. let alert = NSAlert()
  2525. alert.alertStyle = .critical
  2526. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2527. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2528. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2529. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2530. if response == .alertFirstButtonReturn {
  2531. // Handle cancel button clicked
  2532. }
  2533. }
  2534. return
  2535. }
  2536. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2537. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2538. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2539. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  2540. }
  2541. }
  2542. }
  2543. }
  2544. @IBAction func tableAnnotation(_ sender: Any) {
  2545. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2546. changeAnnotationMode(sender)
  2547. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2548. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2549. winC?.kEventName = "Reading_Table_BuyNow"
  2550. winC?.showWindow(nil)
  2551. return
  2552. }
  2553. listView.addAnnotationWithTable()
  2554. openRightPane()
  2555. }
  2556. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2557. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2558. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2559. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2560. }
  2561. if let data = image.tiffRepresentation,
  2562. let imageRep = NSBitmapImageRep(data: data) {
  2563. imageRep.size = image.size
  2564. var imageData: Data?
  2565. if path.lowercased() == "png" {
  2566. imageData = imageRep.representation(using: .png, properties: [:])
  2567. } else {
  2568. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2569. }
  2570. if let imageData = imageData {
  2571. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2572. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2573. return true
  2574. } else {
  2575. return false
  2576. }
  2577. }
  2578. }
  2579. return false
  2580. }
  2581. func tagString() -> String {
  2582. let dateFormatter = DateFormatter()
  2583. dateFormatter.dateFormat = "yyMMddHHmmss"
  2584. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2585. }
  2586. // MARK: - Split View
  2587. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2588. }
  2589. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2590. }
  2591. func updateBackAndForwardButtonState() {
  2592. }
  2593. }
  2594. // MARK: -
  2595. // MARK: - KMToolbarViewControllerDelegate
  2596. extension KMMainViewController : KMToolbarViewControllerDelegate {
  2597. func changeModelAction(mode: CToolMode) {
  2598. self.listView.toolMode = mode
  2599. if mode == .editPDFToolMode {
  2600. }
  2601. }
  2602. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  2603. switch selectedTag {
  2604. case 2:
  2605. if self.listView.scaleFactor != 1.0 {
  2606. self.listView.scaleFactor = 1.0
  2607. self.listView.autoScales = false
  2608. }
  2609. break
  2610. case 1:
  2611. let pageHeight = self.listView.currentPage()!.size.height
  2612. let pdfviewHeight = self.listView.bounds.size.height
  2613. self.listView.scaleFactor = pdfviewHeight/pageHeight
  2614. self.listView.autoScales = false
  2615. break
  2616. case 0:
  2617. self.listView.autoScales = true
  2618. break
  2619. case 3:
  2620. self.listView.scaleFactor = 0.1
  2621. break
  2622. case 4:
  2623. self.listView.scaleFactor = 0.25
  2624. break
  2625. case 5:
  2626. self.listView.scaleFactor = 0.5
  2627. break
  2628. case 6:
  2629. self.listView.scaleFactor = 0.75
  2630. break
  2631. case 7:
  2632. self.listView.scaleFactor = 1.0
  2633. break
  2634. case 8:
  2635. self.listView.scaleFactor = 1.5
  2636. break
  2637. case 9:
  2638. self.listView.scaleFactor = 2.0
  2639. break
  2640. case 10:
  2641. self.listView.scaleFactor = 4.0
  2642. break
  2643. case 11:
  2644. self.listView.scaleFactor = 8.0
  2645. break
  2646. case 12:
  2647. self.listView.scaleFactor = 16.0
  2648. break
  2649. case 13:
  2650. self.listView.scaleFactor = 32.0
  2651. break
  2652. case 14:
  2653. self.listView.scaleFactor = 64.0
  2654. break
  2655. case 15:
  2656. self.listView.scaleFactor = 100.0
  2657. break
  2658. default:
  2659. break
  2660. }
  2661. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2662. if self.digitalSignController?.pdfView != nil {
  2663. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  2664. }
  2665. if self.redactController?.redactPdfView != nil {
  2666. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  2667. }
  2668. }
  2669. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  2670. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2671. if scale > 100 {
  2672. scale = 100
  2673. }
  2674. if (scale <= 0.101) {
  2675. self.listView.scaleFactor = self.listView.minScaleFactor()
  2676. } else {
  2677. self.listView.scaleFactor = scale
  2678. }
  2679. if self.digitalSignController?.pdfView != nil {
  2680. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  2681. }
  2682. if self.redactController?.redactPdfView != nil {
  2683. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  2684. }
  2685. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2686. }
  2687. func changePDFViewZoomInAction() {
  2688. }
  2689. func changePDFViewZoomOutAction() {
  2690. }
  2691. func changePDFViewGotoNextPageAction() {
  2692. self.listView.km_goBack(nil)
  2693. if (self.listView.canGoToNextPage()) {
  2694. self.listView.goToNextPage(nil)
  2695. }
  2696. }
  2697. func changePDFViewGoToPreviousPageAction() {
  2698. if (self.listView.canGoToPreviousPage()) {
  2699. self.listView.goToPreviousPage(nil)
  2700. }
  2701. }
  2702. func changePDFViewGotoBackAction() {
  2703. self.listView.km_goBack(nil)
  2704. self.updateBackAndForwardButtonState()
  2705. }
  2706. func changePDFViewGoToForwardAction() {
  2707. self.listView.km_goForward(nil)
  2708. self.updateBackAndForwardButtonState()
  2709. }
  2710. func aiTranslationPDFFileAction() {
  2711. #if VERSION_DMG
  2712. #else
  2713. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  2714. KMLoginWindowController.show(window: NSApp.mainWindow!)
  2715. return
  2716. }
  2717. #endif
  2718. self.trackEvent_aiTranslate()
  2719. self._aiTranslationPDFFileAction()
  2720. }
  2721. private func _aiTranslationPDFFileAction() {
  2722. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2723. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2724. let alert = NSAlert()
  2725. alert.alertStyle = .critical
  2726. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2727. alert.runModal()
  2728. return
  2729. } else if isExceedsLimit {
  2730. let alert = NSAlert()
  2731. alert.alertStyle = .critical
  2732. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2733. alert.runModal()
  2734. return
  2735. }
  2736. let alert = NSAlert()
  2737. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2738. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2739. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2740. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2741. if (result == .alertFirstButtonReturn) {
  2742. } else if result == .alertSecondButtonReturn {
  2743. return
  2744. }
  2745. }
  2746. }
  2747. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2748. self.trackEvent_share()
  2749. }
  2750. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2751. self.shareDocument(sender: viewController)
  2752. }
  2753. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2754. if IAPProductsManager.default().isAvailableAllFunction() == false {
  2755. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2756. winC?.kEventName = "Reading_Flatten_BuyNow"
  2757. winC?.showWindow(nil)
  2758. return
  2759. }
  2760. self.shareFlatten(sender: viewController)
  2761. }
  2762. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2763. self.shareOriginalPDF(sender: viewController)
  2764. }
  2765. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2766. if(0 == selectedTag) {
  2767. } else {
  2768. }
  2769. }
  2770. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2771. if beforeType == .editPDF {
  2772. self.editPDFHanddler.enterEditPDF()
  2773. }
  2774. if(type != .Page) {
  2775. if (hasEnterPageEdit()) {
  2776. self.exitPageEdit()
  2777. }
  2778. }
  2779. if type != .redact {
  2780. if self.hasEnterRedact() {
  2781. self.exitRedact()
  2782. }
  2783. }
  2784. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  2785. if self.hasShowDigitalSign() {
  2786. self.exitDigitalSign()
  2787. }
  2788. }
  2789. if item.itemIdentifier != KMDocumentViewDisplayToolbarItemIdentifier {
  2790. }
  2791. if(type != .Form) {
  2792. self.removeFromAlertView()
  2793. }
  2794. if (type == .Page) {
  2795. if (hasEnterPageEdit()) {
  2796. self.exitPageEdit()
  2797. } else {
  2798. self.enterPageEdit(pages)
  2799. }
  2800. } else if type == .editPDF {
  2801. self.enterEditPDF()
  2802. } else if type == .Annatiton {
  2803. self.rightSideViewController.subViewType = .AnnotationProperts
  2804. } else if type == .redact {
  2805. if self.needSaveDocument() {
  2806. self.saveDocumentWithProgressAlert { [unowned self] params in
  2807. self.enterRedact()
  2808. }
  2809. return
  2810. }
  2811. let isEdited = self.listView.isEdited()
  2812. let isPDFTextImageEdited = self.model.isPDFTextImageEdited
  2813. if isEdited || isPDFTextImageEdited {
  2814. self.enterRedact()
  2815. } else {
  2816. self.enterRedact()
  2817. }
  2818. } else if type == .Tool {
  2819. if KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  2820. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  2821. } else if KMGuideInfoWindowController.availableShow(.measureGuide) {
  2822. self.loadOpenFileFunctionGuide(.measureGuide)
  2823. }
  2824. } else if type == . Conversion {
  2825. self.loadOpenFileFunctionGuide(.convertGuide)
  2826. }else if type == .Form {
  2827. self.showFormAlertView()
  2828. }else if type == .Select {
  2829. self.rightSideViewController.isHidden = true
  2830. self.closeRightPane()
  2831. }
  2832. }
  2833. func clickChildTool(type: KMToolbarType, index: Int) {
  2834. if (type == .secure) {
  2835. if (index == 1) {
  2836. self.trackEvent_setPassword()
  2837. } else if (index == 2) {
  2838. self.trackEvent_removePassword()
  2839. }
  2840. } else {
  2841. self.trackEvent(toolBarType: type)
  2842. }
  2843. Task { @MainActor in
  2844. if (type == .compress) { /// 压缩
  2845. if !self.documentAllowsEdit() {
  2846. return
  2847. }
  2848. if (self.needSaveDocument()) {
  2849. self.saveDocumentWithProgressAlert { [unowned self] params in
  2850. self.showCompressWindow()
  2851. }
  2852. return
  2853. }
  2854. self.showCompressWindow()
  2855. return
  2856. }
  2857. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  2858. if type == .conversion_imageToPDF {
  2859. Task {
  2860. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  2861. }
  2862. return
  2863. }
  2864. var identifier: String?
  2865. if (type == .word) { /// Word
  2866. identifier = KMToolbarConversionWordItemIdentifier
  2867. } else if (type == .excel) {
  2868. identifier = KMToolbarConversionExcelItemIdentifier
  2869. } else if (type == .ppt) {
  2870. identifier = KMToolbarConversionPPTItemIdentifier
  2871. } else if (type == .rtf) {
  2872. identifier = KMToolbarConversionRTFItemIdentifier
  2873. } else if (type == .html) {
  2874. identifier = KMToolbarConversionHTMLItemIdentifier
  2875. } else if (type == .conversion_text) {
  2876. identifier = KMToolbarConversionTextItemIdentifier
  2877. } else if (type == .csv) {
  2878. identifier = KMToolbarConversionCSVItemIdentifier
  2879. } else if (type == .conversion_image) {
  2880. identifier = KMToolbarConversionImageItemIdentifier
  2881. }
  2882. if (self.needSaveDocument()) {
  2883. self.saveDocumentWithProgressAlert { [unowned self] params in
  2884. self.showConvertWindow(type: type, identifier: identifier)
  2885. }
  2886. return
  2887. }
  2888. self.showConvertWindow(type: type, identifier: identifier)
  2889. return
  2890. }
  2891. if (type == .merge) { /// 合并
  2892. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  2893. if !self.documentAllowsEdit() {
  2894. return
  2895. }
  2896. if (self.needSaveDocument()) {
  2897. self.saveDocumentWithProgressAlert { [unowned self] params in
  2898. self.showMergeWindow(self.listView.document.password)
  2899. }
  2900. return
  2901. }
  2902. self.showMergeWindow(self.listView.document.password)
  2903. return
  2904. }
  2905. if (type == .bates || type == .headerAndFooter) {
  2906. if !IAPProductsManager.default().isAvailableAllFunction(){
  2907. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2908. if type == .headerAndFooter {
  2909. if index == 1 {
  2910. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  2911. } else if index == 2 {
  2912. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  2913. }
  2914. } else if type == .bates {
  2915. if index == 1 {
  2916. winC?.kEventName = "Reading_AddBates_BuyNow"
  2917. } else if index == 2 {
  2918. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  2919. }
  2920. }
  2921. winC?.showWindow(nil)
  2922. return
  2923. }
  2924. if !self.documentAllowsEdit() {
  2925. return
  2926. }
  2927. if (index == 1) {
  2928. var windowController: KMBaseWindowController = KMBaseWindowController()
  2929. if (type == .bates) {
  2930. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2931. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2932. let fpath = self.document?.documentURL?.path ?? ""
  2933. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2934. }
  2935. windowController.isBates = true
  2936. } else if (type == .headerAndFooter) {
  2937. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2938. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2939. let fpath = self.document?.documentURL?.path ?? ""
  2940. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2941. }
  2942. } else if (type == .background) {
  2943. } else if (type == .watermark) {
  2944. }
  2945. windowController.pdfDocument = self.listView.document
  2946. windowController.cancelAction = { [unowned self] controller in
  2947. self.view.window?.endSheet((self.currentWindowController.window)!)
  2948. self.currentWindowController = nil
  2949. }
  2950. self.currentWindowController = windowController
  2951. await self.view.window?.beginSheet(windowController.window!)
  2952. return
  2953. }
  2954. if (index == 1) { /// 取消
  2955. self.rightSideViewController.isHidden = true
  2956. self.rightSideViewController.subViewType = .None
  2957. self.closeRightPane()
  2958. return
  2959. } else if index == 3 {
  2960. let fpath = self.document?.documentURL?.path ?? ""
  2961. if type == .bates {
  2962. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2963. } else {
  2964. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2965. }
  2966. } else if index == 4 {
  2967. let fpath = self.document?.documentURL?.path ?? ""
  2968. if type == .bates {
  2969. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  2970. } else {
  2971. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  2972. }
  2973. } else if (index == 2) { //// 移除
  2974. if type == .headerAndFooter {
  2975. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2976. let savePanel = NSSavePanel()
  2977. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2978. savePanel.allowedFileTypes = ["pdf"]
  2979. savePanel.accessoryView = savePanelAccessoryViewController.view
  2980. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2981. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2982. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2983. if success == 1 && savePanel.url?.path == self.listView.document?.documentURL.path {
  2984. self.setDocument = CPDFDocument(url: savePanel.url!)
  2985. return
  2986. }
  2987. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2988. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2989. }
  2990. } else {
  2991. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2992. }
  2993. }
  2994. }
  2995. }
  2996. } else if type == .bates {
  2997. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2998. let savePanel = NSSavePanel()
  2999. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3000. savePanel.allowedFileTypes = ["pdf"]
  3001. savePanel.accessoryView = savePanelAccessoryViewController.view
  3002. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3003. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3004. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3005. if success == 1 && savePanel.url?.path == self.listView.document?.documentURL.path {
  3006. self.setDocument = CPDFDocument(url: savePanel.url!)
  3007. return
  3008. }
  3009. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3010. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3011. }
  3012. } else {
  3013. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3014. }
  3015. }
  3016. }
  3017. }
  3018. }
  3019. return
  3020. } else if (index == 2) { /// 应用
  3021. let model = self.rightSideViewController.model
  3022. if (type == .bates || type == .headerAndFooter) {
  3023. if (model == nil || (model?.isKind(of: KMHeaderFooterObject.self) == false)) {
  3024. let alert = NSAlert()
  3025. alert.alertStyle = .critical
  3026. alert.messageText = "没有找到模型"
  3027. alert.runModal()
  3028. return
  3029. }
  3030. // if ((model as! KMHeaderFooterObject).hasVaild == false) {
  3031. // let alert = NSAlert()
  3032. // alert.alertStyle = .critical
  3033. // alert.messageText = "没有找到内容"
  3034. // alert.runModal()
  3035. // return
  3036. // }
  3037. }
  3038. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  3039. result in
  3040. DispatchQueue.main.async {
  3041. self.listView.layoutDocumentView()
  3042. self.listView.setNeedsDisplayForVisiblePages()
  3043. }
  3044. if (result) {
  3045. let alert = NSAlert()
  3046. alert.alertStyle = .warning
  3047. alert.messageText = "成功"
  3048. alert.runModal()
  3049. } else {
  3050. let alert = NSAlert()
  3051. alert.alertStyle = .critical
  3052. alert.messageText = "失败"
  3053. alert.runModal()
  3054. }
  3055. }
  3056. return
  3057. } else if index == 5 {
  3058. self.rightSideViewController.isHidden = false
  3059. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3060. self.openRightPane()
  3061. }
  3062. } else if (type == .redact) { /// 标记密文
  3063. if !IAPProductsManager.default().isAvailableAllFunction(){
  3064. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3065. return
  3066. }
  3067. if (index == 1) { /// 取消
  3068. if (self.model.hasAddRedact) {
  3069. let alert = NSAlert()
  3070. 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: "")
  3071. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  3072. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3073. let result = alert.runModal()
  3074. if (result == .alertFirstButtonReturn) {
  3075. self.listView.toolMode = .moveToolMode
  3076. }
  3077. return
  3078. }
  3079. self.listView.toolMode = .moveToolMode
  3080. return
  3081. }
  3082. if (index == 2) { /// 擦除
  3083. self.exeRedactConfirm(.eraserAll) {}
  3084. return
  3085. }
  3086. if (index == 3) { /// 应用
  3087. self.exeRedactConfirm(.redactAll) {}
  3088. return
  3089. }
  3090. if (index == 4) { /// 文本&图像
  3091. self.listView.toolMode = .redactToolMode
  3092. return
  3093. }
  3094. if (index == 5) { /// 页面
  3095. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3096. await self.view.window?.beginSheet(windowController.window!)
  3097. self.currentWindowController = windowController
  3098. windowController.itemClick = { [weak self] index, value in
  3099. if (index == 1) {
  3100. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3101. self?.currentWindowController = nil
  3102. return
  3103. }
  3104. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3105. let pageType = windowController_pageRange.pageType
  3106. let pageString = windowController_pageRange.pageString
  3107. if (pageType == 5) { /// 自定义页面
  3108. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  3109. if (array.count == 0) {
  3110. let alert = NSAlert()
  3111. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3112. alert.runModal()
  3113. return
  3114. }
  3115. }
  3116. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3117. self!.currentWindowController = nil
  3118. var indexs: IndexSet = []
  3119. if (pageType == 1) { /// 当前页面
  3120. indexs.insert((self?.listView.currentPageIndex)!)
  3121. } else {
  3122. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  3123. }
  3124. if (indexs.count == 0) {
  3125. return
  3126. }
  3127. for i in indexs {
  3128. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3129. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3130. redactAnno.bounds = page.bounds
  3131. self?.listView.add(redactAnno, to: page)
  3132. }
  3133. }
  3134. return
  3135. }
  3136. } else if (type == .secure) { /// 安全
  3137. if (index == 1) { /// 设置密码
  3138. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3139. if !self.documentAllowsEdit() {
  3140. return
  3141. }
  3142. }
  3143. self.showSecureWindow(self.listView.document.documentURL)
  3144. return
  3145. } else if index == 2 {
  3146. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3147. let alert = NSAlert()
  3148. alert.alertStyle = .warning
  3149. alert.messageText = NSLocalizedString("Warning", comment: "")
  3150. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3151. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3152. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3153. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3154. if returnCode == .alertSecondButtonReturn {
  3155. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3156. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3157. if success {
  3158. self.document?.unlock(withPassword: resultPassword)
  3159. self.clickChildTool(type: .secure, index: 2)
  3160. }
  3161. }
  3162. }
  3163. }
  3164. }
  3165. } else {
  3166. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3167. controller.pdfDocument = self.document
  3168. self.currentWindowController = controller
  3169. controller.batchAction = { [unowned self] controller, files in
  3170. self.view.window?.endSheet((self.currentWindowController.window)!)
  3171. self.currentWindowController = nil
  3172. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  3173. if #available(macOS 10.13, *) {
  3174. baseWindowController.window?.makeKeyAndOrderFront(nil)
  3175. } else {
  3176. baseWindowController.showWindow(nil)
  3177. }
  3178. let arr = NSMutableArray()
  3179. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  3180. file.password = document?.password ?? ""
  3181. arr.add(file)
  3182. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  3183. }
  3184. controller.cancelAction = { [unowned self] controller in
  3185. self.view.window?.endSheet((self.currentWindowController.window)!)
  3186. self.currentWindowController = nil
  3187. }
  3188. controller.doneAction = { [unowned self] controller in
  3189. self.view.window?.endSheet((self.currentWindowController.window)!)
  3190. self.currentWindowController = nil
  3191. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  3192. if success {
  3193. let savePanel = NSSavePanel()
  3194. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  3195. savePanel.allowedFileTypes = ["pdf"]
  3196. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  3197. guard result == .OK else { return }
  3198. /// 删除安全性设置
  3199. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3200. self.model.isSaveKeyChain = false
  3201. self.listView.document.unlock(withPassword: resultPassword)
  3202. }
  3203. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  3204. guard let document = document else { return }
  3205. document.unlock(withPassword: resultPassword)
  3206. let success = document.writeDecrypt(to: savePanel.url)
  3207. if success {
  3208. self.hiddenSecureLimitTip()
  3209. let tip = KMRemovePasswordResultTipView()
  3210. tip.result = .success
  3211. tip.showInView(superView: (self.listView.superview)!)
  3212. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3213. } else {
  3214. self.hiddenSecureLimitTip()
  3215. let tip = KMRemovePasswordResultTipView()
  3216. tip.result = .failure
  3217. tip.showInView(superView: (self.listView.superview)!)
  3218. }
  3219. }
  3220. }
  3221. }
  3222. }
  3223. await NSWindow.currentWindow().beginSheet(controller.window!)
  3224. }
  3225. return
  3226. }
  3227. } else if type == .comparison {
  3228. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  3229. if !IAPProductsManager.default().isAvailableAllFunction(){
  3230. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3231. winC?.kEventName = "Reading_Compare_BuyNow"
  3232. winC?.showWindow(nil)
  3233. return
  3234. }
  3235. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3236. self.currentWindowController = controller
  3237. controller.password = self.document?.password ?? ""
  3238. controller.filePath = (self.document?.documentURL.path)!
  3239. controller.cancelAction = { [unowned self] controller in
  3240. self.view.window?.endSheet((self.currentWindowController.window)!)
  3241. self.currentWindowController = nil
  3242. }
  3243. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3244. self.view.window?.endSheet((self.currentWindowController.window)!)
  3245. self.currentWindowController = nil
  3246. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3247. }
  3248. controller.coveringComplete = { [unowned self] controller, document in
  3249. self.view.window?.endSheet((self.currentWindowController.window)!)
  3250. self.currentWindowController = nil
  3251. self.openCoveringCompareVC(with: document)
  3252. }
  3253. if index == 1 {
  3254. controller.fileType = .content
  3255. } else {
  3256. controller.fileType = .coverting
  3257. }
  3258. await NSWindow.currentWindow().beginSheet(controller.window!)
  3259. } else if type == .watermark {
  3260. if !IAPProductsManager.default().isAvailableAllFunction(){
  3261. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3262. if index == 1 {
  3263. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  3264. } else if index == 2 {
  3265. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  3266. }
  3267. winC?.showWindow(nil)
  3268. return
  3269. }
  3270. if !self.documentAllowsEdit() {
  3271. return
  3272. }
  3273. if index == 1 {
  3274. } else if index == 2 {
  3275. let watermarks = self.listView.document.watermarks()
  3276. if (watermarks == nil || watermarks!.count <= 0) {
  3277. let alert = NSAlert()
  3278. alert.alertStyle = .warning
  3279. alert.messageText = NSLocalizedString("Could not find a removable watermark in this document. If you see a watermark, it was not added with PDF Reader Pro and therefore cannot be detected.", comment: "")
  3280. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  3281. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3282. alert.runModal()
  3283. return
  3284. }
  3285. let alert = NSAlert()
  3286. alert.alertStyle = .warning
  3287. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  3288. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  3289. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3290. let result = alert.runModal()
  3291. if (result != .alertFirstButtonReturn) {
  3292. return
  3293. }
  3294. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3295. let savePanel = NSSavePanel()
  3296. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  3297. savePanel.allowedFileTypes = ["pdf"]
  3298. savePanel.accessoryView = savePanelAccessoryViewController.view
  3299. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3300. guard result == .OK else { return }
  3301. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  3302. KMWatermarkAdjectiveTools.delete(oType, self.listView, savePanel.url!.path) {
  3303. result in
  3304. DispatchQueue.main.async {
  3305. self.listView.layoutDocumentView()
  3306. self.listView.setNeedsDisplayForVisiblePages()
  3307. }
  3308. if (result) {
  3309. let alert = NSAlert()
  3310. alert.alertStyle = .warning
  3311. alert.messageText = NSLocalizedString("Finish", comment: "")
  3312. alert.runModal()
  3313. if savePanel.url?.path == self.listView.document?.documentURL.path {
  3314. self.setDocument = CPDFDocument(url: savePanel.url!)
  3315. return
  3316. }
  3317. let needOpen = savePanelAccessoryViewController.needOpen
  3318. if needOpen {
  3319. NSDocumentController.shared.km_safe_openDocument(withContentsOf: savePanel.url!, display: true) { document, hasOpen, err in }
  3320. } else {
  3321. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3322. }
  3323. } else {
  3324. let alert = NSAlert()
  3325. alert.alertStyle = .critical
  3326. alert.messageText = NSLocalizedString("Failed", comment: "")
  3327. alert.runModal()
  3328. }
  3329. }
  3330. }
  3331. } else if index == 3 {
  3332. let fpath = self.document?.documentURL?.path ?? ""
  3333. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  3334. } else if index == 4 {
  3335. let fpath = self.document?.documentURL?.path ?? ""
  3336. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  3337. } else if index == 5 {
  3338. self.rightSideViewController.isHidden = false
  3339. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3340. self.openRightPane()
  3341. return
  3342. }
  3343. } else if type == .background {
  3344. if !IAPProductsManager.default().isAvailableAllFunction(){
  3345. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3346. if index == 1 {
  3347. winC?.kEventName = "Reading_AddBackground_BuyNow"
  3348. } else if index == 2 {
  3349. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  3350. }
  3351. winC?.showWindow(nil)
  3352. return
  3353. }
  3354. if !self.documentAllowsEdit() {
  3355. return
  3356. }
  3357. if index == 1 {
  3358. } else if index == 2 {
  3359. guard let document = self.document else { return }
  3360. if !document.allowsPrinting || !document.allowsCopying {
  3361. let alert = NSAlert()
  3362. alert.alertStyle = .critical
  3363. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3364. alert.runModal()
  3365. return
  3366. }
  3367. guard let documentURL = document.documentURL else { return }
  3368. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3369. let savePanel = NSSavePanel()
  3370. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  3371. savePanel.allowedFileTypes = ["pdf"]
  3372. savePanel.accessoryView = savePanelAccessoryViewController.view
  3373. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3374. guard result == .OK else { return }
  3375. }
  3376. } else if index == 3 {
  3377. let fpath = self.document?.documentURL?.path ?? ""
  3378. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  3379. } else if index == 4 {
  3380. let fpath = self.document?.documentURL?.path ?? ""
  3381. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  3382. } else if index == 5 {
  3383. self.rightSideViewController.isHidden = false
  3384. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3385. self.openRightPane()
  3386. return
  3387. }
  3388. } else if type == .measure {
  3389. if !IAPProductsManager.default().isAvailableAllFunction(){
  3390. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3391. winC?.kEventName = "Reading_Measure_BuyNow"
  3392. winC?.showWindow(nil)
  3393. return
  3394. }
  3395. if !self.documentAllowsEdit() {
  3396. return
  3397. }
  3398. self.listView.toolMode = .measureToolMode
  3399. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  3400. distanceMeasureInfoWindowController?.hideFloatingWindow()
  3401. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  3402. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  3403. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  3404. areaMeasureInfoWindowController?.hideFloatingWindow()
  3405. }
  3406. if distanceMeasureInfoWindowController == nil {
  3407. let measureInfo = CPDFDistanceMeasureInfo()
  3408. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  3409. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  3410. distanceMeasureInfoWindowController?.delegate = self
  3411. }
  3412. if perimeterMeasureInfoWindowController == nil {
  3413. let measureInfo = CPDFPerimeterMeasureInfo()
  3414. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  3415. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  3416. perimeterMeasureInfoWindowController?.delegate = self
  3417. }
  3418. if areaMeasureInfoWindowController == nil {
  3419. let measureInfo = CPDFAreaMeasureInfo()
  3420. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  3421. areaMeasureInfoWindowController?.measureInfo = measureInfo
  3422. areaMeasureInfoWindowController?.delegate = self
  3423. }
  3424. if index == 1 {
  3425. self.listView.annotationType = .line
  3426. let winW: CGFloat = 300
  3427. let rightW: CGFloat = 270
  3428. var winFrame = self.view.window?.frame ?? .zero
  3429. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3430. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3431. distanceMeasureInfoWindowController?.showWindow(nil)
  3432. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3433. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  3434. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  3435. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  3436. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3437. self.trackEvent(toolMode: .measureToolMode)
  3438. } else if index == 2 {
  3439. self.listView.annotationType = .polyLine
  3440. let winW: CGFloat = 300
  3441. let rightW: CGFloat = 270
  3442. var winFrame = self.view.window?.frame ?? .zero
  3443. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3444. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3445. perimeterMeasureInfoWindowController?.showWindow(nil)
  3446. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3447. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  3448. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3449. self.trackEvent(toolMode: .measureToolMode)
  3450. } else if index == 3 {
  3451. self.listView.annotationType = .polyGon
  3452. let winW: CGFloat = 300
  3453. let rightW: CGFloat = 270
  3454. var winFrame = self.view.window?.frame ?? .zero
  3455. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3456. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3457. areaMeasureInfoWindowController?.showWindow(nil)
  3458. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3459. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3460. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3461. self.trackEvent(toolMode: .measureToolMode)
  3462. } else if index == 4 {
  3463. self.listView.annotationType = .square
  3464. let winW: CGFloat = 300
  3465. let rightW: CGFloat = 270
  3466. var winFrame = self.view.window?.frame ?? .zero
  3467. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3468. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3469. areaMeasureInfoWindowController?.showWindow(nil)
  3470. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3471. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3472. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3473. self.trackEvent(toolMode: .measureToolMode)
  3474. } else {
  3475. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  3476. distanceMeasureInfoWindowController?.hideFloatingWindow()
  3477. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  3478. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  3479. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  3480. areaMeasureInfoWindowController?.hideFloatingWindow()
  3481. }
  3482. }
  3483. self.rightSideViewController.reloadDataWithPDFView(pdfView: listView, isShow: true)
  3484. self.openRightPane()
  3485. }
  3486. }
  3487. }
  3488. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  3489. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3490. var array: [KMBatchOperateFile] = []
  3491. for fpath in filepaths ?? [] {
  3492. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  3493. array.append(batchOperateFile)
  3494. }
  3495. batchWindowController.switchToOperateType(type, files: array)
  3496. batchWindowController.window?.makeKeyAndOrderFront("")
  3497. }
  3498. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  3499. self.toolbarItemClickForExitMode(toolbarItem)
  3500. if let itemID = toolbarItem.itemIdentifier {
  3501. if isMainToolItem(itemID) {
  3502. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  3503. openNewWindowAlertWindow()
  3504. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  3505. self.changePDFViewGoToPreviousPageAction()
  3506. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3507. let isSelected = toolbarItem.isSelected
  3508. toolbarItem.isSelected = !isSelected
  3509. if toolbarItem.isSelected {
  3510. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  3511. self.rightSideViewController.isHidden = false
  3512. self.rightSideViewController.mainController = self
  3513. self.rightSideViewController.subViewType = .ViewSettings
  3514. self.openRightPane()
  3515. }else{
  3516. self.rightSideViewController.isHidden = true
  3517. self.rightSideViewController.subViewType = .AnnotationProperts
  3518. closeRightPane()
  3519. }
  3520. if toolbarItem.isSelected {
  3521. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  3522. }
  3523. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  3524. toolbarItem.isSelected = !toolbarItem.isSelected
  3525. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  3526. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3527. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  3528. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  3529. }
  3530. toolbarItem.isSelected = !toolbarItem.isSelected
  3531. self.toggleRightPane()
  3532. if self.listView.toolMode == .editPDFToolMode {
  3533. self.editPDFHanddler.rightSideLastState = toolbarItem.isSelected ? .open : .close
  3534. }
  3535. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  3536. self.listView.toolMode = .redactToolMode
  3537. self.enterRedact()
  3538. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  3539. showOCRWindow()
  3540. } else if itemID == KMDocumentAIToolsToolbarItemIdentifier {
  3541. self.showAITypeChooseView(aiConfigType: .none)
  3542. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  3543. if self.canEnterDigitalSign() == false {
  3544. Task {
  3545. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3546. }
  3547. return
  3548. }
  3549. toolbarItem.isSelected = !toolbarItem.isSelected
  3550. if toolbarItem.isSelected {
  3551. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3552. }
  3553. self.enterDigitalSign()
  3554. } else if itemID == KMDocumentPrintToolbarItemIdentifier {
  3555. self.showPrintWindow()
  3556. } else if itemID == KMDocumentPresentationToolbarItemIdentifier {
  3557. self.togglePresentation(nil)
  3558. } else if itemID == KMDocumentSignToolbarItemIdentifier {
  3559. let isSelected = toolbarItem.isSelected
  3560. toolbarItem.isSelected = !isSelected
  3561. }
  3562. } else {
  3563. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  3564. toolbarItem.isSelected = false
  3565. let windowC = KMToolbarCustomWindowController()
  3566. windowC.resetCallback = { [weak self] in
  3567. }
  3568. self.km_beginSheet(windowC: windowC) { [weak self] resp, obj in
  3569. if resp == .OK {
  3570. }
  3571. }
  3572. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  3573. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  3574. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  3575. self.trackEvent_print()
  3576. self.showPrintWindow()
  3577. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  3578. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  3579. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  3580. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  3581. windowC.callBack = { [weak self] string in
  3582. if (string.isEmpty == false) {
  3583. self?.listView.addTextField(subType: .profile, string: string)
  3584. }
  3585. self?.km_endSheet()
  3586. }
  3587. self.km_beginSheet(windowC: windowC)
  3588. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  3589. toolbarItem.isSelected = !toolbarItem.isSelected
  3590. rightSideViewController.mainController = self
  3591. self.rightSideViewController.isHidden = toolbarItem.isSelected ? false : true
  3592. self.rightSideViewController.subViewType = .ViewSettings
  3593. self.listView.annotationType = .unkown
  3594. if toolbarItem.isSelected {
  3595. self.rightSideViewController.isHidden = false
  3596. self.rightSideViewController.mainController = self
  3597. self.rightSideViewController.subViewType = .ViewSettings
  3598. self.openRightPane()
  3599. }else{
  3600. self.rightSideViewController.isHidden = true
  3601. self.rightSideViewController.subViewType = .AnnotationProperts
  3602. closeRightPane()
  3603. }
  3604. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  3605. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  3606. self.listView.takeSnapshot(nil)
  3607. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  3608. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  3609. self.listView.annotationType = .unkown
  3610. self.showTTSWindow()
  3611. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  3612. self.showOCRWindow()
  3613. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  3614. toolbarItem.isSelected = false
  3615. self.imageAnnotation(toolbarItem)
  3616. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  3617. self.tableAnnotation(toolbarItem)
  3618. } else if toolbarItem.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { // 插入
  3619. self.leftSideViewController.insertPDF(nil)
  3620. } else if toolbarItem.itemIdentifier == KMToolbarPageEditSplitItemIdentifier { // 拆分
  3621. let windowC = SplitWindowController(document: self.listView.document)
  3622. self.km_beginSheet(windowC: windowC)
  3623. } else if itemID == KMSignDigitalSignToolbarItemIdentifier {
  3624. if self.canEnterDigitalSign() == false {
  3625. Task {
  3626. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3627. }
  3628. return
  3629. }
  3630. toolbarItem.isSelected = !toolbarItem.isSelected
  3631. if toolbarItem.isSelected {
  3632. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3633. }
  3634. self.enterDigitalSign()
  3635. } else if itemID == KMToolbarMeasureItemIdentifier {
  3636. if toolbarItem.isSelected {
  3637. toolbarItem.isSelected = false
  3638. self.listView.toolMode = .textToolMode
  3639. self.listView.annotationType = .unkown
  3640. }
  3641. }
  3642. }
  3643. }
  3644. }
  3645. func openNewWindowAlertWindow() {
  3646. var needShowChooseWindow = false
  3647. //#if VERSION_FREE
  3648. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  3649. needShowChooseWindow = true
  3650. }
  3651. //#endif
  3652. if needShowChooseWindow {
  3653. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  3654. if preferenceNoteShow {
  3655. menuItemAction_newTagPageToNewWindow("")
  3656. } else {
  3657. if !KMDataManager.default.isTabbingWin{
  3658. KMDataManager.default.isTabbingWin = true
  3659. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  3660. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  3661. KMDataManager.default.isTabbingWin = false
  3662. if continueOrNot {
  3663. self?.reopenDocument(forPaths: [])
  3664. } else {
  3665. }
  3666. }
  3667. self.km_beginSheet(windowC: tabbingWin)
  3668. }
  3669. }
  3670. }else{
  3671. handleTabbingLogic()
  3672. }
  3673. }
  3674. func reopenDocument(forPaths paths: [String]) -> Void {
  3675. let browser = KMBrowser.init() as KMBrowser
  3676. browser.windowController = KMBrowserWindowController.init(browser: browser)
  3677. browser.addHomeTabContents()
  3678. browser.windowController.showWindow(self)
  3679. }
  3680. func handleTabbingLogic() {
  3681. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  3682. }
  3683. func showTTSWindow() {
  3684. var lastPDFView: CPDFView?
  3685. let ttsView = KMTTSWindowController.share
  3686. if (ttsView.window?.isVisible ?? false) {
  3687. lastPDFView = ttsView.pdfView
  3688. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  3689. lastPDFView = nil
  3690. ttsView.window?.orderOut(nil)
  3691. } else {
  3692. ttsView.pdfView = self.listView
  3693. ttsView.showWindow(nil)
  3694. }
  3695. } else {
  3696. ttsView.pdfView = self.listView
  3697. ttsView.showWindow(nil)
  3698. }
  3699. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  3700. if isCloseWindow {
  3701. }
  3702. }
  3703. if let currentSelection = self.listView.currentSelection {
  3704. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  3705. ttsView.startSpeakingPDFSelection(currentSelection)
  3706. }
  3707. }
  3708. if let lastPDFView = lastPDFView {
  3709. lastPDFView.setHighlightedSelections([])
  3710. ttsView.stopSpeaking()
  3711. }
  3712. }
  3713. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3714. self.toolbarItemClickForExitMode(toolbarItem)
  3715. let itemId = toolbarItem.itemIdentifier
  3716. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  3717. self.clickChildTool(type: .watermark, index: index)
  3718. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  3719. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  3720. self.clickChildTool(type: .background, index: index)
  3721. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  3722. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  3723. self.clickChildTool(type: .headerAndFooter, index: index)
  3724. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  3725. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  3726. self.clickChildTool(type: .bates, index: index)
  3727. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  3728. } else if (toolbarItem.itemIdentifier == KMToolbarMeasureItemIdentifier) {
  3729. self.clickChildTool(type: .measure, index: index)
  3730. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  3731. self.clickChildTool(type: .comparison, index: index)
  3732. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  3733. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  3734. convertToImg(index: index)
  3735. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  3736. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  3737. extractImageAction(num: index)
  3738. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  3739. self.createPdf(index: index)
  3740. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  3741. if index == 2 { // 裁剪当前页面
  3742. self.cropCurrentPage()
  3743. } else if index == 3 { // Auto Crop – Separate
  3744. self.smart_cropAllPage()
  3745. } else if index == 4 { // Auto Crop – Combined
  3746. self.auto_cropAllPage()
  3747. } else if index == 5 { // Select Area
  3748. }
  3749. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Crop"])
  3750. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  3751. self.clickChildTool(type: .secure, index: index)
  3752. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  3753. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  3754. if index == 11 {
  3755. self.view.window?.makeFirstResponder(nil)
  3756. let winC = KMSearchReplaceWindowController(with: self.listView, type: .search)
  3757. self.currentWindowController = winC
  3758. winC.replaceCallback = { [weak self] in
  3759. let toolMode = self?.listView.toolMode ?? .none
  3760. let isEditing = self?.listView.isEditing() ?? false
  3761. if toolMode == .editPDFToolMode && isEditing {
  3762. } else { // 进入内容编辑模式
  3763. }
  3764. }
  3765. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  3766. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  3767. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 248 - 16
  3768. let winFramePoint = NSPoint(x: x, y: y)
  3769. winC.window?.setFrameOrigin(winFramePoint)
  3770. winC.startModal(nil)
  3771. } else if index == 12 {
  3772. if IAPProductsManager.default().isAvailableAllFunction() == false {
  3773. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3774. winC?.kEventName = "Reading_ReplaceText_BuyNow"
  3775. winC?.showWindow(nil)
  3776. return
  3777. }
  3778. self.view.window?.makeFirstResponder(nil)
  3779. let toolMode = self.listView.toolMode ?? .none
  3780. let isEditing = self.listView.isEditing() ?? false
  3781. if toolMode == .editPDFToolMode && isEditing {
  3782. } else { // 进入内容编辑模式
  3783. }
  3784. self.trackEvent_replace()
  3785. let winC = KMSearchReplaceWindowController(with: self.listView, type: .replace)
  3786. self.currentWindowController = winC
  3787. winC.replaceCallback = { [weak self] in
  3788. let toolMode = self?.listView.toolMode ?? .none
  3789. let isEditing = self?.listView.isEditing() ?? false
  3790. if toolMode == .editPDFToolMode && isEditing {
  3791. } else { // 进入内容编辑模式
  3792. }
  3793. }
  3794. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  3795. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  3796. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 388
  3797. let winFramePoint = NSPoint(x: x, y: y)
  3798. winC.window?.setFrameOrigin(winFramePoint)
  3799. winC.startModal(nil)
  3800. } else {
  3801. }
  3802. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3803. toolbarItem.isSelected = !toolbarItem.isSelected
  3804. self.toggleRightPane()
  3805. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3806. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  3807. self.showOCRWindow()
  3808. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  3809. if index == 1 {
  3810. self.showAITypeChooseView(aiConfigType: .summarize)
  3811. } else if index == 2 {
  3812. self.showAITypeChooseView(aiConfigType: .reWriting)
  3813. } else if index == 3 {
  3814. self.showAITypeChooseView(aiConfigType: .proofreading)
  3815. } else if index == 4 {
  3816. self.showAITypeChooseView(aiConfigType: .translate)
  3817. }
  3818. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  3819. self.showOCRWindow()
  3820. } else if toolbarItem.itemIdentifier == KMDocumentEditToolbarItemIdentifier {
  3821. self.enterEditPDF()
  3822. } else if toolbarItem.itemIdentifier == KMDocumentFillSginToolbarItemIdentifier {
  3823. } else if toolbarItem.itemIdentifier == KMDocumentFormToolbarItemIdentifier {
  3824. } else if itemId == KMDocumentDigitalSignToolbarItemIdentifier {
  3825. if self.canEnterDigitalSign() == false {
  3826. Task {
  3827. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3828. }
  3829. return
  3830. }
  3831. toolbarItem.isSelected = !toolbarItem.isSelected
  3832. if toolbarItem.isSelected {
  3833. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3834. }
  3835. self.enterDigitalSign()
  3836. } else if itemId == KMSignDigitalSignToolbarItemIdentifier {
  3837. if self.canEnterDigitalSign() == false {
  3838. Task {
  3839. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3840. }
  3841. return
  3842. }
  3843. toolbarItem.isSelected = !toolbarItem.isSelected
  3844. if toolbarItem.isSelected {
  3845. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3846. }
  3847. self.enterDigitalSign()
  3848. } else if itemId == KMDocumentAIToolsToolbarItemIdentifier {
  3849. self.showAITypeChooseView(aiConfigType: .none)
  3850. } else if itemId == KMToolbarToolCompressItemIdentifier {
  3851. self.clickChildTool(type: .compress, index: 0)
  3852. } else if itemId == KMToolbarPageEditSplitItemIdentifier { // 拆分
  3853. let windowC = SplitWindowController(document: self.listView.document)
  3854. self.km_beginSheet(windowC: windowC)
  3855. } else if itemId == KMToolbarToolMergeItemIdentifier {
  3856. self.clickChildTool(type: .merge, index: 0)
  3857. } else if itemId == KMToolbarPageEditInsetItemIdentifier {
  3858. self.leftSideViewController.insertPDF(nil)
  3859. } else if itemId == KMToolbarShowToolbarItemIdentifier {
  3860. self.showOrHideNotes()
  3861. } else if itemId == KMAnnotationTableToolbarItemIdentifier {
  3862. self.tableAnnotation(toolbarItem)
  3863. } else if itemId == KMToolbarConversionTextItemIdentifier {
  3864. self.clickChildTool(type: .conversion_text, index: 0)
  3865. } else if itemId == KMToolbarConversionHTMLItemIdentifier {
  3866. self.clickChildTool(type: .html, index: 0)
  3867. } else if itemId == KMToolbarConversionCSVItemIdentifier {
  3868. self.clickChildTool(type: .csv, index: 0)
  3869. } else if itemId == KMToolbarConversionRTFItemIdentifier {
  3870. self.clickChildTool(type: .rtf, index: 0)
  3871. } else if itemId == KMToolbarConversionPPTItemIdentifier {
  3872. self.clickChildTool(type: .ppt, index: 0)
  3873. } else if itemId == KMToolbarConversionExcelItemIdentifier {
  3874. self.clickChildTool(type: .excel, index: 0)
  3875. } else if itemId == KMToolbarConversionWordItemIdentifier {
  3876. self.clickChildTool(type: .word, index: 0)
  3877. } else if itemId == KMToolbarConversionOtherItemIdentifier {
  3878. if index == KMPDFConvertType.text.rawValue {
  3879. self.clickChildTool(type: .conversion_text, index: 0)
  3880. } else if index == KMPDFConvertType.rtf.rawValue {
  3881. self.clickChildTool(type: .rtf, index: 0)
  3882. } else if index == KMPDFConvertType.html.rawValue {
  3883. self.clickChildTool(type: .html, index: 0)
  3884. } else if index == KMPDFConvertType.csv.rawValue {
  3885. self.clickChildTool(type: .csv, index: 0)
  3886. } else if index == KMPDFConvertType.json.rawValue {
  3887. self.clickChildTool(type: .json, index: 0)
  3888. }
  3889. }
  3890. }
  3891. func convertToImg(index: Int) {
  3892. var convertT: KMConvertType = .JPEG
  3893. switch index {
  3894. case 7:
  3895. convertT = .JPEG
  3896. case 8:
  3897. convertT = .JPG
  3898. case 9:
  3899. convertT = .PNG
  3900. case 10:
  3901. convertT = .GIF
  3902. case 11:
  3903. convertT = .TIFF
  3904. case 12:
  3905. convertT = .TGA
  3906. case 13:
  3907. convertT = .BMP
  3908. default:
  3909. convertT = .JPEG
  3910. }
  3911. showAllConvertWindow(convertT: convertT)
  3912. }
  3913. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  3914. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3915. self.search(searchString: searchString, isCase: caseInsensitive, display: false)
  3916. var row = max(searchIndex - 1, 0)
  3917. if forward {
  3918. row = searchIndex + 1
  3919. }
  3920. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  3921. let model = self.searchResults[row]
  3922. if model.selection != nil {
  3923. self.listView.setHighlightedSelections([])
  3924. self.listView.go(to: model.selection, animated: true)
  3925. self.listView.setHighlightedSelection(model.selection, animated: true)
  3926. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  3927. searchIndex = row
  3928. }
  3929. }
  3930. self.leftSideViewController.showSearchMode(searchString)
  3931. }
  3932. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAction searchString: String, forward: Bool) {
  3933. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3934. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  3935. var row = max(searchIndex - 1, 0)
  3936. if forward {
  3937. row = searchIndex + 1
  3938. }
  3939. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  3940. let model = self.searchResults[row]
  3941. if model.selection != nil {
  3942. self.listView.setHighlightedSelections([])
  3943. self.listView.go(to: model.selection, animated: true)
  3944. self.listView.setHighlightedSelection(model.selection, animated: true)
  3945. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  3946. searchIndex = row
  3947. }
  3948. }
  3949. }
  3950. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAllAction searchString: String, forward: Bool) {
  3951. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3952. self.search(searchString: searchString, isCase: !caseInsensitive, display: false, needShowAll: true)
  3953. self.leftSideViewController.showSearchMode(searchString)
  3954. }
  3955. func toolbarViewController(_ viewController: KMToolbarViewController, viewItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3956. let itemId = toolbarItem.itemIdentifier
  3957. if itemId == KMDocumentFirstLastToolbarItemIdentifier {
  3958. if index == 1 {
  3959. if self.listView.canGoToFirstPage() {
  3960. self.listView.goToFirstPage(nil)
  3961. }
  3962. } else if index == 2 {
  3963. if self.listView.canGoToLastPage() {
  3964. self.listView.goToLastPage(nil)
  3965. }
  3966. }
  3967. } else if itemId == KMDocumentPageInputToolbarItemIdentifier {
  3968. var valid = false
  3969. if let number = Int(info as? String ?? "") {
  3970. let cnt = self.listView.document?.pageCount ?? 0
  3971. if number > 0 && number <= cnt {
  3972. self.listView.go(toPageIndex: number-1, animated: false)
  3973. valid = true
  3974. }
  3975. }
  3976. if valid == false {
  3977. Task {@MainActor in
  3978. _ = await KMAlertTool.runModel(message: NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))
  3979. }
  3980. }
  3981. }
  3982. }
  3983. }
  3984. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  3985. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  3986. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  3987. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  3988. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  3989. distanceSettingWC.delegate = self
  3990. distanceSettingWC.startModal("")
  3991. }
  3992. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  3993. }
  3994. }
  3995. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  3996. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  3997. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  3998. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  3999. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  4000. distanceSettingWC.delegate = self
  4001. distanceSettingWC.startModal("")
  4002. }
  4003. }
  4004. // MARK: CAreaMeasureInfoWindowControllerDelegate
  4005. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  4006. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  4007. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  4008. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  4009. areaSettingWC.delegate = self
  4010. areaSettingWC.startModal("")
  4011. }
  4012. }
  4013. // MARK: CDistanceSettingWindowControllerDelegate
  4014. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  4015. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  4016. if distanceMeasureInfo != nil {
  4017. if self.listView.activeAnnotations.count > 0 {
  4018. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  4019. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  4020. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4021. }
  4022. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  4023. } else {
  4024. distanceMeasureInfo?.leadLength = 0
  4025. self.listView.distanceMeasureInfo = distanceMeasureInfo
  4026. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  4027. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4028. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  4029. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  4030. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  4031. }
  4032. if let data = self.listView.activeAnnotation {
  4033. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4034. }
  4035. }
  4036. self.distanceMeasureInfoWindowController?.showWindow(self)
  4037. }
  4038. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  4039. if perimeterMeasureInfo != nil {
  4040. if self.listView.activeAnnotations.count > 0 {
  4041. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  4042. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  4043. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4044. }
  4045. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  4046. } else {
  4047. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  4048. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  4049. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4050. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  4051. }
  4052. if let data = self.listView.activeAnnotation {
  4053. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4054. }
  4055. }
  4056. self.perimeterMeasureInfoWindowController?.showWindow(self)
  4057. }
  4058. }
  4059. // MARK: CAreaSettingWindowControllerDelegate
  4060. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  4061. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  4062. if self.listView.annotationType == .square && self.listView.toolMode == .measureToolMode {
  4063. if measureInfo != nil {
  4064. if self.listView.activeAnnotations.count > 0 {
  4065. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4066. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4067. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4068. }
  4069. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4070. } else {
  4071. self.listView.squareAreaMeasureInfo = measureInfo
  4072. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  4073. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4074. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4075. }
  4076. }
  4077. self.areaMeasureInfoWindowController?.showWindow(self)
  4078. } else if self.listView.annotationType == .polyGon && self.listView.toolMode == .measureToolMode {
  4079. if measureInfo != nil {
  4080. if self.listView.activeAnnotations.count > 0 {
  4081. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4082. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4083. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4084. }
  4085. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4086. } else {
  4087. self.listView.polygonAreaMeasureInfo = measureInfo
  4088. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  4089. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4090. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4091. }
  4092. }
  4093. self.areaMeasureInfoWindowController?.showWindow(self)
  4094. } else {
  4095. if measureInfo != nil {
  4096. if self.listView.activeAnnotations.count > 0 {
  4097. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4098. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4099. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4100. }
  4101. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4102. }
  4103. }
  4104. self.areaMeasureInfoWindowController?.showWindow(self)
  4105. }
  4106. if measureInfo != nil {
  4107. if let data = self.listView.activeAnnotation {
  4108. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4109. }
  4110. }
  4111. }
  4112. }
  4113. //MARK: LeftSideViewController
  4114. extension KMMainViewController {
  4115. func leftSideViewCancelSelect() {
  4116. if self.listView.isEditing() == true {
  4117. if self.listView.editingAreas() != nil &&
  4118. self.listView.editingAreas().count != 0 {
  4119. let areas = self.listView.editingAreas().first
  4120. if areas is CPDFEditTextArea {
  4121. self.listView.clearEditingSelectCharItem()
  4122. self.listView.updateEditing([])
  4123. KMPrint("取消选中")
  4124. }
  4125. }
  4126. }
  4127. }
  4128. }
  4129. // MARK: - Analytics (埋点)
  4130. extension KMMainViewController {
  4131. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  4132. if (type == .Annatiton) {
  4133. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  4134. } else if (type == .editPDF) {
  4135. } else if (type == .Page) {
  4136. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  4137. } else if (type == .Conversion) {
  4138. } else if (type == .Tool) {
  4139. }
  4140. }
  4141. func trackEvent_aiTranslate() -> Void {
  4142. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  4143. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4144. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4145. }
  4146. func trackEvent_print() -> Void {
  4147. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  4148. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4149. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4150. }
  4151. func trackEvent_share() -> Void {
  4152. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  4153. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4154. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4155. }
  4156. func trackEvent_upgrade() -> Void {
  4157. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  4158. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4159. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4160. }
  4161. func trackEvent(annotationType type: CAnnotationType) -> Void {
  4162. if (type == .highlight) {
  4163. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  4164. } else if (type == .underline) {
  4165. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  4166. } else if (type == .strikeOut) {
  4167. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  4168. } else if (type == .ink) {
  4169. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  4170. } else if (type == .freeText) {
  4171. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  4172. } else if (type == .anchored) {
  4173. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  4174. } else if (type == .square) {
  4175. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  4176. } else if (type == .link) {
  4177. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  4178. } else if (type == .stamp) {
  4179. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  4180. } else if (type == .signSignature) {
  4181. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  4182. } else if (type == .circle) {
  4183. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  4184. } else if (type == .arrow) {
  4185. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  4186. } else if (type == .line) {
  4187. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  4188. } else if (type == .addText) {
  4189. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  4190. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4191. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4192. } else if (type == .addImage) {
  4193. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  4194. } else if (type == .textField) {
  4195. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  4196. } else if (type == .checkBox) {
  4197. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  4198. } else if (type == .radioButton) {
  4199. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  4200. } else if (type == .listMenu) {
  4201. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  4202. } else if (type == .comboBox) {
  4203. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  4204. } else if (type == .actionButton) {
  4205. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4206. } else if (type == .actionButton) {
  4207. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4208. } else if (type == .signature) {
  4209. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  4210. } else if (type == .squiggly) {
  4211. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  4212. } else if (type == .eraser) {
  4213. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  4214. }
  4215. }
  4216. func trackEvent(toolMode mode: CToolMode) -> Void {
  4217. if (mode == .selectToolMode) {
  4218. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  4219. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4220. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4221. } else if (mode == .moveToolMode) {
  4222. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  4223. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4224. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4225. } else if mode == .measureToolMode {
  4226. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  4227. }
  4228. }
  4229. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  4230. if (type == .word) {
  4231. } else if (type == .excel) {
  4232. } else if (type == .ppt) {
  4233. } else if (type == .rtf) {
  4234. } else if (type == .csv) {
  4235. } else if (type == .html) {
  4236. } else if (type == .conversion_text) {
  4237. } else if (type == .conversion_image) {
  4238. } else if (type == .compress) {
  4239. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  4240. } else if (type == .merge) {
  4241. } else if (type == .secure) {
  4242. } else if (type == .crop) {
  4243. } else if type == .json {
  4244. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  4245. }
  4246. }
  4247. func trackEvent_setPassword() -> Void {
  4248. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  4249. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4250. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4251. }
  4252. func trackEvent_removePassword() -> Void {
  4253. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  4254. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4255. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4256. }
  4257. func trackEvent_replace() -> Void {
  4258. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  4259. }
  4260. }
  4261. extension KMMainViewController {
  4262. //文件对比
  4263. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  4264. self.isCompareModel = true
  4265. let compareContentView = KMCompareContentView()
  4266. compareContentView.oldDocument = oldDocument
  4267. compareContentView.document = document
  4268. compareContentView.compareResults = results
  4269. compareContentView.saveHandle = { [unowned self] view in
  4270. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  4271. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  4272. self.currentWindowController = saveController
  4273. saveController.cancelHandle = { [unowned self] controller in
  4274. self.view.window!.endSheet(controller.window!)
  4275. self.currentWindowController = nil
  4276. }
  4277. saveController.saveHandle = { [unowned self] controller, saveType in
  4278. let folderPath = controller.fileSaveFolderPath
  4279. if folderPath != nil {
  4280. if !FileManager.default.fileExists(atPath: folderPath) {
  4281. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  4282. }
  4283. #if VERSION_DMG
  4284. #else
  4285. let url = URL(fileURLWithPath: folderPath)
  4286. let fileAccess = AppSandboxFileAccess()
  4287. fileAccess?.persistPermissionURL(url)
  4288. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  4289. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  4290. let urlString = url.path
  4291. let _url = URL(fileURLWithPath: urlString)
  4292. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  4293. }
  4294. #endif
  4295. var savePath: String
  4296. switch saveType {
  4297. case 0:
  4298. let filePath = oldDocument.documentURL.path
  4299. let fileName = filePath.deletingPathExtension.lastPathComponent
  4300. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4301. savePath = self.getValidFilePath(savePath)
  4302. oldDocument.write(to: URL(fileURLWithPath: savePath))
  4303. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4304. case 1:
  4305. let filePath = document.documentURL.path
  4306. let fileName = filePath.deletingPathExtension.lastPathComponent
  4307. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4308. savePath = self.getValidFilePath(savePath)
  4309. document.write(to: URL(fileURLWithPath: savePath))
  4310. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4311. case 2:
  4312. let filePath = oldDocument.documentURL.path
  4313. let fileName = filePath.deletingPathExtension.lastPathComponent
  4314. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  4315. savePath = self.getValidFilePath(savePath)
  4316. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  4317. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4318. default:
  4319. break
  4320. }
  4321. }
  4322. self.view.window!.endSheet(controller.window!)
  4323. self.currentWindowController = nil
  4324. }
  4325. NSWindow.currentWindow().beginSheet(saveController.window!)
  4326. }
  4327. }
  4328. compareContentView.closeHandle = { [unowned self] view in
  4329. self.isCompareModel = false
  4330. view.removeFromSuperview()
  4331. }
  4332. compareContentView.autoresizingMask = [.width,.height]
  4333. }
  4334. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  4335. self.isCompareModel = true
  4336. let coveringView = KMCompareCoveringView()
  4337. coveringView.pdfDocument = pdfDocument
  4338. coveringView.closeHandle = { [unowned self] view in
  4339. self.isCompareModel = false
  4340. view.removeFromSuperview()
  4341. }
  4342. coveringView.saveHandle = { [unowned self] view in
  4343. let savePanel = NSSavePanel()
  4344. savePanel.nameFieldStringValue = "untitled"
  4345. savePanel.allowedFileTypes = ["pdf"]
  4346. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  4347. if result == .OK {
  4348. pdfDocument.write(to: savePanel.url!)
  4349. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  4350. }
  4351. }
  4352. }
  4353. coveringView.autoresizingMask = [.width,.height]
  4354. }
  4355. func getValidFilePath(_ oldPath: String) -> String {
  4356. let fileManager = FileManager.default
  4357. do {
  4358. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  4359. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  4360. return oldPath
  4361. }
  4362. var i = 1
  4363. var newPath = oldPath
  4364. while fileManager.fileExists(atPath: newPath) {
  4365. if fileType == FileAttributeType.typeDirectory.rawValue {
  4366. newPath = oldPath + "(\(i))"
  4367. } else {
  4368. let fileExtension = (oldPath as NSString).pathExtension
  4369. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  4370. }
  4371. i += 1
  4372. }
  4373. return newPath
  4374. } catch {
  4375. print("Error getting file attributes: \(error)")
  4376. return oldPath
  4377. }
  4378. }
  4379. }
  4380. extension KMMainViewController {
  4381. func documentAllowsEdit() -> Bool {
  4382. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  4383. let alert = NSAlert()
  4384. alert.alertStyle = .critical
  4385. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  4386. alert.runModal()
  4387. return false
  4388. } else {
  4389. return true
  4390. }
  4391. }
  4392. func changeFont(_ sender: NSFontManager) {
  4393. KMPrint("changeFont ...")
  4394. if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
  4395. let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
  4396. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  4397. font = sender.convert(font!)
  4398. annotation.fontSize = font?.pointSize ?? 12
  4399. self.listView.commitEditAnnotationFreeText(annotation)
  4400. self.listView.setNeedsDisplay(annotation)
  4401. }
  4402. }
  4403. func currentSetup() -> [String: Any] {
  4404. var setup: [String: Any] = [:]
  4405. var point = NSZeroPoint
  4406. if listView == nil {
  4407. return setup
  4408. }
  4409. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  4410. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  4411. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  4412. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  4413. setup[KMMainModel.Key.pageIndex] = pageIndex
  4414. return setup
  4415. }
  4416. // MARK: - Recommond活动
  4417. func loadRecommondPopWindow() {
  4418. if IAPProductsManager.default().isAvailableAllFunction() {
  4419. return
  4420. }
  4421. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  4422. if recommondPopWindowVC == nil {
  4423. recommondPopWindowVC = KMRecommondPopWindow.default()
  4424. }
  4425. recommondPopWindowVC?.recommondInfo = info
  4426. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  4427. return
  4428. }
  4429. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  4430. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  4431. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  4432. recommondPopWindowVC?.window?.orderFront((Any).self)
  4433. recommondPopWindowVC?.window?.becomeMain()
  4434. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  4435. UserDefaults.standard.synchronize()
  4436. }
  4437. }
  4438. @objc func didAddContentViewNotification(_ sender: Notification) {
  4439. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  4440. return
  4441. }
  4442. if self.interactionMode == .presentation {
  4443. }
  4444. }
  4445. @objc func purchaseStateUpdateNoti() {
  4446. if IAPProductsManager.default().isAvailableAllFunction() {
  4447. }
  4448. }
  4449. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  4450. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  4451. guard let anno = sender.object as? CPDFAnnotation else {
  4452. return
  4453. }
  4454. if anno.page?.document != self.listView.document {
  4455. return
  4456. }
  4457. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: [anno], page: anno.page)
  4458. }
  4459. // MARK: Split View
  4460. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  4461. let openPanel = NSOpenPanel()
  4462. openPanel.allowedFileTypes = ["pdf", "PDF"]
  4463. openPanel.allowsMultipleSelection = false
  4464. guard let mainWindow = NSApp.mainWindow else {
  4465. return
  4466. }
  4467. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  4468. if response == NSApplication.ModalResponse.OK {
  4469. guard let url = openPanel.url else {
  4470. return
  4471. }
  4472. if let document = CPDFDocument(url: url) {
  4473. replaceBlock(document.documentURL?.path ?? "")
  4474. } else {
  4475. let alert = NSAlert()
  4476. alert.alertStyle = .critical
  4477. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  4478. alert.runModal()
  4479. }
  4480. }
  4481. }
  4482. }
  4483. }