KMMainViewController+Action.swift 296 KB

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