KMMainViewController.swift 338 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775
  1. //
  2. // KMMainViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. let MIN_SIDE_PANE_WIDTH: NSNumber = 264 // 最小值
  10. let CPDFViewIsReadModeKey = "kKMPDFViewIsReadMode"
  11. let CPDFViewLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  12. struct KMNMWCFlags {
  13. var settingUpWindow: Bool = true
  14. }
  15. @objcMembers class KMMainViewController: KMNBaseViewController, NSTextFieldDelegate {
  16. @IBOutlet var contendBox: NSBox!
  17. @IBOutlet var toolbarBox: NSBox! //工具栏Box
  18. @IBOutlet var bottomContendBox: NSBox! //
  19. @IBOutlet var sidebarBox: NSBox! //左侧边栏Box
  20. @IBOutlet var infoContendSplitView: NSSplitView!
  21. @IBOutlet var infoSplitLeftView: NSView!
  22. @IBOutlet var infoSplitRightView: NSView!
  23. @IBOutlet var infoSplitCenterView: NSView!
  24. @IBOutlet var pdfSplitView: NSSplitView!
  25. @IBOutlet var pdfSplitTopView: NSView!
  26. @IBOutlet var pdfSplitBottomView: NSView!
  27. @IBOutlet var toolbarBoxHeightConst: NSLayoutConstraint!
  28. @IBOutlet var infoSplitViewLeftConst: NSLayoutConstraint!
  29. @IBOutlet var infoSplitViewRightConst: NSLayoutConstraint!
  30. var viewManager: KMPDFViewManager = KMPDFViewManager.init()
  31. var toolbarManager: KMPDFToolbarManager = KMPDFToolbarManager.init()
  32. var listView: CPDFListView = CPDFListView.init()
  33. var document: CPDFDocument?
  34. var myDocument: NSDocument?
  35. var isFirstOpen: Bool = true
  36. var insertDocuments: Set<CPDFDocument> = [] //插入新文档时,SDK会出现崩溃,临时记录
  37. //工具栏
  38. private var pdfToolbarController: KMPDFToolbarController?
  39. //BOTA SideBar
  40. private var sideBarController: KMPDFSideBarController?
  41. //页面编辑
  42. private var pageEditViewController: KMNPageEditViewController?
  43. //DisplaySetting
  44. private var displaySettingController: KMNDisplayViewController?
  45. //SPlitPDF分屏视图
  46. private var splitPDFController: KMSplitPDFViewController?
  47. private var pageNumberToolbar: KMPageNumberPromptView?
  48. //PPT操作界面
  49. var presentationTopViewController: KMPresentationTopViewController?
  50. //Edit
  51. var editToolbarView: KMEditToolbarView?
  52. //水印
  53. var watermarkViewController: KMWatermarkController?
  54. //背景
  55. var backgroundViewController: KMBackgroundController?
  56. //Header&Footer
  57. var headerFooterViewController: KMHeaderFooterController?
  58. //Bates
  59. var batesViewController: KMBatesController?
  60. //Crop
  61. var cropController: KMCropController?
  62. //左边
  63. var botaViewController: KMNLeftSideViewController?
  64. //右边
  65. var rightSideController: KMRightSideController?
  66. let alertTipViewController: KMNAlertTipViewController = KMNAlertTipViewController(nibName: "KMNAlertTipViewController", bundle: nil)
  67. //合并
  68. var mergeWindowController: KMMergeWindowController?
  69. //春季活动
  70. var recommondPopWindowVC: KMRecommondPopWindow?
  71. //数字签名状态
  72. var signaturestateVC: CDSignatureCertificateStateViewController = CDSignatureCertificateStateViewController.init()
  73. //PDFView右键菜单
  74. private var groupListMenuGroup: ComponentGroup? = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  75. var textFieldSheet: KMTextFieldSheetController = KMTextFieldSheetController.init(windowNibName: "KMTextFieldSheetController")
  76. @IBOutlet weak var leftView: NSView!
  77. var model = KMMainModel()
  78. //Search
  79. var searchIndex: Int = 0
  80. //对比
  81. var isCompareModel: Bool = false
  82. //密码弹窗
  83. var passwordWindow: KMPasswordInputWindow?
  84. var securityWindowController: KMSecurityWindowController?
  85. //压缩
  86. var compressWindowController: KMCompressWindowController?
  87. //引导
  88. var guideInfoWindowController: KMGuideInfoWindowController?
  89. //测量
  90. var distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController?
  91. var perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController?
  92. var areaMeasureInfoWindowController: CAreaMeasureInfoWindowController?
  93. //打印
  94. var bookletWindowController: KMPDFBookletWindowController?
  95. var multiplePrintWindowController: KMPDFMultiplePrintWindowController?
  96. var posterPrintWindowController: KMPDFPosterPrintWindowController?
  97. var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  98. private var _needSave = false
  99. var needSave: Bool {
  100. set {
  101. _needSave = newValue
  102. if (_needSave == false) {
  103. self.clearIsPDFDocumentEdited()
  104. }
  105. }
  106. get {
  107. return _needSave
  108. }
  109. }
  110. var isPDFDocumentEdited: Bool {
  111. get {
  112. return self.model.isPDFDocumentEdited
  113. }
  114. }
  115. var newMwcFlags = KMNMWCFlags(settingUpWindow: true)
  116. var searchResults: [KMSearchMode] = []
  117. var mwcFlags: MwcFlags = MwcFlags()
  118. weak var browserWindowController: KMBrowserWindowController? //慎直接使用这个方法
  119. var currentWindowController: NSWindowController!
  120. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  121. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  122. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  123. var extract: KMExtractImageWindowController?
  124. var pageNumber: UInt?
  125. var autoSaveTimer: Timer?
  126. private var _documentFirstLoad: Bool = true
  127. var eventMonitor: Any?
  128. var keyEventMonitor: Any?
  129. var mouseRightMenuEvent: NSEvent?
  130. lazy private var homeVC: KMNHomeViewController? = {
  131. let vc = KMNHomeViewController()
  132. return vc
  133. }()
  134. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  135. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  136. get {
  137. return self._secureOptions
  138. }
  139. }
  140. var documentAttribute: [CPDFDocumentAttribute : Any]?
  141. fileprivate var _removeSecureFlag = false
  142. var removeSecureFlag: Bool {
  143. get {
  144. return self._removeSecureFlag
  145. }
  146. }
  147. fileprivate var _saveWatermarkFlag = false
  148. var saveWatermarkFlag: Bool {
  149. get {
  150. return self._saveWatermarkFlag
  151. }
  152. }
  153. private var mainWindow_: NSWindow?
  154. var mainWindow: NSWindow? {
  155. get {
  156. return self.mainWindow_
  157. }
  158. set {
  159. self.mainWindow_ = newValue
  160. }
  161. }
  162. var setDocument: CPDFDocument? {
  163. get {
  164. return document
  165. }
  166. set {
  167. if document != newValue {
  168. document = newValue
  169. }
  170. listView.document = document
  171. botaViewController?.changeDocument(document: document)
  172. }
  173. }
  174. var setPageNumber: UInt {
  175. get {
  176. return pageNumber!
  177. }
  178. set {
  179. let pageCount = listView.document?.pageCount ?? 0
  180. var value = newValue
  181. if value > pageCount {
  182. value = pageCount
  183. }
  184. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  185. listView.go(to: listView.document?.page(at: value-1))
  186. }
  187. if pageNumber != value {
  188. pageNumber = value
  189. }
  190. }
  191. }
  192. //MARK: - func
  193. deinit {
  194. NotificationCenter.default.removeObserver(self)
  195. self.listView.delegate = nil
  196. self.listView.document?.delegate = nil
  197. self.removeEventMonitor()
  198. }
  199. override func viewDidLoad() {
  200. super.viewDidLoad()
  201. // Do view setup here.
  202. setupData()
  203. setupUI()
  204. NotificationCenter.default.addObserver(self, selector: #selector(pdfViewScrollViewDidScroll), name: NSScrollView.didLiveScrollNotification, object: listView.documentView())
  205. NotificationCenter.default.addObserver(self, selector: #selector(pageCountChangedNotification), name: NSNotification.Name.CPDFDocumentPageCountChanged, object: listView.document)
  206. }
  207. override func viewDidAppear() {
  208. super.viewDidAppear()
  209. reloadPopUIWindow()
  210. addEventMonitor()
  211. addKeyEventMonitor()
  212. }
  213. override func viewDidDisappear() {
  214. super.viewDidDisappear()
  215. toggleClosePopUIWindow()
  216. }
  217. override func initContentView() {
  218. super.initContentView()
  219. }
  220. override func updateUIThemeColor() {
  221. super.updateUIThemeColor()
  222. }
  223. override func updateUILanguage() {
  224. super.updateUILanguage()
  225. }
  226. //MARK: - private
  227. func setupUI() {
  228. initPDFView()
  229. initToolbar()
  230. initSideBar()
  231. setUpSplitView()
  232. }
  233. func setupData() {
  234. toolbarManager.pdfViewManager = viewManager
  235. if (UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) != nil) {
  236. UserDefaults.standard.set(MIN_SIDE_PANE_WIDTH, forKey: CPDFViewLeftSidePaneWidthKey)
  237. UserDefaults.standard.synchronize()
  238. }
  239. newMwcFlags.settingUpWindow = true
  240. }
  241. @objc func editFontColorItemPanelAction(_ sender: Any) {
  242. if let color = (sender as? NSColorPanel)?.color {
  243. listView.changeEditingTextarea_Color(color: color)
  244. }
  245. }
  246. //MARK: - document load成功
  247. private func documentLoadComplete() {
  248. initLeftSideController()
  249. addNotificationCenter()
  250. activityLoadMethod()
  251. let readModel = UserDefaults.standard.bool(forKey: CPDFViewIsReadModeKey)
  252. if readModel == true {
  253. self.openPDFReadMode()
  254. }
  255. reloadDigitalSigns()
  256. alertTipViewController.showInView(listView)
  257. alertTipViewController.formFieldHighlightCallback = { [weak self] in
  258. let value = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
  259. CPDFAnnotation.updateHighlightFormFiled(self?.listView, highlightFormFiled: !value)
  260. self?.toolbarManager.refreshDefaultConfigItem()
  261. }
  262. alertTipViewController.enterPasswordCallback = { [weak self] in
  263. self?.removeOwnerPassword()
  264. }
  265. alertTipViewController.digitalDetailsCallback = { [weak self] in
  266. }
  267. alertTipViewController.redactApplyCallback = { [weak self] in
  268. self?.redactApplyAction()
  269. }
  270. newMwcFlags.settingUpWindow = false
  271. loadUserDefaultsData()
  272. }
  273. private func saveAsPath() {
  274. let saveAccessCtr = KMSavePanelAccessoryController()
  275. var fileName = listView.document.documentURL.deletingPathExtension().lastPathComponent
  276. fileName = String(format: "%@_%@.pdf", fileName, "Redact")
  277. let outputSavePanel = NSSavePanel()
  278. outputSavePanel.allowedFileTypes = ["pdf"]
  279. outputSavePanel.nameFieldStringValue = fileName
  280. outputSavePanel.accessoryView = saveAccessCtr.view
  281. outputSavePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  282. if result == .OK {
  283. self.listView.document.applyRedactions()
  284. self.showProgressWindow(message: KMLocalizedString("Save") + "PDF")
  285. self.progressC?.maxValue = 3.0
  286. self.progressC?.increment(by: 1.0)
  287. let savePDFPath = outputSavePanel.url!.path
  288. // 执行进度 [假进度]
  289. self.progressC?.increment(by: 1.0)
  290. self.progressC?.increment(by: 1.0)
  291. let isSuccess = self.listView.document.write(toFile: savePDFPath)
  292. if (isSuccess) {
  293. if (saveAccessCtr.openAutomaticButton.state == .on) {
  294. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  295. }
  296. } else {
  297. let url = URL(fileURLWithPath: savePDFPath)
  298. NSWorkspace.shared.activateFileViewerSelecting([url])
  299. }
  300. }
  301. self.hiddenProgressWindow()
  302. }
  303. }
  304. }
  305. private func reloadDigitalSigns() {
  306. let signatures = listView.document.signatures()
  307. for i in 0 ..< (signatures?.count ?? 0) {
  308. let signature:CPDFSignature = signatures?[i] ?? CPDFSignature()
  309. if signature.signers.count > 0 {
  310. signature.verifySignature(with: listView.document)//耗时,注意
  311. }
  312. }
  313. listView.signatures = signatures
  314. }
  315. //MARK: - 活动加载相关
  316. private func activityLoadMethod() {
  317. }
  318. private func addNotificationCenter() {
  319. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  320. NotificationCenter.default.addObserver(self, selector: #selector(signatureStateChangeNoti), name: NSNotification.Name(rawValue: "CSignatureTrustCerDidChangeNotification"), object: nil)
  321. }
  322. private func loadUserDefaultsData() {
  323. applyLeftSideWidth(0, rightSideWidth: 0) //初始打开左边栏
  324. //初始化侧边栏打开内容
  325. if SettingsManager.sharedInstance.leftPanelType == .defaultOpen {
  326. if SettingsManager.sharedInstance.defaultOpen == .thumbnail {
  327. viewManager.pdfSideBarType = .thumbnail
  328. } else if SettingsManager.sharedInstance.defaultOpen == .outline {
  329. viewManager.pdfSideBarType = .outline
  330. } else if SettingsManager.sharedInstance.defaultOpen == .bookmark {
  331. viewManager.pdfSideBarType = .bookmark
  332. } else if SettingsManager.sharedInstance.defaultOpen == .annotation {
  333. viewManager.pdfSideBarType = .annotation
  334. }
  335. } else if SettingsManager.sharedInstance.leftPanelType == .sameAsLastOpen {
  336. if let value = UserDefaults.standard.value(forKey: "KMPDFSidebarTypeKey"), let data = value as? Int {
  337. let pdfSideBarType: KMPDFSidebarType = KMPDFSidebarType(rawValue: data) ?? .none
  338. viewManager.pdfSideBarType = pdfSideBarType
  339. }
  340. } else if SettingsManager.sharedInstance.leftPanelType == .hideLeftSide {
  341. viewManager.pdfSideBarType = .none
  342. } else if SettingsManager.sharedInstance.leftPanelType == .prioritizeOutline {
  343. }
  344. if viewManager.pdfSideBarType == .none {
  345. toggleCloseLeftSide()
  346. } else {
  347. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
  348. self.toggleCloseLeftSide()
  349. self.toggleOpenLeftSide(pdfSideBarType: self.viewManager.pdfSideBarType)
  350. }
  351. }
  352. //Layout & Zoom
  353. let layoutType = SettingsManager.sharedInstance.layoutType
  354. if layoutType == .singlePage {
  355. self.updatePDFViewDisplayMode(viewMode: .singlePage)
  356. } else if layoutType == .singlePageContinue {
  357. self.updatePDFViewDisplayMode(viewMode: .singlePageContinuous)
  358. } else if layoutType == .twoPage {
  359. self.updatePDFViewDisplayMode(viewMode: .twoUp)
  360. } else if layoutType == .twoPageContinue {
  361. self.updatePDFViewDisplayMode(viewMode: .twoUpContinuous)
  362. } else if layoutType == .bookMode {
  363. self.updatePDFViewDisplayMode(isbookMode: true, direction: .horizontal)
  364. } else if layoutType == .bookModeContinue {
  365. self.updatePDFViewDisplayMode(isbookMode: true, direction: .vertical)
  366. }
  367. }
  368. func refreshPDFViewZoomInfo(_ zoomType: zoomInfoType) {
  369. if zoomType == .adaptationWidth {
  370. listView.autoScales = true
  371. } else if zoomType == .adapPage {
  372. let pageHeight = listView.currentPage().size.height
  373. let pdfviewHeight = listView.bounds.size.height
  374. listView.scaleFactor = pdfviewHeight/pageHeight
  375. listView.autoScales = false
  376. } else if zoomType == .actualSize {
  377. if listView.scaleFactor != 1.0 {
  378. listView.scaleFactor = 1.0
  379. listView.autoScales = false
  380. }
  381. } else if zoomType == .percent_10 {
  382. listView.scaleFactor = 0.1
  383. } else if zoomType == .percent_25 {
  384. listView.scaleFactor = 0.25
  385. } else if zoomType == .percent_50 {
  386. listView.scaleFactor = 0.5
  387. } else if zoomType == .percent_75 {
  388. listView.scaleFactor = 0.75
  389. } else if zoomType == .percent_100 {
  390. listView.scaleFactor = 1.0
  391. } else if zoomType == .percent_150 {
  392. listView.scaleFactor = 1.5
  393. } else if zoomType == .percent_200 {
  394. listView.scaleFactor = 2.0
  395. } else if zoomType == .percent_400 {
  396. listView.scaleFactor = 4.0
  397. } else if zoomType == .percent_800 {
  398. listView.scaleFactor = 8.0
  399. }
  400. }
  401. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  402. infoContendSplitView.setPosition(infoContendSplitView.maxPossiblePositionOfDivider(at: 1) - infoContendSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  403. infoContendSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  404. }
  405. //MARK: - PDFView
  406. func initPDFView() {
  407. listView.autoresizingMask = [.width, .height]
  408. listView.autoScales = true
  409. listView.delegate = self
  410. listView.pdfListViewDelegate = self
  411. listView.document = self.document
  412. listView.pageBreakMargins = NSEdgeInsetsMake(10, 0, 10, 10)
  413. listView.hideNotes = false
  414. if let _ = UserDefaults.standard.value(forKey: "kPDFViewShowFormFieldNameKey") {
  415. listView.showFormFieldName = UserDefaults.getDefaultBoolValue(forKey: "kPDFViewShowFormFieldNameKey")
  416. } else {
  417. listView.showFormFieldName = true
  418. }
  419. reloadPDFSplitInfo()
  420. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
  421. let zoomType = SettingsManager.sharedInstance.zoomType
  422. self.refreshPDFViewZoomInfo(zoomType)
  423. }
  424. }
  425. func updatePDFViewAnnotationMode() {
  426. let toolbarMode = viewManager.toolMode
  427. let subToolMode = viewManager.subToolMode
  428. listView.isHidden = false
  429. if toolbarMode == .None {
  430. listView.toolMode = .CTextToolMode
  431. listView.annotationType = .unkown
  432. } else if toolbarMode == .Markup {
  433. if subToolMode == .None {
  434. listView.toolMode = .CTextToolMode
  435. } else {
  436. listView.toolMode = .CNoteToolMode
  437. }
  438. //MARK: -Markup
  439. if subToolMode == .None {
  440. listView.annotationType = .unkown
  441. } else if subToolMode == .Highlight {
  442. listView.annotationType = .highlight
  443. } else if subToolMode == .Underline {
  444. listView.annotationType = .underline
  445. } else if subToolMode == .Waveline {
  446. listView.annotationType = .squiggly
  447. } else if subToolMode == .Strikethrough {
  448. listView.annotationType = .strikeOut
  449. } else if subToolMode == .Text {
  450. listView.annotationType = .freeText
  451. } else if subToolMode == .Note {
  452. listView.annotationType = .anchored
  453. } else if subToolMode == .Pen {
  454. listView.annotationType = .ink
  455. } else if subToolMode == .Eraser {
  456. listView.annotationType = .eraser
  457. } else if subToolMode == .Rectangle {
  458. listView.annotationType = .square
  459. } else if subToolMode == .Circle {
  460. listView.annotationType = .circle
  461. } else if subToolMode == .Arrow {
  462. listView.annotationType = .arrow
  463. } else if subToolMode == .Line {
  464. listView.annotationType = .line
  465. } else if subToolMode == .Measure {
  466. listView.annotationType = CPDFMeasureDefaultInfo.default_measureType()
  467. refreshMeasureInfo()
  468. } else if subToolMode == .Stamp {
  469. listView.annotationType = .stamp
  470. } else if subToolMode == .Sign {
  471. listView.annotationType = .signSignature
  472. }
  473. } else if toolbarMode == .Edit {
  474. //MARK: -编辑
  475. if subToolMode == .None {
  476. if listView.toolMode != .CEditPDFToolMode {
  477. listView.toolMode = .CEditPDFToolMode
  478. listView.configPDFEditingInfo()
  479. }
  480. let editingPDFLoadType: CEditingLoadType = listView.editingPDFLoadType()
  481. listView.setShouAddEdit([])
  482. listView.change([.text, .image])
  483. } else if subToolMode == .Edit_text {
  484. if listView.toolMode != .CEditPDFToolMode {
  485. listView.toolMode = .CEditPDFToolMode
  486. listView.configPDFEditingInfo()
  487. }
  488. listView.setShouAddEdit([.text])
  489. listView.change(.text)
  490. } else if subToolMode == .Edit_Image {
  491. if listView.toolMode != .CEditPDFToolMode {
  492. listView.toolMode = .CEditPDFToolMode
  493. listView.configPDFEditingInfo()
  494. }
  495. listView.setShouAddEdit([.image])
  496. listView.change(.image)
  497. } else if subToolMode == .Edit_Link {
  498. listView.toolMode = .CEditLinkToolMode
  499. listView.annotationType = .link
  500. } else if subToolMode == .Edit_Crop {
  501. listView.isHidden = true
  502. listView.toolMode = .CCropToolMode
  503. }
  504. if viewManager.editType == .watermark ||
  505. viewManager.editType == .background ||
  506. viewManager.editType == .header_Footer ||
  507. viewManager.editType == .bates {
  508. listView.isHidden = true
  509. listView.toolMode = .CTextToolMode
  510. }
  511. if subToolMode != .Edit_Crop {
  512. removeCropController()
  513. }
  514. self.showOCREditAlert()
  515. } else if toolbarMode == .Form {
  516. //MARK: -Form表单
  517. listView.toolMode = .CFormToolMode
  518. if subToolMode == .None {
  519. listView.annotationType = .unkown
  520. } else if subToolMode == .Form_text {
  521. listView.annotationType = .textField
  522. } else if subToolMode == .Form_checkbox {
  523. listView.annotationType = .checkBox
  524. } else if subToolMode == .Form_radio {
  525. listView.annotationType = .radioButton
  526. } else if subToolMode == .Form_list {
  527. listView.annotationType = .listMenu
  528. } else if subToolMode == .Form_dropdown {
  529. listView.annotationType = .comboBox
  530. } else if subToolMode == .Form_OK {
  531. listView.annotationType = .actionButton
  532. } else if subToolMode == .Form_digitalSign {
  533. listView.annotationType = .signature
  534. }
  535. } else if toolbarMode == .Fill {
  536. //MARK: -填充
  537. if subToolMode == .None {
  538. listView.toolMode = .CTextToolMode
  539. } else {
  540. listView.toolMode = .CNoteToolMode
  541. }
  542. if subToolMode == .None {
  543. } else if subToolMode == .Fill_tick {
  544. listView.annotationType = .signTure
  545. } else if subToolMode == .fill_fork {
  546. listView.annotationType = .signFalse
  547. } else if subToolMode == .fill_rectangle {
  548. listView.annotationType = .signCircle
  549. } else if subToolMode == .fill_line {
  550. listView.annotationType = .signLine
  551. } else if subToolMode == .fill_dot {
  552. listView.annotationType = .signDot
  553. } else if subToolMode == .fill_date {
  554. listView.annotationType = .signDate
  555. } else if subToolMode == .fill_sign {
  556. listView.annotationType = .signSignature
  557. }
  558. } else if toolbarMode == .Convert {
  559. //MARK: -转档
  560. listView.toolMode = .CTextToolMode
  561. } else if toolbarMode == .Protect {
  562. //MARK: -Protect
  563. listView.toolMode = .CTextToolMode
  564. if subToolMode == .Redact {
  565. //密文
  566. listView.annotationType = .redact
  567. listView.toolMode = .CRedactToolMode
  568. } else if subToolMode == .Digital_Sign {
  569. //数字签名
  570. listView.annotationType = .digitalSign
  571. listView.toolMode = .CDigitalSignToolMode
  572. }
  573. } else if toolbarMode == .Tools {
  574. //MARK: -工具
  575. // if subToolMode == .Tool_OCR {
  576. // listView.toolMode = .COCRToolMode
  577. // } else {
  578. // listView.toolMode = .CTextToolMode
  579. // }
  580. }
  581. if (toolbarMode != .Edit) {
  582. self.closeOCREditAlert()
  583. }
  584. }
  585. func showOrHideNotes() {
  586. self.listView.hideNotes = !self.listView.hideNotes
  587. let items = [toolbarManager.highlightProperty, toolbarManager.UnderlineProperty,
  588. toolbarManager.wavelineProperty, toolbarManager.strikethroughProperty,
  589. toolbarManager.textProperty, toolbarManager.noteProperty,
  590. toolbarManager.penProperty, toolbarManager.eraserProperty,
  591. toolbarManager.rectangleProperty, toolbarManager.circleProperty,
  592. toolbarManager.arrowProperty, toolbarManager.lineProperty,
  593. toolbarManager.measureProperty, toolbarManager.stampProperty,
  594. toolbarManager.signProperty]
  595. for item in items {
  596. item.isDisabled = listView.hideNotes
  597. }
  598. pdfToolbarController?.resetSecondToolbar(forceRefresh: true)
  599. }
  600. //MARK: - SplitView
  601. func setUpSplitView() {
  602. infoContendSplitView.wantsLayer = true
  603. infoContendSplitView.layer?.backgroundColor = NSColor.clear.cgColor
  604. infoContendSplitView.delegate = self
  605. infoContendSplitView.layer?.masksToBounds = true
  606. }
  607. func setupSplitPDFController() {
  608. if splitPDFController == nil {
  609. splitPDFController = KMSplitPDFViewController.init()
  610. }
  611. splitPDFController?.view.frame = pdfSplitBottomView.bounds
  612. splitPDFController?.view.autoresizingMask = [.height, .width]
  613. splitPDFController?.viewManager = self.viewManager
  614. splitPDFController?.delegate = self
  615. splitPDFController?.pdfView?.pdfListViewDelegate = self
  616. splitPDFController?.reloadData()
  617. pdfSplitBottomView.addSubview(splitPDFController!.view)
  618. }
  619. //MARK: - 工具栏
  620. func initToolbar() {
  621. toolbarBox.borderWidth = 0
  622. if pdfToolbarController == nil {
  623. pdfToolbarController = KMPDFToolbarController.init()
  624. }
  625. pdfToolbarController?.view.frame = toolbarBox.bounds
  626. pdfToolbarController?.view.autoresizingMask = [.width, .height]
  627. pdfToolbarController?.delegate = self
  628. toolbarBox.contentView = pdfToolbarController?.view
  629. pdfToolbarController?.viewManager = viewManager
  630. pdfToolbarController?.toolbarManager = toolbarManager
  631. pdfToolbarController?.pdfView = listView
  632. pdfToolbarController?.setUpData()
  633. refreshToolbarViewHeightInfo()
  634. if listView.showFormFieldName {
  635. toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
  636. } else {
  637. toolbarManager.form_ShowName_Property.righticon = nil
  638. }
  639. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
  640. self.pdfToolbarController?.clickWithIdentify(KMPDFToolbar_Markup_Identifier)
  641. }
  642. }
  643. func refreshToolbarViewHeightInfo() {
  644. let _viewManager = viewManager
  645. if viewManager.isPageEditMode {
  646. toolbarBoxHeightConst.constant = 80
  647. } else if viewManager.editType == .watermark ||
  648. viewManager.editType == .background ||
  649. viewManager.editType == .header_Footer ||
  650. viewManager.editType == .bates {
  651. toolbarBoxHeightConst.constant = 40
  652. } else if _viewManager.toolMode == .Markup ||
  653. _viewManager.toolMode == .Edit ||
  654. _viewManager.toolMode == .Form ||
  655. _viewManager.toolMode == .Fill ||
  656. _viewManager.toolMode == .Convert ||
  657. _viewManager.toolMode == .Protect ||
  658. _viewManager.toolMode == .Tools {
  659. toolbarBoxHeightConst.constant = 80
  660. if _viewManager.subToolMode == .Redact {
  661. toolbarBoxHeightConst.constant = 40
  662. }
  663. } else {
  664. toolbarBoxHeightConst.constant = 40
  665. }
  666. }
  667. func toolbarViewModeChanged() {
  668. updatePDFViewAnnotationMode()
  669. refreshToolbarRightViewInfo()
  670. if viewManager.toolMode != .Edit && viewManager.subToolMode != .Edit_Crop {
  671. removeCropController()
  672. }
  673. }
  674. func updatePDFViewToolsType(_ viewToolsType: KMPDFViewToolsType) {
  675. viewManager.viewToolsType = viewToolsType
  676. pdfToolbarController?.reloadToolsView()
  677. if let toolbarVC = pdfToolbarController {
  678. kmPDFToolbarControllerDidViewToolsChanged(toolbarVC)
  679. }
  680. }
  681. //MARK: - 右边属性栏
  682. func refreshToolbarRightViewInfo() {
  683. //统一刷新viewManager.showRightSide, 由这个参数控制右边属性边框的展开与隐藏
  684. if viewManager.showRightSide == true {
  685. toolbarManager.rightViewProperty.state = .pressed
  686. toggleOpenRightSide()
  687. rightSideController?.reloadDataWithPDFView(pdfView: listView)
  688. } else {
  689. toggleCloseRightSide()
  690. }
  691. if viewManager.showRightSide == true {
  692. toolbarManager.rightViewProperty.state = .pressed
  693. } else {
  694. toolbarManager.rightViewProperty.state = .normal
  695. }
  696. pdfToolbarController?.reloadRightToolsView()
  697. }
  698. //MARK: - 侧边工具栏
  699. func initSideBar() {
  700. sidebarBox.borderWidth = 0
  701. if sideBarController == nil {
  702. sideBarController = KMPDFSideBarController.init()
  703. }
  704. sideBarController?.view.frame = sidebarBox.bounds
  705. sideBarController?.view.autoresizingMask = [.width, .height]
  706. sidebarBox.contentView = sideBarController?.view
  707. sideBarController?.pdfView = listView
  708. sideBarController?.delegate = self
  709. sideBarController?.pdfViewManager = viewManager
  710. sideBarController?.reloadData()
  711. }
  712. func reloadSideBar() {
  713. sideBarController?.reloadData()
  714. if viewManager.editType == .none {
  715. sideBarController?.searchItem.isHidden = false
  716. sideBarController?.thumbnailItem.isHidden = false
  717. sideBarController?.outlineItem.isHidden = false
  718. sideBarController?.bookmarkItem.isHidden = false
  719. sideBarController?.annotationItem.isHidden = false
  720. sideBarController?.aiToolItem.isHidden = false
  721. } else {
  722. sideBarController?.searchItem.isHidden = true
  723. sideBarController?.thumbnailItem.isHidden = true
  724. sideBarController?.outlineItem.isHidden = true
  725. sideBarController?.bookmarkItem.isHidden = true
  726. sideBarController?.annotationItem.isHidden = true
  727. sideBarController?.aiToolItem.isHidden = true
  728. }
  729. }
  730. //MARK: - 左边侧边栏
  731. func initLeftSideController() {
  732. if botaViewController == nil {
  733. botaViewController = KMNLeftSideViewController(listView.document)
  734. }
  735. botaViewController?.leftSideViewDelegate = self
  736. botaViewController?.view.frame = infoSplitLeftView.bounds
  737. botaViewController?.view.autoresizingMask = [.width, .height]
  738. if botaViewController != nil {
  739. infoSplitLeftView?.addSubview(botaViewController!.view)
  740. }
  741. }
  742. private func leftSidePaneIsOpen() -> Bool {
  743. return !infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) //第一次点击时存在问题,待解决
  744. }
  745. func toggleOpenLeftSide(pdfSideBarType: KMPDFSidebarType) {
  746. if(leftSidePaneIsOpen() == false) {
  747. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) as? NSNumber ?? MIN_SIDE_PANE_WIDTH
  748. infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0) //暂时无法记录上一次打开的宽度
  749. }
  750. if pdfSideBarType == .search {
  751. botaViewController?.searchViewC.handdler.pdfView = listView
  752. botaViewController?.leftsideType = .search
  753. } else if pdfSideBarType == .thumbnail {
  754. botaViewController?.leftsideType = pdfSideBarType
  755. } else if pdfSideBarType == .outline {
  756. botaViewController?.outlineViewC.handdler.pdfView = listView
  757. botaViewController?.leftsideType = pdfSideBarType
  758. } else if pdfSideBarType == .bookmark {
  759. botaViewController?.bookmarkViewC.handdler.pdfView = listView
  760. botaViewController?.leftsideType = pdfSideBarType
  761. } else if pdfSideBarType == .annotation {
  762. botaViewController?.annoController.listView = listView
  763. botaViewController?.leftsideType = .annotation
  764. } else if pdfSideBarType == .aiTools {
  765. botaViewController?.leftsideType = .aiTools
  766. }
  767. }
  768. func toggleCloseLeftSide() {
  769. if(leftSidePaneIsOpen() == true) {
  770. infoContendSplitView.setPosition(0, ofDividerAt: 0)
  771. }
  772. }
  773. //MARK: - 右侧属性栏
  774. func initRightSideController() {
  775. if rightSideController == nil {
  776. rightSideController = KMRightSideController.init()
  777. rightSideController?.delegate = self
  778. }
  779. rightSideController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, 680)
  780. rightSideController?.view.autoresizingMask = [.height, .maxXMargin]
  781. }
  782. func removeRightSideController() {
  783. rightSideController?.view.removeFromSuperview()
  784. rightSideController = nil
  785. }
  786. @objc func toggleOpenRightSide() -> Void {
  787. if rightSideController != nil {
  788. return
  789. }
  790. initRightSideController()
  791. rightSideController?.view.frame = infoSplitRightView.bounds
  792. rightSideController?.view.autoresizingMask = [.width, .height]
  793. infoSplitRightView.addSubview(rightSideController!.view)
  794. infoContendSplitView.setPosition(CGRectGetWidth(view.frame)-MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 1)
  795. rightSideController?.viewManager = self.viewManager
  796. rightSideController?.reloadDataWithPDFView(pdfView: listView)
  797. }
  798. @objc func toggleCloseRightSide() -> Void {
  799. removeRightSideController()
  800. infoContendSplitView.setPosition(CGRectGetWidth(view.frame), ofDividerAt: 1)
  801. viewManager.showRightSide = false
  802. pdfToolbarController?.reloadRightToolsView()
  803. }
  804. func refreshRightSide() -> Void {
  805. if let rightVC = rightSideController, let _ = rightSideController?.view.superview {
  806. rightVC.reloadDataWithPDFView(pdfView: listView)
  807. }
  808. }
  809. //MARK: - PDFDisplayView
  810. func updatePDFDisplaySettingView() {
  811. if viewManager.showDisplayView {
  812. infoSplitViewLeftConst.constant = 0
  813. infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0)
  814. } else {
  815. if viewManager.isPDFReadMode == false {
  816. infoSplitViewLeftConst.constant = 44
  817. if viewManager.pdfSideBarType == .none {
  818. toggleCloseLeftSide()
  819. } else {
  820. toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
  821. }
  822. } else {
  823. toggleCloseLeftSide()
  824. }
  825. }
  826. if viewManager.showDisplayView {
  827. if displaySettingController == nil {
  828. displaySettingController = KMNDisplayViewController.init()
  829. }
  830. displaySettingController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, CGRectGetHeight(bottomContendBox.frame))
  831. displaySettingController?.view.autoresizingMask = [.height, .width]
  832. infoSplitLeftView.addSubview(displaySettingController!.view)
  833. displaySettingController?.pdfView = self.listView
  834. displaySettingController?.viewManager = self.viewManager
  835. displaySettingController?.delegate = self
  836. displaySettingController?.reloadData()
  837. } else {
  838. displaySettingController?.view.removeFromSuperview()
  839. displaySettingController = nil
  840. }
  841. }
  842. //MARK: - 页面编辑
  843. func enterPageEditMode() {
  844. pageEditViewController = KMNPageEditViewController(self.document)
  845. if(pageEditViewController != nil) {
  846. bottomContendBox.addSubview(pageEditViewController!.view)
  847. pageEditViewController?.view.frame = bottomContendBox.bounds
  848. pageEditViewController?.thumbnailBaseViewDelegate = self
  849. pageEditViewController?.selectionIndexPaths = [IndexPath(item: listView.currentPageIndex, section: 0)]
  850. pageEditViewController?.view.autoresizingMask = [.width,.height]
  851. pageEditViewController?.currentUndoManager = listView.undoManager
  852. toolbarManager.page_pageInfo_Property.text = String(listView.currentPageIndex + 1)
  853. pdfToolbarController?.refreshSecondToolbarItemsState()
  854. listView.isHidden = true
  855. }
  856. }
  857. func exitPageEditMode() {
  858. if pageEditViewController != nil {
  859. pageEditViewController?.view.removeFromSuperview()
  860. pageEditViewController = nil
  861. }
  862. listView.isHidden = false
  863. if listView.document?.isModified() == true {
  864. listView.layoutDocumentView()
  865. botaViewController?.reloadData()
  866. }
  867. }
  868. //MARK: - 阅读模式
  869. func openPDFReadMode() {
  870. if viewManager.showDisplayView {
  871. UserDefaults.setDefaultBoolValue(true, toKey: "ShowDisplayViewWhenExitPDFReadMode")
  872. viewManager.showDisplayView = false
  873. pdfToolbarController?.reloadLeftIconView()
  874. updatePDFDisplaySettingView()
  875. }
  876. if infoSplitViewLeftConst.constant != 0 {
  877. infoSplitViewLeftConst.constant = 0
  878. updatePDFDisplaySettingView()
  879. }
  880. if viewManager.pdfSideBarType != .none {
  881. UserDefaults.setDefaultIntValue(viewManager.pdfSideBarType.rawValue, toKey: "viewManagerPdfSideBarTypeRawValue")
  882. viewManager.pdfSideBarType = .none
  883. }
  884. toolbarBoxHeightConst.constant = 0
  885. view.window?.makeFirstResponder(listView)
  886. let readModeMessage: ComponentMessage = ComponentMessage()
  887. readModeMessage.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode On"))
  888. readModeMessage.frame = CGRectMake((CGRectGetWidth(self.view.frame) - readModeMessage.properties.propertyInfo.viewWidth)/2,
  889. CGRectGetHeight(self.view.frame) - readModeMessage.properties.propertyInfo.viewHeight - 8,
  890. readModeMessage.properties.propertyInfo.viewWidth,
  891. readModeMessage.properties.propertyInfo.viewHeight)
  892. readModeMessage.reloadData()
  893. readModeMessage.show(inView: self.view, autoHideSeconde: 2)
  894. setUpPDFPageNumberToolbar()
  895. }
  896. func exitPDFReadMode() {
  897. viewManager.isPDFReadMode = false
  898. if UserDefaults.getDefaultBoolValue(forKey: "ShowDisplayViewWhenExitPDFReadMode") == true {
  899. if viewManager.showDisplayView == false {
  900. viewManager.showDisplayView = true
  901. pdfToolbarController?.reloadLeftIconView()
  902. }
  903. UserDefaults.setDefaultBoolValue(false, toKey: "ShowDisplayViewWhenExitPDFReadMode")
  904. }
  905. if let index = UserDefaults.getDefaultIntValue(forKey: "viewManagerPdfSideBarTypeRawValue") {
  906. let type = KMPDFSidebarType(rawValue: index) ?? .none
  907. viewManager.pdfSideBarType = type
  908. UserDefaults.standard.removeObject(forKey: "viewManagerPdfSideBarTypeRawValue")
  909. UserDefaults.standard.synchronize()
  910. }
  911. updatePDFDisplaySettingView()
  912. refreshToolbarViewHeightInfo()
  913. reloadPDFPageNumberToolbar()
  914. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  915. let readModeMessage: ComponentMessage = ComponentMessage()
  916. readModeMessage.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode Off"))
  917. readModeMessage.frame = CGRectMake((CGRectGetWidth(self.infoSplitCenterView.frame) - readModeMessage.properties.propertyInfo.viewWidth)/2,
  918. CGRectGetHeight(self.infoSplitCenterView.frame) - readModeMessage.properties.propertyInfo.viewHeight - 8,
  919. readModeMessage.properties.propertyInfo.viewWidth,
  920. readModeMessage.properties.propertyInfo.viewHeight)
  921. readModeMessage.reloadData()
  922. readModeMessage.show(inView: self.infoSplitCenterView, autoHideSeconde: 2)
  923. }
  924. }
  925. //MARK: - PPT
  926. func togglePresentation(_ sender: Any?) {
  927. if self.canExitPresentation() {
  928. exitFullScreen()
  929. } else if self.canEnterPresentation() {
  930. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  931. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  932. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  933. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  934. view.window?.enterPresentation(provider: self)
  935. }
  936. }
  937. func enterPresentationMode() {
  938. let scrollView = listView.documentView().enclosingScrollView
  939. savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: KMMainModel.Key.kHasHorizontalScroller)
  940. savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: KMMainModel.Key.kHasVerticalsCroller)
  941. savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: KMMainModel.Key.kAutoHidesScrollers)
  942. listView.backgroundColor = NSColor.clear
  943. listView.setDisplay(.singlePage)
  944. listView.autoScales = true
  945. listView.displayBox = .cropBox
  946. listView.displaysPageBreaks = false
  947. scrollView?.autohidesScrollers = true
  948. scrollView?.hasHorizontalScroller = false
  949. scrollView?.hasVerticalScroller = false
  950. listView.setCurrentSelection(nil, animate: true)
  951. }
  952. func exitPresentationMode() {
  953. NotificationCenter.default.removeObserver(self, name: NSWindow.willEnterInteractionModeNotification, object: nil)
  954. NotificationCenter.default.removeObserver(self, name: NSWindow.didEnterInteractionModeNotification, object: nil)
  955. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  956. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  957. }
  958. func exitFullScreen() {
  959. if self.canExitPresentation() == true {
  960. let mainDocument = self.myDocument as? KMMainDocument
  961. let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
  962. browserWindowController?.exitFullscreen()
  963. }
  964. }
  965. func exitFullscreenMode() {
  966. if self.interactionMode == .presentation {
  967. self.exitPresentationMode()
  968. }
  969. self.applyPDFSettings(self.savedNormalSetup)
  970. self.savedNormalSetup.removeAllObjects()
  971. listView.layoutDocumentView()
  972. listView.requiresDisplay()
  973. if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
  974. listView.backgroundColor = backgroundColor
  975. }
  976. reloadPDFSplitInfo()
  977. }
  978. func applyPDFSettings(_ setup: NSDictionary) {
  979. if let data = setup.object(forKey: KMMainModel.Key.kAutoScales) as? NSNumber {
  980. self.listView.autoScales = data.boolValue
  981. }
  982. if self.listView.autoScales == false {
  983. if let data = setup.object(forKey: KMMainModel.Key.kScaleFactor) as? NSNumber {
  984. self.listView.scaleFactor = data.floatValue.cgFloat
  985. }
  986. }
  987. if let data = setup.object(forKey: KMMainModel.Key.kDisplayMode) as? NSNumber {
  988. self.listView.setDisplay(CPDFDisplayViewMode(rawValue: data.intValue) ?? .singlePage)
  989. }
  990. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysAsBook) as? NSNumber {
  991. self.listView.displaysAsBook = data.boolValue
  992. }
  993. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysPageBreaks) as? NSNumber {
  994. self.listView.displaysPageBreaks = data.boolValue
  995. }
  996. if let data = setup.object(forKey: KMMainModel.Key.kDisplayBox) as? NSNumber {
  997. }
  998. self.listView.layoutDocumentView()
  999. }
  1000. func currentPDFSettings() -> NSDictionary {
  1001. let setup = NSMutableDictionary()
  1002. setup[KMMainModel.Key.kDisplaysPageBreaks] = NSNumber(value: listView.displaysPageBreaks)
  1003. setup[KMMainModel.Key.kDisplaysAsBook] = NSNumber(value: listView.displaysAsBook)
  1004. setup[KMMainModel.Key.kDisplayBox] = NSNumber(value: listView.displayBox.rawValue)
  1005. setup[KMMainModel.Key.kScaleFactor] = NSNumber(value: listView.scaleFactor)
  1006. setup[KMMainModel.Key.kAutoScales] = NSNumber(value: listView.autoScales)
  1007. setup[KMMainModel.Key.kDisplayMode] = NSNumber(value: listView.fetchDisplayViewMode().rawValue)
  1008. return setup
  1009. }
  1010. func canEnterFullscreen() -> Bool {
  1011. if (mwcFlags.isSwitchingFullScreen != 0) {
  1012. return false
  1013. }
  1014. if useNativeFullScreen() {
  1015. return interactionMode == .normal || interactionMode == .presentation
  1016. } else {
  1017. return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
  1018. }
  1019. }
  1020. override func canEnterPresentation() -> Bool {
  1021. let can = super.canEnterPresentation()
  1022. if can == false {
  1023. return false
  1024. }
  1025. guard let doc = self.listView.document, doc.isLocked == false else {
  1026. return false
  1027. }
  1028. return can
  1029. }
  1030. func fadeOutFullScreenWindow() {
  1031. guard let fullScreenWindow = self.view.window as? KMFullScreenWindow else {
  1032. NSSound.beep()
  1033. return
  1034. }
  1035. let mainWindow = fullScreenWindow.interactionParent
  1036. let collectionBehavior = mainWindow?.collectionBehavior
  1037. mainWindow?.alphaValue = 0
  1038. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  1039. mainWindow?.animationBehavior = .none
  1040. }
  1041. // trick to make sure the main window shows up in the same space as the fullscreen window
  1042. fullScreenWindow.addChildWindow(mainWindow!, ordered: .below)
  1043. fullScreenWindow.removeChildWindow(mainWindow!)
  1044. fullScreenWindow.level = .popUpMenu
  1045. // these can change due to the child window trick
  1046. mainWindow?.level = .normal
  1047. mainWindow?.alphaValue = 1.0
  1048. mainWindow?.collectionBehavior = collectionBehavior!
  1049. mainWindow?.display()
  1050. mainWindow?.makeFirstResponder(self.listView)
  1051. mainWindow?.recalculateKeyViewLoop()
  1052. // mainWindow?.delegate = self
  1053. mainWindow?.makeKey()
  1054. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  1055. mainWindow?.animationBehavior = .default
  1056. }
  1057. NSApp.removeWindowsItem(fullScreenWindow)
  1058. fullScreenWindow.fadeOut()
  1059. }
  1060. //MARK: - PDF分屏视图
  1061. func reloadPDFSplitInfo() {
  1062. if listView.viewSplitMode == .disable {
  1063. pdfSplitView.isHidden = true
  1064. listView.frame = infoSplitCenterView.bounds
  1065. infoSplitCenterView.addSubview(listView)
  1066. if splitPDFController != nil {
  1067. splitPDFController = nil
  1068. }
  1069. } else {
  1070. pdfSplitView.isHidden = false
  1071. listView.frame = pdfSplitTopView.bounds
  1072. pdfSplitTopView.addSubview(listView)
  1073. setUpPDFPageNumberToolbar()
  1074. setupSplitPDFController()
  1075. if listView.viewSplitMode == .horizontal {
  1076. pdfSplitView.isVertical = false
  1077. } else if listView.viewSplitMode == .vertical {
  1078. pdfSplitView.isVertical = true
  1079. }
  1080. }
  1081. }
  1082. func setUpPDFPageNumberToolbar() {
  1083. if pageNumberToolbar != nil {
  1084. pageNumberToolbar?.removeFromSuperview()
  1085. pageNumberToolbar = nil
  1086. }
  1087. if pageNumberToolbar == nil {
  1088. pageNumberToolbar = KMPageNumberPromptView.init()
  1089. }
  1090. pageNumberToolbar?.frame = CGRectMake(CGRectGetWidth(listView.frame)/2-144, 20, 288, 40)
  1091. pageNumberToolbar?.autoresizingMask = [.minXMargin, .maxXMargin, .maxYMargin]
  1092. pageNumberToolbar?.pdfView = self.listView
  1093. pageNumberToolbar?.reloadData()
  1094. pageNumberToolbar?.isHidden = true
  1095. listView.addSubview(pageNumberToolbar!)
  1096. reloadPDFPageNumberToolbar()
  1097. }
  1098. func reloadPDFPageNumberToolbar() {
  1099. if viewManager.isPDFReadMode == true ||
  1100. (viewManager.splitShowBottomBar && listView.viewSplitMode != .disable) {
  1101. pageNumberToolbar?.isHidden = false
  1102. pageNumberToolbar?.reloadData()
  1103. } else {
  1104. pageNumberToolbar?.isHidden = true
  1105. }
  1106. }
  1107. //MARK: - Edit模式
  1108. func showEditToolbarView() {
  1109. if editToolbarView == nil {
  1110. editToolbarView = KMEditToolbarView()
  1111. }
  1112. editToolbarView?.frame = toolbarBox.bounds
  1113. editToolbarView?.delegate = self
  1114. editToolbarView?.autoresizingMask = [.width, .height]
  1115. toolbarBox.contentView = editToolbarView
  1116. reloadSideBar()
  1117. }
  1118. func exitEditToolbarView() {
  1119. viewManager.editType = .none
  1120. viewManager.subToolMode = .None
  1121. editToolbarView?.removeFromSuperview()
  1122. editToolbarView = nil
  1123. watermarkViewController?.view.removeFromSuperview()
  1124. watermarkViewController = nil
  1125. backgroundViewController?.view.removeFromSuperview()
  1126. backgroundViewController = nil
  1127. headerFooterViewController?.view.removeFromSuperview()
  1128. headerFooterViewController = nil
  1129. batesViewController?.view.removeFromSuperview()
  1130. batesViewController = nil
  1131. refreshToolbarViewHeightInfo()
  1132. toolbarBox.contentView = pdfToolbarController?.view
  1133. updatePDFViewAnnotationMode()
  1134. reloadSideBar()
  1135. }
  1136. func updateEditModeDocumentWhenPageChanged() {
  1137. if viewManager.editType == .watermark {
  1138. updateWatermarkDocument()
  1139. } else if viewManager.editType == .background {
  1140. updateBackgroundDocument()
  1141. } else if viewManager.editType == .header_Footer {
  1142. updateHeaderFooterDocument()
  1143. } else if viewManager.editType == .bates {
  1144. updateBatesDocument()
  1145. } else if viewManager.subToolMode == .Edit_Crop {
  1146. updateCropDocument()
  1147. }
  1148. }
  1149. //MARK: - 数字签名
  1150. func writeSignatureToWidget(_ widget: CPDFSignatureWidgetAnnotation, _ path: String, _ password: String, _ config: CPDFSignatureConfig, _ isLock: Bool) ->() {
  1151. let fileName = listView.document.documentURL?.lastPathComponent
  1152. let fileNameWithoutExtension = URL(fileURLWithPath: fileName!).deletingPathExtension().lastPathComponent
  1153. let outputSavePanel = NSSavePanel()
  1154. outputSavePanel.directoryURL = listView.document.documentURL.deletingLastPathComponent()
  1155. outputSavePanel.title = NSLocalizedString("", comment: "Save as PDF")
  1156. outputSavePanel.allowedFileTypes = ["pdf"]
  1157. outputSavePanel.nameFieldStringValue = fileNameWithoutExtension + "_" + NSLocalizedString("Signed", comment: "")
  1158. let result = outputSavePanel.runModal()
  1159. if result == .OK {
  1160. let contentArr = NSMutableArray()
  1161. var locationStr = ""
  1162. var reasonStr = NSLocalizedString("none", comment: "")
  1163. for item in config.contents {
  1164. if item.key == NSLocalizedString("Reason", comment: "") {
  1165. if item.value == NSLocalizedString("<your signing reason here>", comment: "") {
  1166. item.value = " " + NSLocalizedString("none", comment: "")
  1167. }
  1168. reasonStr = item.value
  1169. } else if item.key == NSLocalizedString("Location", comment: "") {
  1170. if item.value == NSLocalizedString("<your signing location here>", comment: "") {
  1171. item.value = " "
  1172. }
  1173. locationStr = item.value
  1174. }
  1175. contentArr.add(item)
  1176. }
  1177. config.contents = contentArr as? [CPDFSignatureConfigItem]
  1178. widget.setFieldName(widget.getValidName(inPage: widget.page))
  1179. widget.signAppearanceConfig(config)
  1180. let success = listView.document.writeSignature(to: outputSavePanel.url, withWidget: widget, pkcs12Cert: path, password: password, location: locationStr, reason: reasonStr, permissions: .forbidChange)
  1181. widget.removeSignature()
  1182. if success {
  1183. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1184. NSDocumentController.shared.openDocument(withContentsOf: outputSavePanel.url!, display: true) { document, documentWasAlreadyOpen, error in
  1185. if error != nil {
  1186. NSApp.presentError(error!)
  1187. return
  1188. }
  1189. }
  1190. }
  1191. } else {
  1192. let alert = NSAlert.init()
  1193. alert.messageText = NSLocalizedString("Save failed!", comment: "")
  1194. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  1195. alert.runModal()
  1196. }
  1197. widget.page.removeAnnotation(widget)
  1198. listView.setNeedsDisplayAnnotationViewFor(widget.page)
  1199. } else {
  1200. widget.page.removeAnnotation(widget)
  1201. listView.setNeedsDisplayAnnotationViewFor(widget.page)
  1202. }
  1203. }
  1204. func popUpSignatureWidgetState(_ signature: CPDFSignature, _ pdfListView: CPDFListView) ->(){
  1205. signaturestateVC.signature = signature
  1206. signaturestateVC.pdfListView = pdfListView
  1207. signaturestateVC.actionBlock = { [weak self, weak signaturestateVC] stateVCSelf, actionType in
  1208. guard let weakSelf = self, let stateVC = signaturestateVC else { return }
  1209. if actionType == .cancel {
  1210. stateVC.dismiss(stateVCSelf)
  1211. } else if actionType == .confirm {
  1212. if let signer = signature.signers.first, let data = signer.certificates {
  1213. let signatureDetail = DSignatureDetailsViewController.init()
  1214. signatureDetail.certificates = data
  1215. signatureDetail.signature = signature
  1216. signatureDetail.pdfListView = pdfListView
  1217. stateVCSelf.presentAsSheet(signatureDetail)
  1218. } else {
  1219. NSSound.beep()
  1220. }
  1221. }
  1222. }
  1223. self.presentAsSheet(signaturestateVC)
  1224. signaturestateVC.reloadData()
  1225. }
  1226. // MARK: - 显示合并窗口
  1227. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  1228. DispatchQueue.main.async {
  1229. var documentURL = url
  1230. if documentURL == nil {
  1231. documentURL = self.listView.document?.documentURL
  1232. }
  1233. guard let _url = documentURL else { return }
  1234. guard let document = PDFDocument(url: _url) else { return }
  1235. self.mergeWindowController = KMMergeWindowController(document: document, password: password ?? "")
  1236. self.mergeWindowController!.oriDucumentUrl = self.listView.document?.documentURL
  1237. self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
  1238. self.mergeWindowController!.cancelAction = { [unowned self] controller in
  1239. self.view.window?.endSheet(mergeWindowController!.window!)
  1240. }
  1241. self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
  1242. self.view.window?.endSheet(mergeWindowController!.window!)
  1243. }
  1244. self.view.window?.beginSheet(self.mergeWindowController!.window!)
  1245. }
  1246. }
  1247. //MARK: - Crop裁剪
  1248. func showCropController() {
  1249. if cropController == nil {
  1250. cropController = KMCropController.init()
  1251. cropController?.view.frame = infoSplitCenterView.bounds
  1252. cropController?.view.autoresizingMask = [.width, .height]
  1253. cropController?.delegate = self
  1254. infoSplitCenterView.addSubview(cropController!.view)
  1255. updateCropDocument()
  1256. if viewManager.showRightSide == false {
  1257. viewManager.showRightSide = true
  1258. refreshToolbarRightViewInfo()
  1259. }
  1260. }
  1261. }
  1262. func updateCropDocument() {
  1263. guard let controller = cropController else { return }
  1264. controller.pdfDocument = nil
  1265. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1266. let editDocument = CPDFDocument.init()
  1267. editDocument?.insertPageObject(page, at: 0)
  1268. if let editPage = editDocument?.page(at: 0) {
  1269. let mediaRect = editPage.bounds(for: .mediaBox)
  1270. editPage.setBounds(mediaRect, for: .cropBox)
  1271. controller.selectionRect = page?.bounds(for: .cropBox) ?? .zero
  1272. }
  1273. controller.pdfDocument = editDocument
  1274. controller.reloadData()
  1275. }
  1276. func removeCropController() {
  1277. if cropController != nil {
  1278. cropController?.view.removeFromSuperview()
  1279. cropController = nil
  1280. toolbarManager.edit_crop_Property.state = .normal
  1281. }
  1282. }
  1283. // MARK: - Secure 【安全】
  1284. public func hiddenSecureLimitTip() {
  1285. }
  1286. func savePageNumberIfNeed() {
  1287. let scaleFactor = self.listView.scaleFactor ?? 0
  1288. if scaleFactor <= 0 {
  1289. return
  1290. }
  1291. if self.listView.document != nil {
  1292. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  1293. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  1294. }
  1295. }
  1296. // MARK: - 显示加密弹窗
  1297. public func showSecureWindow() {
  1298. guard let url = self.listView.document?.documentURL else {
  1299. return
  1300. }
  1301. self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  1302. guard let securityWindowController = securityWindowController else { return }
  1303. securityWindowController.documentURL = self.listView.document?.documentURL
  1304. securityWindowController.batchAction = { [unowned self] controller, files in
  1305. self.view.window?.endSheet((securityWindowController.window)!)
  1306. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1307. let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
  1308. batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
  1309. batchWindowController.window?.makeKeyAndOrderFront("")
  1310. }
  1311. securityWindowController.doneAction = { [unowned self] controller, options, attribute in
  1312. let openPanel = NSOpenPanel()
  1313. openPanel.canChooseFiles = false
  1314. openPanel.canChooseDirectories = true
  1315. openPanel.canCreateDirectories = true
  1316. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  1317. if result == NSApplication.ModalResponse.OK {
  1318. for fileURL in openPanel.urls {
  1319. let document = CPDFDocument(url: self.document?.documentURL)
  1320. if document != nil {
  1321. document!.setDocumentAttributes(attribute)
  1322. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  1323. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  1324. if success {
  1325. self.view.window?.endSheet((securityWindowController.window)!)
  1326. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  1327. }
  1328. }
  1329. }
  1330. }
  1331. }
  1332. }
  1333. securityWindowController.cancelAction = { [unowned self] controller in
  1334. self.view.window?.endSheet((securityWindowController.window)!)
  1335. }
  1336. NSWindow.currentWindow().beginSheet(securityWindowController.window!)
  1337. }
  1338. // MARK: - 移除文档密码
  1339. public func showRemoveSecureWindow() {
  1340. var isDocumentLocked: Bool = false
  1341. if self.document?.allowsCopying == false || self.document?.allowsPrinting == false {
  1342. isDocumentLocked = true
  1343. } else if (self.document?.password ?? "").count > 0 {
  1344. isDocumentLocked = true
  1345. }
  1346. if isDocumentLocked == false {
  1347. let alert = NSAlert()
  1348. alert.alertStyle = .warning
  1349. alert.messageText = KMLocalizedString("This document doesn’t contain any security settings and doesn‘t need to be removed.")
  1350. alert.addButton(withTitle: KMLocalizedString("OK"))
  1351. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  1352. }
  1353. } else {
  1354. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  1355. controller.pdfDocument = self.document
  1356. self.currentWindowController = controller
  1357. controller.batchAction = { [unowned self] controller, files in
  1358. self.view.window?.endSheet((self.currentWindowController.window)!)
  1359. self.currentWindowController = nil
  1360. var array: [URL] = []
  1361. for item in files {
  1362. array.append(NSURL(fileURLWithPath: item.filePath) as URL)
  1363. }
  1364. self.showBatchWindow(type: .batchRemove, files: array)
  1365. }
  1366. controller.cancelAction = { [unowned self] controller in
  1367. self.view.window?.endSheet((self.currentWindowController.window)!)
  1368. self.currentWindowController = nil
  1369. }
  1370. controller.doneAction = { [unowned self] controller in
  1371. self.view.window?.endSheet((self.currentWindowController.window)!)
  1372. self.currentWindowController = nil
  1373. NSWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  1374. if success {
  1375. let savePanel = NSSavePanel()
  1376. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  1377. savePanel.allowedFileTypes = ["pdf"]
  1378. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  1379. guard result == .OK else { return }
  1380. /// 删除安全性设置
  1381. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1382. self.model.isSaveKeyChain = false
  1383. self.listView.document.unlock(withPassword: resultPassword)
  1384. }
  1385. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  1386. guard let document = document else { return }
  1387. document.unlock(withPassword: resultPassword)
  1388. let success = document.writeDecrypt(to: savePanel.url)
  1389. if success {
  1390. self.hiddenSecureLimitTip()
  1391. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  1392. } else {
  1393. self.hiddenSecureLimitTip()
  1394. }
  1395. }
  1396. }
  1397. }
  1398. }
  1399. NSWindow.currentWindow().beginSheet(controller.window!)
  1400. }
  1401. }
  1402. //MARK: - Unlock Document
  1403. func unlockPDFDocument() {
  1404. NSWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  1405. self.listView.document.unlock(withPassword: resultPassword)
  1406. }
  1407. }
  1408. //MARK: - Watermark水印
  1409. func showWatermarkController() {
  1410. viewManager.editType = .watermark
  1411. showEditToolbarView()
  1412. editToolbarView?.editType = .watermark
  1413. if KMWatermarkManager.defaultManager.watermarks.count == 0 {
  1414. editToolbarView?.editSubType = .add
  1415. } else {
  1416. editToolbarView?.editSubType = .template
  1417. }
  1418. editToolbarView?.reloadData()
  1419. if watermarkViewController == nil {
  1420. watermarkViewController = KMWatermarkController.init()
  1421. }
  1422. watermarkViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1423. watermarkViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1424. watermarkViewController?.delegate = self
  1425. bottomContendBox.contentView?.addSubview(watermarkViewController!.view)
  1426. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1427. watermarkViewController?.reloadData()
  1428. updateWatermarkDocument()
  1429. watermarkViewController?.loadData()
  1430. }
  1431. func updateWatermarkDocument() {
  1432. guard let controller = watermarkViewController else { return }
  1433. var editDocument = CPDFDocument.init()
  1434. if let vcDoc = controller.pdfDocument {
  1435. editDocument = vcDoc
  1436. }
  1437. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1438. editDocument?.insertPageObject(page, at: 0)
  1439. if editDocument?.pageCount == 2 {
  1440. let theIndex = IndexSet(integer: 1)
  1441. editDocument?.removePage(at: theIndex)
  1442. }
  1443. if watermarkViewController?.pdfDocument == nil {
  1444. watermarkViewController?.pdfDocument = editDocument
  1445. }
  1446. watermarkViewController?.resetUI()
  1447. watermarkViewController?.reloadData()
  1448. }
  1449. //移除文档水印
  1450. func removePDFWatermark() {
  1451. let watermarks = self.listView.document.watermarks()
  1452. if (watermarks == nil || watermarks!.count <= 0) {
  1453. let alert = NSAlert()
  1454. alert.alertStyle = .warning
  1455. 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: "")
  1456. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  1457. alert.runModal()
  1458. return
  1459. }
  1460. let alert = NSAlert()
  1461. alert.alertStyle = .warning
  1462. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  1463. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1464. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1465. let result = alert.runModal()
  1466. if (result == .alertFirstButtonReturn) {
  1467. for watermark in watermarks! {
  1468. listView.document.removeWatermark(watermark)
  1469. }
  1470. listView.layoutDocumentView()
  1471. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Watermark removed"),
  1472. type: .success,
  1473. fromView: bottomContendBox,
  1474. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1475. }
  1476. }
  1477. func batchAddWatermark() {
  1478. self.showBatchWindow(type: .watermark, files: nil)
  1479. }
  1480. func batchRemoveWatermark() {
  1481. self.showBatchWindow(type: .batchRemove, files: nil)
  1482. }
  1483. //MARK: - PopUI
  1484. func reloadPopUIWindow() {
  1485. if listView.toolMode == .CSelectToolMode {
  1486. let pageRect = listView.currentSelectionRect()
  1487. let page:CPDFPage? = listView.currentSelectionPage()
  1488. if listView.selectionRect != CGRectZero && page != nil {
  1489. let positioningRect = listView.convert(pageRect, from: page)
  1490. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1491. reloadPopUIOperation()
  1492. return
  1493. }
  1494. }
  1495. toggleClosePopUIWindow()
  1496. } else if listView.toolMode == .COCRToolMode {
  1497. let pageRect = listView.currentSelectionRect()
  1498. let page:CPDFPage? = listView.currentSelectionPage()
  1499. if listView.selectionRect != CGRectZero && page != nil {
  1500. let positioningRect = listView.convert(pageRect, from: page)
  1501. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1502. reloadPopUIOperation()
  1503. return
  1504. }
  1505. }
  1506. toggleClosePopUIWindow()
  1507. } else if(listView.isEditing() == false) {
  1508. let activeAnnotations:[CPDFAnnotation] = listView.activeAnnotations as! [CPDFAnnotation]
  1509. if(activeAnnotations.count > 0) {
  1510. if let page = activeAnnotations.first?.page {
  1511. let pageRect = listView.selectionMultipleBounds(with: activeAnnotations)
  1512. let positioningRect = listView.convert(pageRect, from: page)
  1513. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1514. reloadPopUIActiveAnnotations(activeAnnotations: activeAnnotations)
  1515. } else {
  1516. toggleClosePopUIWindow()
  1517. }
  1518. } else {
  1519. toggleClosePopUIWindow()
  1520. }
  1521. } else {
  1522. toggleClosePopUIWindow()
  1523. }
  1524. if(listView.popOver?.isShown == true || (groupListMenuGroup?.superview) != nil) { //右键菜单弹出时,或者Pop编辑框弹出时不显示Pop
  1525. toggleClosePopUIWindow()
  1526. }
  1527. } else {
  1528. let editAreas:[CPDFEditArea] = listView.km_EditingAreas()
  1529. if(editAreas.count > 0) {
  1530. if let page = editAreas.first?.page {
  1531. let pageRect = listView.selectionMultipleBounds(withEditArea: editAreas)
  1532. let positioningRect = listView.convert(pageRect, from: page)
  1533. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1534. reloadPopUIContentEdits(editAreas: editAreas)
  1535. } else {
  1536. toggleClosePopUIWindow()
  1537. }
  1538. } else {
  1539. toggleClosePopUIWindow()
  1540. }
  1541. } else {
  1542. toggleClosePopUIWindow()
  1543. }
  1544. if(listView.popOver?.isShown == true || (groupListMenuGroup?.superview) != nil) { //右键菜单弹出时,或者Pop编辑框弹出时不显示Pop
  1545. toggleClosePopUIWindow()
  1546. }
  1547. }
  1548. }
  1549. func toggleClosePopUIWindow() {
  1550. let popWindow = KMNPopAnnotationWindowController.shared
  1551. if popWindow.window?.isVisible == true {
  1552. closeAnnotationPopWindow()
  1553. }
  1554. let editPopWindow = KMNPopContentEditWindowController.shared
  1555. if editPopWindow.window?.isVisible == true {
  1556. closePopContentEditWindow()
  1557. }
  1558. let operationWindow = KMNPopOperationWindowController.shared
  1559. if operationWindow.window?.isVisible == true {
  1560. closePopOperationWindow()
  1561. }
  1562. }
  1563. func closeAnnotationPopWindow() {
  1564. KMNPopAnnotationWindowController.shared.closeWindow(listView: listView)
  1565. }
  1566. func closePopContentEditWindow() {
  1567. KMNPopContentEditWindowController.shared.closeWindow(listView: listView)
  1568. }
  1569. func closePopOperationWindow() {
  1570. KMNPopOperationWindowController.shared.closeWindow(listView: listView)
  1571. }
  1572. func reloadPopUIOperation() {
  1573. if listView.selectionRect != CGRectZero {
  1574. let popWindow = KMNPopOperationWindowController.shared
  1575. if popWindow.window?.isVisible == false {
  1576. listView.window?.addChildWindow(popWindow.window ?? NSWindow(), ordered: .above)
  1577. }
  1578. popWindow.listView = listView
  1579. if listView.toolMode == .CSelectToolMode {
  1580. popWindow.popType = .crop
  1581. popWindow.cropCurrentCallback = {[weak self] in
  1582. let rect = self?.listView.currentSelectionRect() ?? CGRect.zero
  1583. let orgPage : CPDFPage = self?.listView.currentSelectionPage() ?? CPDFPage()
  1584. self?.cropPages(atIndexs: [orgPage.pageIndex()], to: [rect])
  1585. self?.closePopOperationWindow()
  1586. }
  1587. } else if listView.toolMode == .COCRToolMode {
  1588. popWindow.popType = .ocr
  1589. popWindow.OCRAction = { [weak self] in
  1590. self?.convertSelectionRectOCR(rect: self?.listView.currentSelectionRect() ?? CGRectZero)
  1591. }
  1592. }
  1593. popWindow.updatePDFViewCallback = {[weak self] in
  1594. self?.closePopOperationWindow()
  1595. self?.listView.setNeedsDisplayForVisiblePages()
  1596. }
  1597. updatePopOperationPopWinodwFrame()
  1598. } else {
  1599. closePopOperationWindow()
  1600. }
  1601. }
  1602. func reloadPopUIActiveAnnotations(activeAnnotations:[CPDFAnnotation]) {
  1603. let annotationMode = KMNAnnotationPopMode(pdfAnnotations: activeAnnotations )
  1604. let popWindow = KMNPopAnnotationWindowController.shared
  1605. if annotationMode.popType == .popTypeNone || !SettingsManager.sharedInstance.showQuickActionBar {
  1606. closeAnnotationPopWindow()
  1607. } else {
  1608. if popWindow.window?.isVisible == false {
  1609. listView.window?.addChildWindow(popWindow.window ?? NSWindow(), ordered: .above)
  1610. }
  1611. popWindow.listView = listView
  1612. popWindow.annotationPopMode = annotationMode
  1613. popWindow.isOpenPane = viewManager.showRightSide
  1614. updateAnnotationsPopWinodwFrame()
  1615. popWindow.updatePDFViewCallback = {[weak self] in
  1616. self?.rightSideController?.reloadDataWithPDFView(pdfView: self?.listView ?? CPDFListView())
  1617. self?.listView.setNeedsDisplayMultiAnnotations(annotationMode.annotations)
  1618. NotificationCenter.default.post(name: toolbarImageColorChangedNotificationName, object: nil)
  1619. }
  1620. popWindow.paneCallback = {[weak self] isOpen in
  1621. if isOpen == true {
  1622. self?.viewManager.showRightSide = true
  1623. } else {
  1624. self?.viewManager.showRightSide = false
  1625. }
  1626. self?.refreshToolbarRightViewInfo()
  1627. }
  1628. }
  1629. }
  1630. func reloadPopUIContentEdits(editAreas:[CPDFEditArea]) {
  1631. let editingAreas = listView.km_EditingAreas()
  1632. let editMode = KMNEditContentPopMode(currentEditAreas: editingAreas)
  1633. let popWindow = KMNPopContentEditWindowController.shared
  1634. if editMode.popType == .editNone || !SettingsManager.sharedInstance.showQuickActionBar {
  1635. closePopContentEditWindow()
  1636. } else {
  1637. listView.window?.addChildWindow(popWindow.window ?? NSWindow(), ordered: .above)
  1638. popWindow.listView = listView
  1639. popWindow.editContentPopMode = editMode
  1640. popWindow.isOpenPane = viewManager.showRightSide
  1641. updateContentEditPopWinodwFrame()
  1642. popWindow.paneCallback = {[weak self] isOpen in
  1643. if isOpen == true && self?.viewManager.showRightSide == false {
  1644. self?.viewManager.showRightSide = false
  1645. } else {
  1646. self?.viewManager.showRightSide = true
  1647. }
  1648. self?.refreshToolbarRightViewInfo()
  1649. }
  1650. }
  1651. }
  1652. func updateAnnotationsPopWinodwFrame() {
  1653. let popWindow = KMNPopAnnotationWindowController.shared
  1654. if popWindow.window?.isVisible == true {
  1655. popWindow.updateFrame(listView: listView)
  1656. }
  1657. }
  1658. func updateContentEditPopWinodwFrame() {
  1659. let popWindow = KMNPopContentEditWindowController.shared
  1660. if popWindow.window?.isVisible == true {
  1661. popWindow.updateFrame(listView: listView)
  1662. }
  1663. }
  1664. func updatePopOperationPopWinodwFrame() {
  1665. let popWindow = KMNPopOperationWindowController.shared
  1666. if popWindow.window?.isVisible == true {
  1667. popWindow.updateFrame(listView: listView,page: listView.currentSelectionPage())
  1668. }
  1669. }
  1670. //MARK: - 安全
  1671. func removeOwnerPassword() {
  1672. guard let doc = listView.document else {
  1673. NSSound.beep()
  1674. return
  1675. }
  1676. if doc.permissionsStatus != .user {
  1677. NSSound.beep()
  1678. return
  1679. }
  1680. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  1681. if result == .cancel { /// 关闭
  1682. return
  1683. }
  1684. self?.listView.document?.unlock(withPassword: password)
  1685. if doc.permissionsStatus == .owner {
  1686. self?.alertTipViewController.reloadSecureAlertUI()
  1687. self?.alertTipViewController.reloadAlertUIFrame()
  1688. }
  1689. }
  1690. }
  1691. //MARK: - Background背景
  1692. func showBackgroundController() {
  1693. viewManager.editType = .background
  1694. showEditToolbarView()
  1695. editToolbarView?.editType = .background
  1696. if KMBackgroundManager.defaultManager.datas.count == 0 {
  1697. editToolbarView?.editSubType = .add
  1698. } else {
  1699. editToolbarView?.editSubType = .template
  1700. }
  1701. editToolbarView?.reloadData()
  1702. if backgroundViewController == nil {
  1703. backgroundViewController = KMBackgroundController.init()
  1704. }
  1705. backgroundViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1706. backgroundViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1707. backgroundViewController?.delegate = self
  1708. bottomContendBox.contentView?.addSubview(backgroundViewController!.view)
  1709. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1710. backgroundViewController?.resetUI()
  1711. updateBackgroundDocument()
  1712. }
  1713. func updateBackgroundDocument() {
  1714. guard let controller = backgroundViewController else { return }
  1715. controller.pdfDocument = nil
  1716. let editDocument = CPDFDocument.init()
  1717. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1718. editDocument?.insertPageObject(page, at: 0)
  1719. backgroundViewController?.pdfDocument = editDocument
  1720. backgroundViewController?.reloadData()
  1721. }
  1722. func removePDFBackground() {
  1723. let alert = NSAlert()
  1724. alert.alertStyle = .warning
  1725. alert.messageText = NSLocalizedString("Are you sure you want to remove the background?", comment: "")
  1726. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1727. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1728. let result = alert.runModal()
  1729. if (result == .alertFirstButtonReturn) {
  1730. let background = listView.document.background()
  1731. background?.clear()
  1732. listView.document?.refreshPageData()
  1733. listView.layoutDocumentView()
  1734. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Background removed"),
  1735. type: .success,
  1736. fromView: bottomContendBox,
  1737. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1738. }
  1739. }
  1740. func batchAddBackground() {
  1741. self.showBatchWindow(type: .background, files: nil)
  1742. }
  1743. func batchRemoveBackground() {
  1744. self.showBatchWindow(type: .batchRemove, files: nil)
  1745. }
  1746. //MARK: - header&footer
  1747. func showHeaderFooterController() {
  1748. viewManager.editType = .header_Footer
  1749. showEditToolbarView()
  1750. editToolbarView?.editType = .header_Footer
  1751. if KMHeaderFooterManager.defaultManager.headFooterObjects.count == 0 {
  1752. editToolbarView?.editSubType = .add
  1753. } else {
  1754. editToolbarView?.editSubType = .template
  1755. }
  1756. editToolbarView?.reloadData()
  1757. if headerFooterViewController == nil {
  1758. headerFooterViewController = KMHeaderFooterController.init()
  1759. }
  1760. headerFooterViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1761. headerFooterViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1762. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  1763. headerFooterViewController?.delegate = self
  1764. bottomContendBox.contentView?.addSubview(headerFooterViewController!.view)
  1765. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1766. updateHeaderFooterDocument()
  1767. }
  1768. func updateHeaderFooterDocument() {
  1769. guard let controller = headerFooterViewController else { return }
  1770. controller.pdfDocument = nil
  1771. let editDocument = CPDFDocument.init()
  1772. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1773. editDocument?.insertPageObject(page, at: 0)
  1774. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  1775. headerFooterViewController?.pdfDocument = editDocument
  1776. headerFooterViewController?.resetUI()
  1777. headerFooterViewController?.reloadData()
  1778. }
  1779. func removeHeaderFooter() {
  1780. let alert = NSAlert()
  1781. alert.alertStyle = .warning
  1782. alert.messageText = NSLocalizedString("Are you sure you want to remove the Header & Footer?", comment: "")
  1783. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1784. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1785. let result = alert.runModal()
  1786. if (result == .alertFirstButtonReturn) {
  1787. let headerFooter = listView.document.headerFooter()
  1788. headerFooter?.clear()
  1789. listView.document?.refreshPageData()
  1790. listView.layoutDocumentView()
  1791. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Header & Footer removed"),
  1792. type: .success,
  1793. fromView: bottomContendBox,
  1794. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1795. }
  1796. }
  1797. func batchAddHeaderFooter() {
  1798. self.showBatchWindow(type: .headerAndFooter, files: nil)
  1799. }
  1800. func batchRemoveHeaderFooter() {
  1801. self.showBatchWindow(type: .batchRemove, files: nil)
  1802. }
  1803. //MARK: - Bates
  1804. func showBatesController() {
  1805. viewManager.editType = .bates
  1806. showEditToolbarView()
  1807. editToolbarView?.editType = viewManager.editType
  1808. if KMBatesManager.defaultManager.datas.count == 0 {
  1809. editToolbarView?.editSubType = .add
  1810. } else {
  1811. editToolbarView?.editSubType = .template
  1812. }
  1813. editToolbarView?.reloadData()
  1814. if batesViewController == nil {
  1815. batesViewController = KMBatesController.init()
  1816. }
  1817. batesViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1818. batesViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1819. batesViewController?.delegate = self
  1820. batesViewController?.totalPDFCount = Int(listView.document.pageCount)
  1821. bottomContendBox.contentView?.addSubview(batesViewController!.view)
  1822. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1823. updateBatesDocument()
  1824. batesViewController?.resetUI()
  1825. }
  1826. func updateBatesDocument() {
  1827. guard let controller = batesViewController else { return }
  1828. controller.pdfDocument = nil
  1829. let editDocument = CPDFDocument.init()
  1830. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1831. editDocument?.insertPageObject(page, at: 0)
  1832. batesViewController?.pdfDocument = editDocument
  1833. batesViewController?.reloadData()
  1834. }
  1835. func removePDFBates() {
  1836. let alert = NSAlert()
  1837. alert.alertStyle = .warning
  1838. alert.messageText = NSLocalizedString("Are you sure you want to remove the Bates?", comment: "")
  1839. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1840. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1841. let result = alert.runModal()
  1842. if (result == .alertFirstButtonReturn) {
  1843. let bates = listView.document.bates()
  1844. bates?.clear()
  1845. listView.document?.refreshPageData()
  1846. listView.layoutDocumentView()
  1847. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Bates removed"),
  1848. type: .success,
  1849. fromView: bottomContendBox,
  1850. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1851. }
  1852. }
  1853. func batchAddBates() {
  1854. self.showBatchWindow(type: .batesNumber, files: nil)
  1855. }
  1856. func batchRemoveBates() {
  1857. self.showBatchWindow(type: .batchRemove, files: nil)
  1858. }
  1859. //MARK: - Crop Action
  1860. // 白边距,统一大小
  1861. @objc func auto_cropPagesWhiteMargin(_ pageIndexs: [UInt]) {
  1862. var size = NSZeroSize
  1863. for i in pageIndexs {
  1864. let page = self.listView.document.page(at: i)
  1865. let rect = KMCropTools.getPageForegroundBox(page!)
  1866. size.width = fmax(size.width, NSWidth(rect))
  1867. size.height = fmax(size.height, NSHeight(rect))
  1868. }
  1869. var rectArray: Array<NSRect> = []
  1870. for i in pageIndexs {
  1871. progressC?.increment(by: Double(i))
  1872. progressC?.doubleValue = Double(i)
  1873. let page = self.listView.document.page(at: i)
  1874. var rect = KMCropTools.getPageForegroundBox(page!)
  1875. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1876. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1877. rect.origin.x = rect.maxX-size.width
  1878. }
  1879. rect.origin.y = rect.maxY-size.height
  1880. rect.size = size
  1881. if (NSWidth(rect) > NSWidth(bounds)) {
  1882. rect.size.width = NSWidth(bounds)
  1883. }
  1884. if (NSHeight(rect) > NSHeight(bounds)) {
  1885. rect.size.height = NSHeight(bounds)
  1886. }
  1887. if (NSMinX(rect) < NSMinX(bounds)) {
  1888. rect.origin.x = NSMinX(bounds)
  1889. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1890. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1891. }
  1892. if (NSMinY(rect) < NSMinY(bounds)) {
  1893. rect.origin.y = NSMinY(bounds)
  1894. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1895. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1896. }
  1897. rectArray.append(rect)
  1898. }
  1899. self.cropPages(atIndexs: pageIndexs, to: rectArray)
  1900. }
  1901. func cropPages(atIndexs pageIndexs: [UInt], to rects: Array<NSRect>) {
  1902. let currentPage = self.listView.currentPage()
  1903. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1904. var oldRectArray: Array<NSRect> = []
  1905. let rectCount = rects.count
  1906. for i in pageIndexs {
  1907. if let page = self.listView.document.page(at: i) {
  1908. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page.bounds(for: .mediaBox)))
  1909. let oldRect = page.bounds(for: .cropBox)
  1910. oldRectArray.append(oldRect)
  1911. page.setBounds(rect, for: .cropBox)
  1912. }
  1913. }
  1914. let undoManager = self.listView.undoManager
  1915. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(atIndexs: pageIndexs, to: oldRectArray)
  1916. /// 刷新预览视图
  1917. self.listView.layoutDocumentView()
  1918. self.listView.displayBox = .cropBox
  1919. self.listView.go(to: currentPage)
  1920. self.listView.go(to: visibleRect, on: currentPage)
  1921. }
  1922. //MARK: - 文件对比
  1923. func beginCompareAction(_ index: Int) {
  1924. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  1925. self.currentWindowController = controller
  1926. controller.password = self.document?.password ?? ""
  1927. controller.filePath = (self.document?.documentURL.path)!
  1928. controller.cancelAction = { [unowned self] controller in
  1929. self.view.window?.endSheet((self.currentWindowController.window)!)
  1930. self.currentWindowController = nil
  1931. }
  1932. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  1933. self.view.window?.endSheet((self.currentWindowController.window)!)
  1934. self.currentWindowController = nil
  1935. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  1936. }
  1937. controller.coveringComplete = { [unowned self] controller, document in
  1938. self.view.window?.endSheet((self.currentWindowController.window)!)
  1939. self.currentWindowController = nil
  1940. self.openCoveringCompareVC(with: document)
  1941. }
  1942. if index == 1 {
  1943. controller.fileType = .content
  1944. } else {
  1945. controller.fileType = .coverting
  1946. }
  1947. NSWindow.currentWindow().beginSheet(controller.window!)
  1948. }
  1949. //文件对比
  1950. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  1951. self.isCompareModel = true
  1952. let compareContentView = KMCompareContentView()
  1953. compareContentView.oldDocument = oldDocument
  1954. compareContentView.document = document
  1955. compareContentView.compareResults = results
  1956. compareContentView.saveHandle = { [unowned self] view in
  1957. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  1958. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  1959. self.currentWindowController = saveController
  1960. saveController.cancelHandle = { [unowned self] controller in
  1961. self.view.window!.endSheet(controller.window!)
  1962. self.currentWindowController = nil
  1963. }
  1964. saveController.saveHandle = { [unowned self] controller, saveType in
  1965. let folderPath = controller.fileSaveFolderPath
  1966. if folderPath != nil {
  1967. if !FileManager.default.fileExists(atPath: folderPath) {
  1968. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  1969. }
  1970. #if VERSION_DMG
  1971. #else
  1972. let url = URL(fileURLWithPath: folderPath)
  1973. let fileAccess = AppSandboxFileAccess()
  1974. fileAccess?.persistPermissionURL(url)
  1975. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  1976. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  1977. let urlString = url.path
  1978. let _url = URL(fileURLWithPath: urlString)
  1979. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  1980. }
  1981. #endif
  1982. var savePath: String
  1983. switch saveType {
  1984. case 0:
  1985. let filePath = oldDocument.documentURL.path
  1986. let fileName = filePath.deletingPathExtension.lastPathComponent
  1987. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  1988. savePath = self.getValidFilePath(savePath)
  1989. oldDocument.write(to: URL(fileURLWithPath: savePath))
  1990. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1991. case 1:
  1992. let filePath = document.documentURL.path
  1993. let fileName = filePath.deletingPathExtension.lastPathComponent
  1994. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  1995. savePath = self.getValidFilePath(savePath)
  1996. document.write(to: URL(fileURLWithPath: savePath))
  1997. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1998. case 2:
  1999. let filePath = oldDocument.documentURL.path
  2000. let fileName = filePath.deletingPathExtension.lastPathComponent
  2001. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  2002. savePath = self.getValidFilePath(savePath)
  2003. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  2004. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2005. default:
  2006. break
  2007. }
  2008. }
  2009. self.view.window!.endSheet(controller.window!)
  2010. self.currentWindowController = nil
  2011. }
  2012. NSWindow.currentWindow().beginSheet(saveController.window!)
  2013. }
  2014. }
  2015. compareContentView.closeHandle = { [unowned self] view in
  2016. self.isCompareModel = false
  2017. view.removeFromSuperview()
  2018. }
  2019. contendBox.addSubview(compareContentView)
  2020. compareContentView.frame = contendBox.bounds
  2021. compareContentView.autoresizingMask = [.width,.height]
  2022. }
  2023. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  2024. self.isCompareModel = true
  2025. let coveringView = KMCompareCoveringView()
  2026. coveringView.pdfDocument = pdfDocument
  2027. coveringView.closeHandle = { [unowned self] view in
  2028. self.isCompareModel = false
  2029. view.removeFromSuperview()
  2030. }
  2031. coveringView.saveHandle = { [unowned self] view in
  2032. let savePanel = NSSavePanel()
  2033. savePanel.nameFieldStringValue = "untitled"
  2034. savePanel.allowedFileTypes = ["pdf"]
  2035. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  2036. if result == .OK {
  2037. pdfDocument.write(to: savePanel.url!)
  2038. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2039. }
  2040. }
  2041. }
  2042. contendBox.addSubview(coveringView)
  2043. coveringView.frame = contendBox.bounds
  2044. coveringView.autoresizingMask = [.width,.height]
  2045. }
  2046. func getValidFilePath(_ oldPath: String) -> String {
  2047. let fileManager = FileManager.default
  2048. do {
  2049. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  2050. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  2051. return oldPath
  2052. }
  2053. var i = 1
  2054. var newPath = oldPath
  2055. while fileManager.fileExists(atPath: newPath) {
  2056. if fileType == FileAttributeType.typeDirectory.rawValue {
  2057. newPath = oldPath + "(\(i))"
  2058. } else {
  2059. let fileExtension = (oldPath as NSString).pathExtension
  2060. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  2061. }
  2062. i += 1
  2063. }
  2064. return newPath
  2065. } catch {
  2066. print("Error getting file attributes: \(error)")
  2067. return oldPath
  2068. }
  2069. }
  2070. //MARK: - TTS
  2071. @IBAction func startSpeaking(_ sender: Any?) {
  2072. self.showTTSWindow()
  2073. let ttsView = KMTTSWindowController.share
  2074. // ttsView.buttonItemClick_Play(ttsView.playButton)
  2075. }
  2076. @IBAction func stopSpeaking(_ sender: Any) {
  2077. let ttsWindowC = KMTTSWindowController.share
  2078. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
  2079. if let data = ttsWindowC.window?.isVisible, data {
  2080. ttsWindowC.stopSpeaking()
  2081. ttsWindowC.close()
  2082. }
  2083. }
  2084. }
  2085. func showTTSWindow() {
  2086. var lastPDFView: CPDFView?
  2087. let ttsView = KMTTSWindowController.share
  2088. if (ttsView.window?.isVisible ?? false) {
  2089. lastPDFView = ttsView.pdfView
  2090. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  2091. lastPDFView = nil
  2092. ttsView.window?.orderOut(nil)
  2093. } else {
  2094. ttsView.pdfView = self.listView
  2095. ttsView.showWindow(nil)
  2096. }
  2097. } else {
  2098. ttsView.pdfView = self.listView
  2099. ttsView.showWindow(nil)
  2100. }
  2101. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  2102. if isCloseWindow {
  2103. }
  2104. }
  2105. if let currentSelection = self.listView.currentSelection {
  2106. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  2107. ttsView.startSpeakingPDFSelection(currentSelection)
  2108. }
  2109. }
  2110. if let lastPDFView = lastPDFView {
  2111. lastPDFView.setHighlightedSelections([])
  2112. ttsView.stopSpeaking()
  2113. }
  2114. }
  2115. //MARK: 导出图片
  2116. func extractImageAction(num: Int) {
  2117. if !IAPProductsManager.default().isAvailableAllFunction(){
  2118. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2119. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  2120. winC?.showWindow(nil)
  2121. return
  2122. }
  2123. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2124. let alert = NSAlert()
  2125. alert.alertStyle = .critical
  2126. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2127. alert.runModal()
  2128. return
  2129. }
  2130. let document = self.listView.document
  2131. var fileURL = document?.documentURL
  2132. if num == 1 {
  2133. let pageCount = document?.pageCount ?? 0
  2134. let indeSet = NSMutableIndexSet()
  2135. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2136. if indeSet.count == 0 {
  2137. return
  2138. }
  2139. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2140. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2141. let outputSavePanel = NSSavePanel()
  2142. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2143. outputSavePanel.allowsOtherFileTypes = true
  2144. outputSavePanel.isExtensionHidden = true
  2145. outputSavePanel.canCreateDirectories = true
  2146. outputSavePanel.nameFieldStringValue = tFileName
  2147. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2148. if result == NSApplication.ModalResponse.OK {
  2149. DispatchQueue.main.async {
  2150. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2151. let tDestFile = outputSavePanel.url!.path
  2152. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2153. let pdfconverter = PDFConvertObject()
  2154. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2155. self.dismissProgressSheet()
  2156. let fileManager = FileManager.default
  2157. if fileManager.fileExists(atPath: tDestFile) {
  2158. let workspace = NSWorkspace.shared
  2159. let url = URL(fileURLWithPath: tDestFile)
  2160. workspace.activateFileViewerSelecting([url])
  2161. }
  2162. }
  2163. }
  2164. })
  2165. return
  2166. }
  2167. if fileURL != nil {
  2168. self.myDocument?.save(nil)
  2169. } else {
  2170. let myDocument = self.myDocument
  2171. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2172. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2173. if writeSuccess {
  2174. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2175. fileURL = document?.documentURL
  2176. } else {
  2177. NSSound.beep()
  2178. return
  2179. }
  2180. }
  2181. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2182. extract?.docPath = fileURL?.path ?? ""
  2183. extract?.password = document?.password ?? ""
  2184. extract?.currentPage = self.listView.currentPageIndex
  2185. extract?.own_beginSheetModal(for: self.view.window, completionHandler: { result in
  2186. })
  2187. extract?.selectCurrentPageBtn()
  2188. }
  2189. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2190. let progress = SKProgressController()
  2191. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2192. progress.window?.contentView?.wantsLayer = true
  2193. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2194. progress.progressField.textColor = NSColor.white
  2195. progress.message = NSLocalizedString("Converting...", comment: "")
  2196. progressC = progress
  2197. progressC?.message = message
  2198. if maxValue > 0 {
  2199. progressC?.indeterminate = false
  2200. progressC?.maxValue = Double(maxValue)
  2201. progressC?.progressBar.doubleValue = 0.3
  2202. } else {
  2203. progressC?.indeterminate = true
  2204. }
  2205. progressC?.own_beginSheetModal(for: self.view.window, completionHandler: { result in
  2206. })
  2207. }
  2208. func dismissProgressSheet() {
  2209. progressC?.stopAnimation()
  2210. progressC?.own_closeEndSheet()
  2211. progressC = nil
  2212. }
  2213. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2214. let newArr = NSMutableArray()
  2215. for item in files {
  2216. newArr.add(item.filePath)
  2217. }
  2218. return newArr as! [String]
  2219. }
  2220. //MARK: - 打印
  2221. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2222. self.saveDocument()
  2223. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2224. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2225. if (result == .cancel) {
  2226. return
  2227. }
  2228. // 解除权限
  2229. self?.listView.document.unlock(withPassword: password)
  2230. // 隐藏提示
  2231. self?.hiddenSecureLimitTip()
  2232. // 去打印
  2233. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  2234. }
  2235. return
  2236. }
  2237. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  2238. }
  2239. //Poster
  2240. func showPosterPrintWindow() {
  2241. guard let document = self.document else { return }
  2242. guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
  2243. if self.posterPrintWindowController == nil {
  2244. posterPrintWindowController = KMPDFPosterPrintWindowController.init(pdfDocument: pdfDocument)
  2245. }
  2246. if let window = posterPrintWindowController?.window {
  2247. NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
  2248. })
  2249. }
  2250. }
  2251. //Multiple
  2252. func showMultiplePrintWindow() {
  2253. guard let document = self.document else { return }
  2254. guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
  2255. if self.multiplePrintWindowController == nil {
  2256. multiplePrintWindowController = KMPDFMultiplePrintWindowController.init(pdfDocument: pdfDocument)
  2257. }
  2258. if let window = multiplePrintWindowController?.window {
  2259. NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
  2260. })
  2261. }
  2262. }
  2263. //Booklet
  2264. func showBookletPrintWindow() {
  2265. guard let document = self.document else { return }
  2266. guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
  2267. if self.bookletWindowController == nil {
  2268. bookletWindowController = KMPDFBookletWindowController.init(document: pdfDocument)
  2269. }
  2270. if let window = bookletWindowController?.window {
  2271. NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
  2272. })
  2273. }
  2274. }
  2275. //MARK: - FileInfo
  2276. func showFileInfo() {
  2277. KMInfoWindowController.shared.showWindow(nil)
  2278. }
  2279. //MARK: - Share Action
  2280. @objc private func shareDocument(sender: NSView) {
  2281. let document = self.listView.document ?? CPDFDocument()
  2282. if document?.documentURL == nil {
  2283. return
  2284. }
  2285. var doucumentURL : URL = self.listView.document.documentURL
  2286. if doucumentURL.path.count > 0 {
  2287. let docDir = NSTemporaryDirectory()
  2288. let documentName : String = doucumentURL.path.lastPathComponent
  2289. let path = docDir.stringByAppendingPathComponent(documentName)
  2290. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2291. if writeSuccess == false {
  2292. __NSBeep()
  2293. return;
  2294. }
  2295. doucumentURL = URL(fileURLWithPath: path)
  2296. }
  2297. let array = [doucumentURL]
  2298. let picker = NSSharingServicePicker.init(items: array)
  2299. if sender.window != nil {
  2300. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2301. } else {
  2302. 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)
  2303. }
  2304. }
  2305. @objc private func shareFlatten(sender: NSView) {
  2306. let document = self.listView.document ?? CPDFDocument()
  2307. var path: String?
  2308. if document?.documentURL != nil {
  2309. path = document?.documentURL.path ?? ""
  2310. }
  2311. if path?.count ?? 0 > 0 {
  2312. let docDir = NSTemporaryDirectory()
  2313. let documentName : String = path?.lastPathComponent ?? ""
  2314. path = docDir.stringByAppendingPathComponent(documentName)
  2315. }
  2316. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2317. var tfileName = path?.deletingPathExtension.lastPathComponent
  2318. let tStdFileSuffix = "_flatten"
  2319. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2320. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2321. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  2322. if success {
  2323. let url = URL(fileURLWithPath: path ?? "")
  2324. let picker = NSSharingServicePicker.init(items: [url])
  2325. if sender.window != nil {
  2326. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2327. } else {
  2328. 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)
  2329. }
  2330. }
  2331. }
  2332. @objc private func shareOriginalPDF(sender: NSView) {
  2333. guard let pdfDoc = self.listView.document else {
  2334. NSSound.beep()
  2335. return
  2336. }
  2337. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  2338. let alert = NSAlert()
  2339. alert.alertStyle = .critical
  2340. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2341. alert.runModal()
  2342. return
  2343. }
  2344. let document = self.listView.document ?? CPDFDocument()
  2345. var path: String?
  2346. if document?.documentURL != nil {
  2347. path = document?.documentURL.path ?? ""
  2348. }
  2349. if path?.count ?? 0 > 0 {
  2350. let docDir = NSTemporaryDirectory()
  2351. let documentName : String = path?.lastPathComponent ?? ""
  2352. path = docDir.stringByAppendingPathComponent(documentName)
  2353. }
  2354. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  2355. if writeSuccess == false {
  2356. __NSBeep()
  2357. return;
  2358. }
  2359. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2360. let cnt = newDocument?.pageCount ?? 0
  2361. for i in 0 ..< cnt {
  2362. let page = newDocument!.page(at: i)
  2363. var annotations : [CPDFAnnotation] = []
  2364. for annotation in page!.annotations {
  2365. annotations.append(annotation)
  2366. }
  2367. for annotation in annotations {
  2368. annotation.page.removeAnnotation(annotation)
  2369. }
  2370. }
  2371. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  2372. if writeSuccess ?? false {
  2373. let url = URL(fileURLWithPath: path ?? "")
  2374. let picker = NSSharingServicePicker.init(items: [url])
  2375. if sender.window != nil {
  2376. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2377. } else {
  2378. 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)
  2379. }
  2380. }
  2381. }
  2382. @objc func shareFromService(sender: NSMenuItem) {
  2383. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  2384. return
  2385. }
  2386. var string = ""
  2387. if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  2388. string = freeTextAnnotation.contents ?? ""
  2389. } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
  2390. if let page = markupAnnotation.page {
  2391. if let selection = page.selection(for: markupAnnotation.bounds) {
  2392. string = selection.string() ?? ""
  2393. }
  2394. }
  2395. } else {
  2396. string = listView.currentSelection?.string() ?? ""
  2397. }
  2398. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  2399. let model = windowControler.browser?.tabStripModel
  2400. if let cnt = model?.count(), cnt <= 0 {
  2401. return
  2402. }
  2403. if let data = model?.activeTabContents().isHome, data {
  2404. return
  2405. }
  2406. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  2407. if string.count > 0 {
  2408. let represent : NSSharingService = sender.representedObject as! NSSharingService
  2409. represent.perform(withItems: [string])
  2410. return
  2411. }
  2412. let represent = sender.representedObject as? NSSharingService
  2413. represent?.perform(withItems: [string])
  2414. }
  2415. //MARK: - PDFView Menu
  2416. func clickPresentationMenu(point:NSPoint)->KMNMenuStruct {
  2417. var viewHeight: CGFloat = 8
  2418. var menuItemArr: [ComponentMenuitemProperty] = []
  2419. var items: [(String, String)] = []
  2420. items.append(("Next Page", PDFViewMenuIdentifier_PageNext))
  2421. items.append(("Previous Page", PDFViewMenuIdentifier_PagePrevious))
  2422. items.append(("First", PDFViewMenuIdentifier_PageFirst))
  2423. items.append(("Last", PDFViewMenuIdentifier_PageLast))
  2424. items.append(("", ""))
  2425. items.append(("Laser pointer", PDFViewMenuIdentifier_Presentation_LaserPoint))
  2426. items.append(("Brush", PDFViewMenuIdentifier_Presentation_Brush))
  2427. items.append(("", ""))
  2428. items.append(("Exit Presentation", PDFViewMenuIdentifier_Presentation_Exit))
  2429. for (i, value) in items {
  2430. if value.count == 0 {
  2431. let property: ComponentMenuitemProperty = ComponentMenuitemProperty.divider()
  2432. menuItemArr.append(property)
  2433. viewHeight += 8
  2434. } else {
  2435. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  2436. itemSelected: false,
  2437. isDisabled: false,
  2438. keyEquivalent: nil,
  2439. text: KMLocalizedString(i),
  2440. identifier: value,representedObject: point)
  2441. if value == PDFViewMenuIdentifier_PageNext {
  2442. properties_Menuitem.keyEquivalent = "▶"
  2443. } else if value == PDFViewMenuIdentifier_PagePrevious {
  2444. properties_Menuitem.keyEquivalent = "◀"
  2445. } else if value == PDFViewMenuIdentifier_PageFirst {
  2446. properties_Menuitem.keyEquivalent = "⌘ ◀"
  2447. } else if value == PDFViewMenuIdentifier_PageLast {
  2448. properties_Menuitem.keyEquivalent = "⌘ ▶"
  2449. } else if value == PDFViewMenuIdentifier_Presentation_Exit {
  2450. properties_Menuitem.keyEquivalent = "ESC"
  2451. }
  2452. if(value == PDFViewMenuIdentifier_Presentation_LaserPoint) {
  2453. if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
  2454. } else {
  2455. properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
  2456. }
  2457. } else if value == PDFViewMenuIdentifier_Presentation_Brush {
  2458. if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
  2459. properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
  2460. } else {
  2461. }
  2462. }
  2463. menuItemArr.append(properties_Menuitem)
  2464. viewHeight += 36
  2465. }
  2466. }
  2467. let menuStruct = KMNMenuStruct(menuitems: menuItemArr, viewHeight: viewHeight)
  2468. return menuStruct
  2469. }
  2470. func gotoPage(_ sender: Any?) {
  2471. var pages : [String] = []
  2472. for i in 0 ..< self.listView.document.pageCount {
  2473. pages.append("\(i)")
  2474. }
  2475. self.textFieldSheet.callback = { [weak self] stringValue in
  2476. guard let index = Int(stringValue) else {
  2477. return
  2478. }
  2479. if (self?.listView == nil) {
  2480. return
  2481. }
  2482. if (index > 0 && index <= self!.listView.document.pageCount) {
  2483. self?.listView.go(toPageIndex: index-1, animated: true)
  2484. }
  2485. }
  2486. self.textFieldSheet.showWindow(nil)
  2487. self.textFieldSheet.pageBox.addItems(withObjectValues: pages)
  2488. self.textFieldSheet.stringValue = "\(self.listView.currentPageIndex+1)"
  2489. }
  2490. //MARK: - 添加书签
  2491. @objc func menuItemBookMarkClick_add(sender:NSMenuItem?) {
  2492. if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  2493. let index = self.listView.currentPageIndex
  2494. self.listView.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  2495. self.listView.setNeedsDisplayForVisiblePages()
  2496. } else {
  2497. self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  2498. self.listView.setNeedsDisplayForVisiblePages()
  2499. }
  2500. self.listView.undoManager?.setActionName("")//添加undo事件就可删除
  2501. }
  2502. //MARK: - 页面旋转
  2503. func rotateLeft(page:CPDFPage,listView:CPDFListView?) {
  2504. Task { @MainActor in
  2505. let rotation = page.rotation
  2506. page.leftRotate()
  2507. listView?.layoutDocumentView()
  2508. if(listView == self.listView) {
  2509. var pageIndexes = IndexSet()
  2510. pageIndexes.insert(Int(page.pageIndex()))
  2511. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  2512. botaViewController?.reloadData()
  2513. }
  2514. }
  2515. }
  2516. func rotateRight(page:CPDFPage,listView:CPDFListView?) {
  2517. Task { @MainActor in
  2518. let rotation = page.rotation
  2519. page.rightRotate()
  2520. listView?.layoutDocumentView()
  2521. if(listView == self.listView) {
  2522. var pageIndexes = IndexSet()
  2523. pageIndexes.insert(Int(page.pageIndex()))
  2524. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  2525. botaViewController?.reloadData()
  2526. }
  2527. }
  2528. }
  2529. //MARK: - 自动滚动
  2530. func isAutoFlowOn() -> Bool {
  2531. return listView.isAutoFlow()
  2532. }
  2533. func toggleAutoFlow(_ sender: Any?) {
  2534. if (listView.isAutoFlow()) {
  2535. listView.stopAutoFlow()
  2536. } else {
  2537. listView.startAutoFlow()
  2538. }
  2539. }
  2540. //MARK: - 高亮Form
  2541. func highlightFormFiled(_ sender: Any?) {
  2542. let enabled = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
  2543. CPDFKitConfig.sharedInstance().setEnableFormFieldHighlight(!enabled)
  2544. listView.setNeedsDisplayForVisiblePages()
  2545. }
  2546. //MARK: - 高亮Link
  2547. func highlightLinks(_ sender: Any?) {
  2548. let enabled = CPDFKitConfig.sharedInstance().enableLinkFieldHighlight()
  2549. CPDFAnnotation.updateLinkFieldHighlight(listView, linkFieldHighlight: !enabled)
  2550. }
  2551. //MARK: - 重置Form
  2552. func resetForm(_ sender: Any?) {
  2553. listView.resetFormAnnotation()
  2554. }
  2555. //MARK: - 属性
  2556. @IBAction func menuItemAction_property(_ sender: Any?) {
  2557. showFileInfo()
  2558. }
  2559. //MARK: - 打印
  2560. @IBAction func menuItemAction_print(_ sender: Any?) {
  2561. self.showPrintWindow()
  2562. }
  2563. //MARK: - Flattened
  2564. func saveAsFlattenedPDFAction() {
  2565. DispatchQueue.main.async {
  2566. NSPanel.savePanel(self.view.window!, true) { panel in
  2567. panel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_flatten" + ".pdf"
  2568. } completion: { response, url, isOpen in
  2569. if (response == .cancel) {
  2570. return
  2571. }
  2572. var result = self.listView.document.writeFlatten(to: url!)
  2573. if (!result) {
  2574. return
  2575. }
  2576. if (isOpen) {
  2577. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
  2578. }
  2579. } else {
  2580. NSWorkspace.shared.activateFileViewerSelecting([url!])
  2581. }
  2582. }
  2583. }
  2584. }
  2585. func showInFinder() {
  2586. NSWorkspace.shared.activateFileViewerSelecting([self.listView.document.documentURL])
  2587. }
  2588. //MARK: - DisplayViewMode
  2589. func getPDFViewPageLayoutType() -> pageLayoutType {
  2590. if listView.displayMode() == .singlePage {
  2591. return .singlePage
  2592. } else if listView.displayMode() == .singlePageContinuous {
  2593. return .singlePageContinue
  2594. } else if listView.displayMode() == .twoUp {
  2595. if listView.displaysAsBook == true {
  2596. return .bookMode
  2597. }
  2598. return .twoPage
  2599. } else if listView.displayMode() == .twoUpContinuous {
  2600. if listView.displaysAsBook == true {
  2601. return .bookMode
  2602. }
  2603. return .twoPageContinue
  2604. }
  2605. return .singlePage
  2606. }
  2607. func updatePDFViewDisplayMode(viewMode mode: CPDFDisplayViewMode = .singlePage, isbookMode bookMode: Bool = false, direction directionValue: CPDFDisplayDirection? = nil) {
  2608. if bookMode == true {
  2609. //书本模式
  2610. listView.displaysAsBook = true
  2611. listView.displayTwoUp = true
  2612. if let value = directionValue {
  2613. listView.displayDirection = value
  2614. }
  2615. } else {
  2616. listView.setDisplay(mode)
  2617. }
  2618. listView.layoutDocumentView()
  2619. }
  2620. //MARK: - 新增大纲
  2621. @objc func addOutLineItemAction() {
  2622. botaViewController?.outlineViewC.addOutline()
  2623. }
  2624. //MARK: - 搜索
  2625. @objc func searchBaiduAction() {
  2626. let label = self.listView.currentSelection?.string() ?? ""
  2627. let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  2628. if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
  2629. NSWorkspace.shared.open(url)
  2630. }
  2631. }
  2632. //MARK: - 转档
  2633. func showConvertWindow(_ convertType: KMPDFConvertType) {
  2634. var winC: KMConvertBaseWindowController = KMConvertBaseWindowController()
  2635. if convertType == .word {
  2636. winC = KMConvertWordWindowController()
  2637. let model = KMDocumentModel(url: listView.document.documentURL)
  2638. winC.documentModel = model
  2639. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2640. } else if convertType == .ppt {
  2641. winC = KMConvertPPTsWindowController()
  2642. winC.subType = 1
  2643. let model = KMDocumentModel(url: listView.document.documentURL)
  2644. winC.documentModel = model
  2645. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2646. } else if convertType == .rtf {
  2647. winC = KMConvertPPTsWindowController()
  2648. winC.subType = 2
  2649. let model = KMDocumentModel(url: listView.document.documentURL)
  2650. winC.documentModel = model
  2651. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2652. } else if convertType == .text {
  2653. winC = KMConvertPPTsWindowController()
  2654. winC.subType = 4
  2655. let model = KMDocumentModel(url: listView.document.documentURL)
  2656. winC.documentModel = model
  2657. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2658. } else if convertType == .csv {
  2659. winC = KMConvertPPTsWindowController()
  2660. winC.subType = 5
  2661. let model = KMDocumentModel(url: listView.document.documentURL)
  2662. winC.documentModel = model
  2663. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2664. } else if convertType == .excel {
  2665. winC = KMConvertExcelWindowController()
  2666. let model = KMDocumentModel(url: listView.document.documentURL)
  2667. winC.documentModel = model
  2668. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2669. } else if convertType == .html {
  2670. winC = KMConvertHtmlWindowController()
  2671. let model = KMDocumentModel(url: listView.document.documentURL)
  2672. winC.documentModel = model
  2673. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2674. } else if convertType == .json {
  2675. winC = KMConvertJsonWindowController()
  2676. let model = KMDocumentModel(url: listView.document.documentURL)
  2677. winC.documentModel = model
  2678. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  2679. } else if convertType == .jpeg ||
  2680. convertType == .jpg ||
  2681. convertType == .png ||
  2682. convertType == .gif ||
  2683. convertType == .tiff ||
  2684. convertType == .tga ||
  2685. convertType == .bmp ||
  2686. convertType == .jp2{
  2687. winC = KMConvertImageWindowController()
  2688. let model = KMDocumentModel(url: listView.document.documentURL)
  2689. winC.documentModel = model
  2690. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  2691. if let settingView = winC.settingView as? KMConvertImageSettingView {
  2692. settingView.selectConvertType(convertType: convertType)
  2693. }
  2694. }
  2695. winC.batchAction = { [unowned self] in
  2696. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  2697. model.password = listView.document.password ?? ""
  2698. self.showBatchWindow(type: .convertPDF, subType: convertType.rawValue, files: [], fileModels: [model])
  2699. }
  2700. }
  2701. //MARK: - 选择Form注释
  2702. @objc func selectAllFormAnnotation () {
  2703. var formActiveAnnotations:[CPDFAnnotation] = []
  2704. for i in 0 ..< listView.document.pageCount {
  2705. let page = listView.document.page(at: i)
  2706. let annotations = page?.annotations
  2707. for j in 0 ..< (annotations?.count ?? 0) {
  2708. if let an = annotations?[j] as? CPDFAnnotation {
  2709. if (an.isKind(of: CPDFWidgetAnnotation.self) == true) {
  2710. formActiveAnnotations.append(an)
  2711. }
  2712. }
  2713. }
  2714. }
  2715. listView.updateActiveAnnotations(formActiveAnnotations)
  2716. }
  2717. @objc func selectAllNomerAnnotation () {
  2718. var normalActiveAnnotations:[CPDFAnnotation] = []
  2719. for i in 0 ..< listView.document.pageCount {
  2720. let page = listView.document.page(at: i)
  2721. let annotations = page?.annotations
  2722. for j in 0 ..< (annotations?.count ?? 0) {
  2723. if let an = annotations?[j] as? CPDFAnnotation {
  2724. if an.isKind(of: CPDFWidgetAnnotation.self) == true ||
  2725. an.isKind(of: CPDFLinkAnnotation.self) == true ||
  2726. an.isKind(of: CPDFRedactAnnotation.self) == true {
  2727. } else {
  2728. normalActiveAnnotations.append(an)
  2729. }
  2730. }
  2731. }
  2732. }
  2733. listView.updateActiveAnnotations(normalActiveAnnotations)
  2734. }
  2735. //MARK: 搜索 & 替换
  2736. func showSearchPopWindow(type: KMNBotaSearchType, keyborad: String?, replaceText: String?, results: [KMSearchMode]) {
  2737. let toolMode = self.listView.toolMode
  2738. let isEditing = self.listView.isEditing()
  2739. var winH: CGFloat = 112
  2740. if type == .replace {
  2741. if IAPProductsManager.default().isAvailableAllFunction() == false {
  2742. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2743. winC?.kEventName = "Reading_ReplaceText_BuyNow"
  2744. winC?.showWindow(nil)
  2745. return
  2746. }
  2747. if toolMode == .CEditPDFToolMode && isEditing {
  2748. } else { // 进入内容编辑模式
  2749. viewManager.toolMode = .Edit
  2750. updatePDFViewAnnotationMode()
  2751. }
  2752. winH = 208
  2753. }
  2754. self.view.window?.makeFirstResponder(nil)
  2755. let winC = KMSearchReplaceWindowController(with: listView, type: type)
  2756. self.currentWindowController = winC
  2757. winC.replaceCallback = { [weak self] in
  2758. let toolMode = self?.listView.toolMode ?? .none
  2759. let isEditing = self?.listView.isEditing() ?? false
  2760. if toolMode == .CEditPDFToolMode && isEditing {
  2761. } else { // 进入内容编辑模式
  2762. self?.viewManager.toolMode = .Edit
  2763. self?.updatePDFViewAnnotationMode()
  2764. }
  2765. }
  2766. winC.itemClick = { [weak self] idx, params in
  2767. if idx == 1 {
  2768. self?.toggleOpenLeftSide(pdfSideBarType: .search)
  2769. guard let handdler = params.first as? KMNSearchHanddler else {
  2770. return
  2771. }
  2772. let viewC = self?.botaViewController?.searchViewC
  2773. viewC?.update(keyborad: handdler.searchKey, replaceKey: handdler.replaceKey, results: handdler.searchSectionResults)
  2774. }
  2775. }
  2776. let targetView = self.pdfToolbarController?.leftViewButton
  2777. let point = targetView?.convert(targetView?.frame.origin ?? .zero, to: nil) ?? .zero
  2778. // 200 248
  2779. let x = point.x + (self.view.window?.frame.origin.x ?? 0) - 32
  2780. let y = point.y + (self.view.window?.frame.origin.y ?? 0) - winH - 32
  2781. let winFramePoint = NSPoint(x: x, y: y)
  2782. winC.window?.setFrameOrigin(winFramePoint)
  2783. winC.update(keyborad: keyborad, replaceKey: replaceText, results: results)
  2784. self.view.window?.addChildWindow(winC.window!, ordered: .above)
  2785. }
  2786. // MARK: -显示加密弹窗
  2787. //MARK: - Redact密文
  2788. func showRedactProperty(readactAnnotation: CPDFRedactAnnotation?) {
  2789. let properties = KMRedactPropertiesWindowController()
  2790. properties.readactAnnotation = readactAnnotation
  2791. properties.own_beginSheetModal(for: self.view.window) { result in
  2792. }
  2793. }
  2794. //MARK: - 测量
  2795. func refreshMeasureInfo() {
  2796. if distanceMeasureInfoWindowController == nil {
  2797. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2798. }
  2799. if perimeterMeasureInfoWindowController == nil {
  2800. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2801. }
  2802. if areaMeasureInfoWindowController == nil {
  2803. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2804. }
  2805. showMeasureFloatingWindowsIfNeed()
  2806. }
  2807. @objc func cancelMeasureType() {
  2808. self.hideMeasureFloatingWindows()
  2809. }
  2810. func hideMeasureFloatingWindows() {
  2811. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2812. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2813. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  2814. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2815. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2816. areaMeasureInfoWindowController?.hideFloatingWindow()
  2817. }
  2818. }
  2819. func showMeasureFloatingWindowsIfNeed() {
  2820. cancelMeasureType()
  2821. let toolMode = self.listView.toolMode
  2822. if toolMode != .CNoteToolMode {
  2823. return
  2824. }
  2825. if let data = self.listView.activeAnnotation as? CPDFPolylineAnnotation {
  2826. } else if let data = self.listView.activeAnnotation as? CPDFPolygonAnnotation {
  2827. } else if let data = self.listView.activeAnnotation as? CPDFLineAnnotation, data.isMeasure {
  2828. } else {
  2829. let type = self.listView.annotationType
  2830. if type == .measureLine {
  2831. distanceMeasureInfoWindowController?.measureInfo = listView.distanceMeasureInfo
  2832. distanceMeasureInfoWindowController?.window?.orderFront(nil)
  2833. } else if type == .measurePolyLine {
  2834. perimeterMeasureInfoWindowController?.measureInfo = listView.perimeterMeasureInfo
  2835. perimeterMeasureInfoWindowController?.window?.orderFront(nil)
  2836. } else if type == .measurePolyGon {
  2837. areaMeasureInfoWindowController?.measureInfo = listView.polygonAreaMeasureInfo
  2838. areaMeasureInfoWindowController?.window?.orderFront(nil)
  2839. } else if type == .measureSquare {
  2840. areaMeasureInfoWindowController?.measureInfo = listView.squareAreaMeasureInfo
  2841. areaMeasureInfoWindowController?.window?.orderFront(nil)
  2842. } else {
  2843. cancelMeasureType()
  2844. }
  2845. }
  2846. }
  2847. func showMeasureSettingWindow() {
  2848. let distanceSettingWC = CDistanceSettingWindowController(measureInfo: self.listView.distanceMeasureInfo)
  2849. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2850. distanceSettingWC.delegate = self
  2851. distanceSettingWC.own_beginSheetModal(for: self.view.window) { string in
  2852. }
  2853. }
  2854. }
  2855. //MARK: Compress
  2856. extension KMMainViewController {
  2857. func showCompressController(_ url: URL) {
  2858. KMPasswordInputWindow.openWindow(window: NSWindow.currentWindow(), type: .owner, url: url) { [unowned self] result, password in
  2859. if (result == .success) {
  2860. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  2861. model.password = password ?? ""
  2862. model.isLock = false
  2863. self.showCompressController(model: model)
  2864. }
  2865. }
  2866. }
  2867. func showCompressController(model: KMBatchProcessingTableViewModel) {
  2868. let document = CPDFDocument(url: model.filePath.fileURL)
  2869. document?.unlock(withPassword: model.password)
  2870. if !document!.allowsPrinting && !document!.allowsCopying {
  2871. KMPasswordInputWindow.openWindow(window: NSWindow.currentWindow(), type: .owner, url: document!.documentURL) { [unowned self] result, password in
  2872. if (result == .success) {
  2873. // let model = KMBatchProcessingTableViewModel.initWithFilePath(url: model.filePath.fileURL)
  2874. model.password = password ?? ""
  2875. model.isLock = false
  2876. self.showCompress(model: model)
  2877. }
  2878. }
  2879. }
  2880. }
  2881. func showCompress(model: KMBatchProcessingTableViewModel) {
  2882. self.compressWindowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  2883. self.compressWindowController?.password = model.password
  2884. self.compressWindowController?.documentURL = model.filePath.fileURL
  2885. let controllerWindow = self.view.window
  2886. controllerWindow?.beginSheet(self.compressWindowController!.window!)
  2887. self.compressWindowController?.itemClick = { [unowned self] in
  2888. controllerWindow?.endSheet((self.compressWindowController?.window)!)
  2889. }
  2890. self.compressWindowController?.batchAction = { [unowned self] view, filePaths in
  2891. controllerWindow?.endSheet((self.compressWindowController?.window)!)
  2892. self.showBatchWindow(type: .compress, files: filePaths)
  2893. }
  2894. self.compressWindowController?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  2895. controllerWindow?.endSheet((self.compressWindowController?.window)!)
  2896. if (result) {
  2897. if (openDocument) {
  2898. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2899. } else {
  2900. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2901. }
  2902. } else {
  2903. let alert = NSAlert()
  2904. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2905. alert.runModal()
  2906. }
  2907. }
  2908. }
  2909. }
  2910. //MARK: - OCR
  2911. extension KMMainViewController {
  2912. //window
  2913. func showOCRWindow() {
  2914. if !IAPProductsManager.default().isAvailableAllFunction(){
  2915. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2916. winC?.showWindow(nil)
  2917. return
  2918. }
  2919. let window = KMOCRSettingWindowController(windowNibName: "KMOCRSettingWindowController")
  2920. window.OCRAction = {[unowned self] controller, model in
  2921. self.convertOCRScanFile(window: window, document: self.listView.document, model: model)
  2922. }
  2923. self.km_beginSheet(windowC: window)
  2924. }
  2925. func showOCREditAlert() {
  2926. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { [unowned self] in
  2927. alertTipViewController.showInView(listView)
  2928. alertTipViewController.reloadOCRAlertUI()
  2929. alertTipViewController.reloadAlertUIFrame()
  2930. alertTipViewController.OCRApplyCallback = { [unowned self] in
  2931. self.showOCRWindow()
  2932. }
  2933. }
  2934. }
  2935. func closeOCREditAlert() {
  2936. guard let view = alertTipViewController.OCRComponentAlert else { return }
  2937. alertTipViewController.reloadOCRAlertUI()
  2938. alertTipViewController.reloadAlertUIFrame()
  2939. }
  2940. func showOCRToolAlert(_ string: String) {
  2941. let alertView = ComponentMessage()
  2942. alertView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString(string))
  2943. alertView.frame = CGRectMake((CGRectGetWidth(self.listView.frame) - alertView.properties.propertyInfo.viewWidth) / 2,
  2944. CGRectGetHeight(self.listView.frame) - alertView.properties.propertyInfo.viewHeight - 8,
  2945. alertView.properties.propertyInfo.viewWidth,
  2946. alertView.properties.propertyInfo.viewHeight)
  2947. alertView.reloadData()
  2948. self.listView.addSubview(alertView)
  2949. // 自动移除视图
  2950. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  2951. self.removeOCRToolAlert(alertView)
  2952. }
  2953. }
  2954. private func removeOCRToolAlert(_ alertView: NSView) {
  2955. // 淡出动画
  2956. NSAnimationContext.runAnimationGroup({ context in
  2957. context.duration = 0.3
  2958. alertView.animator().alphaValue = 0
  2959. }, completionHandler: {
  2960. alertView.removeFromSuperview()
  2961. })
  2962. }
  2963. //OCR
  2964. func convertOCRScanFile(window: KMOCRSettingWindowController, document: CPDFDocument, model: KMOCRModel) {
  2965. window.beginLoading()
  2966. //当前页面需要提前设置
  2967. if model.pageRangeType == .current {
  2968. model.pageRange = [self.listView.currentPageIndex]
  2969. }
  2970. KMOCRManager.manager.convertScanFile(document: document, model: model, progress: { progress in
  2971. }) { [weak self] document, text, error in
  2972. window.endLoading()
  2973. window.km_quick_endSheet()
  2974. if !model.saveAsPDF {
  2975. self?.listView.layoutDocumentView()
  2976. }
  2977. }
  2978. }
  2979. func convertOCR(document: CPDFDocument, model: KMOCRModel) {
  2980. // self.view.window?.windowController.beginLoading()
  2981. //当前页面需要提前设置
  2982. if model.pageRangeType == .current {
  2983. model.pageRange = [self.listView.currentPageIndex]
  2984. }
  2985. self.showProgressWindow(message: "正在转换中....")
  2986. KMOCRManager.manager.convertOCR(document: document, model: model, progress: { [weak self] progress in
  2987. self?.progressC?.message = "正在转换中...."
  2988. self?.progressC?.doubleValue = Double(progress * 100)
  2989. }) { [weak self] document, text, error in
  2990. // self?.view.window?.windowController.endLoading()
  2991. // window.km_quick_endSheet()
  2992. if !model.saveAsPDF {
  2993. self?.listView.layoutDocumentView()
  2994. }
  2995. self?.hiddenProgressWindow()
  2996. }
  2997. self.progressC?.closeBlock = {
  2998. print("手动取消中")
  2999. KMOCRManager.manager.cancelRecognition()
  3000. }
  3001. }
  3002. func convertOCRSaveAsTXT(text: String) {
  3003. NSPanel.savePanel(NSWindow.currentWindow()) { panel in
  3004. let url: URL = self.listView.document.documentURL
  3005. panel.nameFieldStringValue = ""+url.deletingPathExtension().lastPathComponent+"_OCR"
  3006. panel.allowedFileTypes = ["txt"]
  3007. } completion: { [unowned self] response, url in
  3008. if (response == .cancel) {
  3009. return
  3010. }
  3011. let saveAsPDFFilePath = url?.path ?? ""
  3012. let outputURL = URL(fileURLWithPath: saveAsPDFFilePath)
  3013. try? text.write(to: outputURL, atomically: true, encoding: .utf8)
  3014. }
  3015. }
  3016. func convertSelectionRectOCR(rect: NSRect) {
  3017. let rect = NSIntegralRect(rect)
  3018. let orgPage : CPDFPage = listView.currentSelectionPage() ?? CPDFPage()
  3019. if let page : CPDFPage = orgPage.copy() as? CPDFPage {
  3020. page.setBounds(rect, for: .cropBox)
  3021. let image = page.thumbnail(of: rect.size) ?? NSImage()
  3022. guard let model = self.rightSideController?.tool_OCRController?.model else { return }
  3023. model.pageRange = [Int(orgPage.pageIndex())]
  3024. KMOCRManager.manager.convertOCR(images: [image], model: model, progress: { progress in
  3025. }) { [weak self] document, text, error in
  3026. self?.rightSideController?.tool_OCRController?.model.text = text ?? ""
  3027. self?.rightSideController?.tool_OCRController?.reloadData()
  3028. //关闭窗口
  3029. self?.listView.selectionRect = NSZeroRect
  3030. self?.listView.selectionPageIndex = UInt(NSNotFound)
  3031. self?.closePopOperationWindow()
  3032. self?.listView.setNeedsDisplayForVisiblePages()
  3033. }
  3034. }
  3035. }
  3036. }
  3037. //MARK: Batch
  3038. extension KMMainViewController {
  3039. func showBatchWindow(type: KMBatchCollectionViewType, fileModels: [KMBatchProcessingTableViewModel]?) {
  3040. self.showBatchWindow(type: type, subType: 0, files: [], fileModels: fileModels)
  3041. }
  3042. func showBatchWindow(type: KMBatchCollectionViewType, files: [URL]?) {
  3043. self.showBatchWindow(type: type, subType: 0, files: files, fileModels: [])
  3044. }
  3045. func showBatchWindow(type: KMBatchCollectionViewType, subType: Int = 0, files: [URL]?, fileModels: [KMBatchProcessingTableViewModel]?) {
  3046. let batchWindowController = KMBatchWindowController.init(windowNibName: "KMBatchWindowController")
  3047. batchWindowController.window?.makeKeyAndOrderFront("")
  3048. if files?.count != 0 {
  3049. batchWindowController.inputData = files ?? []
  3050. }
  3051. if fileModels?.count != 0 {
  3052. batchWindowController.inputDataModel = fileModels ?? []
  3053. }
  3054. batchWindowController.type = type
  3055. batchWindowController.inputSubType = subType
  3056. }
  3057. }
  3058. //MARK: - 代理方法
  3059. //MARK: - NSSplitViewDelegate
  3060. extension KMMainViewController: NSSplitViewDelegate {
  3061. func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
  3062. if splitView == infoContendSplitView {
  3063. return subview.isEqual(to: infoSplitCenterView) == false
  3064. }
  3065. return false
  3066. }
  3067. func splitView(_ splitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAt dividerIndex: Int) -> Bool {
  3068. if splitView == infoContendSplitView {
  3069. if(subview.isEqual(to: infoSplitLeftView)) {
  3070. } else if(subview.isEqual(to: infoSplitRightView)) {
  3071. }
  3072. }
  3073. return false
  3074. }
  3075. func splitView(_ splitView: NSSplitView, shouldHideDividerAt dividerIndex: Int) -> Bool {
  3076. if splitView == infoContendSplitView {
  3077. return splitView == infoContendSplitView
  3078. } else if splitView == pdfSplitView {
  3079. return splitView == pdfSplitView
  3080. }
  3081. return false
  3082. }
  3083. func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  3084. if splitView == infoContendSplitView {
  3085. if dividerIndex == 0 {
  3086. if viewManager.showDisplayView {
  3087. return MIN_SIDE_PANE_WIDTH.doubleValue
  3088. }
  3089. return infoContendSplitView.bounds.width/2
  3090. } else if (dividerIndex == 1) {
  3091. return proposedMaximumPosition - MIN_SIDE_PANE_WIDTH.doubleValue
  3092. }
  3093. }
  3094. return proposedMaximumPosition
  3095. }
  3096. func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  3097. if(splitView == infoContendSplitView && dividerIndex == 0) {
  3098. return proposedMinimumPosition + MIN_SIDE_PANE_WIDTH.doubleValue
  3099. }
  3100. return proposedMinimumPosition
  3101. }
  3102. func splitViewDidResizeSubviews(_ notification: Notification) {
  3103. let splitView = notification.object as? NSSplitView
  3104. if(splitView == infoContendSplitView) {
  3105. leftSplitViewResizeFinish()
  3106. if(newMwcFlags.settingUpWindow == false && self.view.window?.frameAutosaveName != nil) {
  3107. let leftWidth = infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) ? 0.0 : infoSplitLeftView.frame.width
  3108. UserDefaults.standard.set(leftWidth, forKey: CPDFViewLeftSidePaneWidthKey)
  3109. UserDefaults.standard.synchronize()
  3110. }
  3111. if listView.isEditing() == false {
  3112. updateAnnotationsPopWinodwFrame()
  3113. } else {
  3114. updateContentEditPopWinodwFrame()
  3115. }
  3116. }
  3117. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(splitViewResizeFinish), object: nil)
  3118. self.perform(#selector(splitViewResizeFinish), with: nil, afterDelay: 0.15)
  3119. }
  3120. @objc func leftSplitViewResizeFinish() {
  3121. botaViewController?.changeLeftSideBounds()
  3122. }
  3123. @objc func splitViewResizeFinish() {
  3124. if infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) {
  3125. if viewManager.pdfSideBarType != .none {
  3126. viewManager.pdfSideBarType = .none
  3127. sideBarController?.reloadBOTAData()
  3128. }
  3129. }
  3130. }
  3131. }
  3132. //MARK: - KMPDFSideBarControllerDelegate 左侧Sidebar代理
  3133. extension KMMainViewController: KMPDFSideBarControllerDelegate {
  3134. func kmPDFSideBarControllerDidSidebarTypeUpdated(_ view: KMPDFSideBarController) {
  3135. if viewManager.pdfSideBarType == .none {
  3136. toggleCloseLeftSide()
  3137. } else {
  3138. toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
  3139. }
  3140. }
  3141. func kmPDFSideBarControllerDidGotoPage(_ view: KMPDFSideBarController, _ pageIndex: Int) {
  3142. listView.go(toPageIndex: pageIndex, animated: true)
  3143. }
  3144. }
  3145. //MARK: - KMPDFToolbarControllerDelegate 工具栏代理
  3146. extension KMMainViewController: KMPDFToolbarControllerDelegate {
  3147. //MARK: -ViewTools发生变化时调用
  3148. func kmPDFToolbarControllerDidViewToolsChanged(_ controller: KMPDFToolbarController) {
  3149. let viewToolsType = viewManager.viewToolsType
  3150. if viewToolsType == .Select {
  3151. listView.toolMode = .CNoteToolMode
  3152. } else if viewToolsType == .Scroll {
  3153. listView.toolMode = .CMoveToolMode
  3154. } else if viewToolsType == .Content_Selection {
  3155. listView.toolMode = .CSelectToolMode
  3156. } else if viewToolsType == .Magnify {
  3157. listView.toolMode = .CMagnifyToolMode
  3158. } else if viewToolsType == .AreaZoom {
  3159. listView.toolMode = .CSelectZoomToolMode
  3160. }
  3161. refreshToolbarViewHeightInfo()
  3162. }
  3163. //MARK: -一级工具栏状态发生变化时调用
  3164. func kmPDFToolbarControllerDidToolModeChanged(_ controller: KMPDFToolbarController) {
  3165. refreshToolbarViewHeightInfo()
  3166. toolbarViewModeChanged()
  3167. }
  3168. //MARK: -点击工具栏按钮
  3169. func kmPDFToolbarControllerDidToolbarItemClicked(_ controller: KMPDFToolbarController, _ itemIdentifier: String) {
  3170. print("toolbar点击", itemIdentifier)
  3171. if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_PageEdit_Identifier).contains(itemIdentifier) {
  3172. //MARK: -页面编辑
  3173. if itemIdentifier == KMPDFToolbar_PageEdit_InsertFile_Identifier {
  3174. pageEditViewController?.insertFromPDFAction()
  3175. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertBlank_Identifier {
  3176. pageEditViewController?.insertFromBlankAction()
  3177. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertClip_Identifier {
  3178. pageEditViewController?.insertFromClipboardAction()
  3179. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertScanner_Identifier {
  3180. pageEditViewController?.insertFromScannerAction()
  3181. } else if itemIdentifier == KMPDFToolbar_PageEdit_Extract_Identifier {
  3182. pageEditViewController?.extractPDFAction()
  3183. } else if itemIdentifier == KMPDFToolbar_PageEdit_Replace_Identifier {
  3184. pageEditViewController?.replacePDFAction()
  3185. } else if itemIdentifier == KMPDFToolbar_PageEdit_Split_Identifier {
  3186. pageEditViewController?.splitPDFAction()
  3187. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reverse_Identifier {
  3188. pageEditViewController?.reversePDFAction()
  3189. } else if itemIdentifier == KMPDFToolbar_PageEdit_LeftRotate_Identifier {
  3190. pageEditViewController?.rotatePageLeftAction()
  3191. } else if itemIdentifier == KMPDFToolbar_PageEdit_RightRotate_Identifier{
  3192. pageEditViewController?.rotatePageRightAction()
  3193. } else if itemIdentifier == KMPDFToolbar_PageEdit_Delete_Identifier {
  3194. pageEditViewController?.deletePageAction()
  3195. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reduce_Identifier {
  3196. pageEditViewController?.zoomOutPageAction()
  3197. if(pageEditViewController?.canZoomInPageSize() == false) {
  3198. toolbarManager.page_Increase_Property.isDisabled = true
  3199. } else {
  3200. toolbarManager.page_Increase_Property.isDisabled = false
  3201. }
  3202. if(pageEditViewController?.canZoomOutPageSize() == false) {
  3203. toolbarManager.page_Reduce_Property.isDisabled = true
  3204. } else {
  3205. toolbarManager.page_Reduce_Property.isDisabled = false
  3206. }
  3207. controller.refreshSecondToolbarItemsState()
  3208. } else if itemIdentifier == KMPDFToolbar_PageEdit_Increase_Identifier {
  3209. pageEditViewController?.zoomInPageAction()
  3210. if(pageEditViewController?.canZoomInPageSize() == false) {
  3211. toolbarManager.page_Increase_Property.isDisabled = true
  3212. } else {
  3213. toolbarManager.page_Increase_Property.isDisabled = false
  3214. }
  3215. if(pageEditViewController?.canZoomOutPageSize() == false) {
  3216. toolbarManager.page_Reduce_Property.isDisabled = true
  3217. } else {
  3218. toolbarManager.page_Reduce_Property.isDisabled = false
  3219. }
  3220. controller.refreshSecondToolbarItemsState()
  3221. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_oddPage_Identifier {
  3222. pageEditViewController?.thumbnailChoosePageStyle = .odd
  3223. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3224. toolbarManager.page_pageInfo_Property.creatable = false
  3225. controller.refreshSecondToolbarItemsState()
  3226. }
  3227. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_EvenPage_Identifier {
  3228. pageEditViewController?.thumbnailChoosePageStyle = .even
  3229. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3230. toolbarManager.page_pageInfo_Property.creatable = false
  3231. controller.refreshSecondToolbarItemsState()
  3232. }
  3233. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_PortraitPage_Identifier {
  3234. pageEditViewController?.thumbnailChoosePageStyle = .horizontal
  3235. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3236. toolbarManager.page_pageInfo_Property.creatable = false
  3237. controller.refreshSecondToolbarItemsState()
  3238. }
  3239. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_LandscapePage_Identifier {
  3240. pageEditViewController?.thumbnailChoosePageStyle = .vertical
  3241. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3242. toolbarManager.page_pageInfo_Property.creatable = false
  3243. controller.refreshSecondToolbarItemsState()
  3244. }
  3245. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_AllPage_Identifier {
  3246. pageEditViewController?.thumbnailChoosePageStyle = .allPage
  3247. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3248. toolbarManager.page_pageInfo_Property.creatable = false
  3249. controller.refreshSecondToolbarItemsState()
  3250. }
  3251. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_CustomPage_Identifier {
  3252. pageEditViewController?.thumbnailChoosePageStyle = .custom
  3253. toolbarManager.page_pageInfo_Property.text = nil
  3254. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  3255. toolbarManager.page_pageInfo_Property.creatable = true
  3256. }
  3257. controller.refreshSecondToolbarItemsState()
  3258. }
  3259. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Markup_Identifier).contains(itemIdentifier) {
  3260. //MARK: -Markup
  3261. if itemIdentifier == KMPDFToolbar_eye_Identifier {
  3262. self.showOrHideNotes()
  3263. }
  3264. if viewManager.subToolMode == .None {
  3265. viewManager.showRightSide = false
  3266. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3267. viewManager.showRightSide = true
  3268. }
  3269. self.refreshToolbarRightViewInfo()
  3270. if let currentSelect = listView.currentSelection {
  3271. if(currentSelect.selectionType() == .text) {
  3272. let annotationType: CAnnotationType = KMPDFViewManager.getValidPDFAnnotationType(viewManager.subToolMode)
  3273. if annotationType != .unkown {
  3274. listView.addAnnotation(with: annotationType, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  3275. }
  3276. }
  3277. }
  3278. toolbarViewModeChanged()
  3279. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Edit_Identifier).contains(itemIdentifier) {
  3280. //MARK: -编辑
  3281. if itemIdentifier == KMPDFToolbar_edit_addWatermark_Identifier {
  3282. showWatermarkController()
  3283. } else if itemIdentifier == KMPDFToolbar_edit_removeWatermark_Identifier {
  3284. removePDFWatermark()
  3285. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddWatermark_Identifier {
  3286. batchAddWatermark()
  3287. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveWatermark_Identifier {
  3288. batchRemoveWatermark()
  3289. } else if itemIdentifier == KMPDFToolbar_edit_addBG_Identifier {
  3290. showBackgroundController()
  3291. } else if itemIdentifier == KMPDFToolbar_edit_removeBG_Identifier {
  3292. removePDFBackground()
  3293. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBG_Identifier {
  3294. batchAddBackground()
  3295. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBG_Identifier {
  3296. batchRemoveBackground()
  3297. } else if itemIdentifier == KMPDFToolbar_edit_addHF_Identifier {
  3298. showHeaderFooterController()
  3299. } else if itemIdentifier == KMPDFToolbar_edit_removeHF_Identifier {
  3300. removeHeaderFooter()
  3301. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddHF_Identifier {
  3302. batchAddHeaderFooter()
  3303. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveHF_Identifier {
  3304. batchRemoveHeaderFooter()
  3305. } else if itemIdentifier == KMPDFToolbar_edit_addBates_Identifier {
  3306. showBatesController()
  3307. } else if itemIdentifier == KMPDFToolbar_edit_removeBates_Identifier {
  3308. removePDFBates()
  3309. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBates_Identifier {
  3310. batchAddBates()
  3311. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBates_Identifier {
  3312. batchRemoveBates()
  3313. } else if itemIdentifier == KMPDFToolbar_edit_crop_Identifier {
  3314. showCropController()
  3315. }
  3316. if viewManager.subToolMode == .None {
  3317. viewManager.showRightSide = false
  3318. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3319. viewManager.showRightSide = true
  3320. }
  3321. self.refreshToolbarRightViewInfo()
  3322. toolbarViewModeChanged()
  3323. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Form_Identifier).contains(itemIdentifier) {
  3324. //MARK: -Form表单
  3325. if itemIdentifier == KMPDFToolbar_form_HighlightFields_Identifier {
  3326. let value = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
  3327. CPDFAnnotation.updateHighlightFormFiled(listView, highlightFormFiled: !value)
  3328. self.toolbarManager.refreshDefaultConfigItem()
  3329. } else if itemIdentifier == KMPDFToolbar_form_ShowName_Identifier {
  3330. listView.showFormFieldName = !listView.showFormFieldName
  3331. if listView.showFormFieldName {
  3332. toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
  3333. } else {
  3334. toolbarManager.form_ShowName_Property.righticon = nil
  3335. }
  3336. listView.setNeedsDisplayForVisiblePages()
  3337. } else if itemIdentifier == KMPDFToolbar_form_ClearForm_Identifier {
  3338. listView.resetFormAnnotation()
  3339. } else if itemIdentifier == KMPDFToolbar_form_Align_Left_Identifier {
  3340. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
  3341. listView.setNeedsDisplayForVisiblePages()
  3342. } else if itemIdentifier == KMPDFToolbar_form_Align_Hori_Identifier {
  3343. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
  3344. listView.setNeedsDisplayForVisiblePages()
  3345. } else if itemIdentifier == KMPDFToolbar_form_Align_Right_Identifier {
  3346. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
  3347. listView.setNeedsDisplayForVisiblePages()
  3348. } else if itemIdentifier == KMPDFToolbar_form_Align_Top_Identifier {
  3349. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
  3350. listView.setNeedsDisplayForVisiblePages()
  3351. } else if itemIdentifier == KMPDFToolbar_form_Align_Vert_Identifier {
  3352. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
  3353. listView.setNeedsDisplayForVisiblePages()
  3354. } else if itemIdentifier == KMPDFToolbar_form_Align_Bottom_Identifier {
  3355. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
  3356. listView.setNeedsDisplayForVisiblePages()
  3357. } else if itemIdentifier == KMPDFToolbar_form_Distribute_Vert_Identifier {
  3358. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
  3359. listView.setNeedsDisplayForVisiblePages()
  3360. } else if itemIdentifier == KMPDFToolbar_form_Distribute_Hori_Identifier {
  3361. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
  3362. listView.setNeedsDisplayForVisiblePages()
  3363. }
  3364. if itemIdentifier == KMPDFToolbar_form_HighlightFields_Identifier ||
  3365. itemIdentifier == KMPDFToolbar_form_ShowName_Identifier ||
  3366. itemIdentifier == KMPDFToolbar_form_ClearForm_Identifier ||
  3367. itemIdentifier == KMPDFToolbar_form_Align_Left_Identifier ||
  3368. itemIdentifier == KMPDFToolbar_form_Align_Hori_Identifier ||
  3369. itemIdentifier == KMPDFToolbar_form_Align_Right_Identifier ||
  3370. itemIdentifier == KMPDFToolbar_form_Align_Top_Identifier ||
  3371. itemIdentifier == KMPDFToolbar_form_Align_Vert_Identifier ||
  3372. itemIdentifier == KMPDFToolbar_form_Align_Bottom_Identifier ||
  3373. itemIdentifier == KMPDFToolbar_form_Distribute_Vert_Identifier ||
  3374. itemIdentifier == KMPDFToolbar_form_Distribute_Hori_Identifier {
  3375. } else {
  3376. toolbarViewModeChanged()
  3377. }
  3378. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Fill_Identifier).contains(itemIdentifier) {
  3379. //MARK: -填充
  3380. if viewManager.subToolMode == .None {
  3381. viewManager.showRightSide = false
  3382. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3383. viewManager.showRightSide = true
  3384. }
  3385. self.refreshToolbarRightViewInfo()
  3386. toolbarViewModeChanged()
  3387. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Convert_Identifier).contains(itemIdentifier) {
  3388. //MARK: -转档
  3389. if itemIdentifier == KMPDFToolbar_convert_word_Identifier {
  3390. self.showConvertWindow(.word)
  3391. } else if itemIdentifier == KMPDFToolbar_convert_ppt_Identifier {
  3392. self.showConvertWindow(.ppt)
  3393. } else if itemIdentifier == KMPDFToolbar_convert_RTF_Identifier {
  3394. self.showConvertWindow(.rtf)
  3395. } else if itemIdentifier == KMPDFToolbar_convert_Text_Identifier {
  3396. self.showConvertWindow(.text)
  3397. } else if itemIdentifier == KMPDFToolbar_convert_CSV_Identifier {
  3398. self.showConvertWindow(.csv)
  3399. } else if itemIdentifier == KMPDFToolbar_convert_excel_Identifier {
  3400. self.showConvertWindow(.excel)
  3401. } else if itemIdentifier == KMPDFToolbar_convert_HTML_Identifier {
  3402. self.showConvertWindow(.html)
  3403. } else if itemIdentifier == KMPDFToolbar_convert_Json_Identifier {
  3404. self.showConvertWindow(.json)
  3405. } else if itemIdentifier == KMPDFToolbar_convert_image_Identifier {
  3406. self.showConvertWindow(.jpeg)
  3407. } else if itemIdentifier == KMPDFToolbar_convert_imageToPDF_Identifier {
  3408. NSApplication.ShowImageToPDFWindow()
  3409. }
  3410. self.refreshToolbarRightViewInfo()
  3411. toolbarViewModeChanged()
  3412. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Protect_Identifier).contains(itemIdentifier) {
  3413. //MARK: -Protect
  3414. if itemIdentifier == KMPDFToolbar_protect_redact_Identifier {
  3415. toolbarViewModeChanged()
  3416. if viewManager.showRightSide == true {
  3417. viewManager.showRightSide = false
  3418. pdfToolbarController?.reloadRightToolsView()
  3419. toggleCloseRightSide()
  3420. }
  3421. } else if itemIdentifier == KMPDFToolbar_protect_redact_Property_Identifier {
  3422. self.showRedactProperty(readactAnnotation: nil)
  3423. toolbarViewModeChanged()
  3424. } else if itemIdentifier == KMPDFToolbar_protect_redact_Apply_Identifier {
  3425. toolbarViewModeChanged()
  3426. } else if itemIdentifier == KMPDFToolbar_protect_redact_Exit_Identifier {
  3427. toolbarViewModeChanged()
  3428. } else if itemIdentifier == KMPDFToolbar_protect_security_Identifier {
  3429. self.showSecureWindow()
  3430. } else if itemIdentifier == KMPDFToolbar_protect_removeSecurity_Identifier {
  3431. self.showRemoveSecureWindow()
  3432. } else if itemIdentifier == KMPDFToolbar_protect_digitalSign_Identifier {
  3433. self.toolbarViewModeChanged()
  3434. }
  3435. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Tools_Identifier).contains(itemIdentifier) {
  3436. //MARK: -工具
  3437. if itemIdentifier == KMPDFToolbar_tools_compress_Identifier {
  3438. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3439. model.password = listView.document.password ?? ""
  3440. self.showCompressController(model: model)
  3441. } else if itemIdentifier == KMPDFToolbar_tools_batch_compress_Identifier {
  3442. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3443. model.password = listView.document.password ?? ""
  3444. self.showBatchWindow(type: .compress, files: [], fileModels: [model])
  3445. } else if itemIdentifier == KMPDFToolbar_tools_OCR_Identifier {
  3446. viewManager.showRightSide = !viewManager.showRightSide
  3447. self.refreshToolbarRightViewInfo()
  3448. } else if itemIdentifier == KMPDFToolbar_tools_merge_Identifier {
  3449. self.showMergeWindow(self.listView.document.password)
  3450. } else if itemIdentifier == KMPDFToolbar_tools_TTS_Identifier {
  3451. self.showTTSWindow()
  3452. } else if itemIdentifier == KMPDFToolbar_tools_extractImage_Identifier {
  3453. self.extractImageAction(num: 2)
  3454. } else if itemIdentifier == KMPDFToolbar_tools_AITools_Identifier {
  3455. self.viewManager.pdfSideBarType = .aiTools
  3456. self.sideBarController?.reloadData()
  3457. if let sideVC = self.sideBarController {
  3458. self.kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  3459. }
  3460. } else if itemIdentifier == KMPDFToolbar_tools_compare_side_Identifier {
  3461. self.beginCompareAction(1)
  3462. } else if itemIdentifier == KMPDFToolbar_tools_compare_Overlay_Identifier {
  3463. self.beginCompareAction(2)
  3464. } else if itemIdentifier == KMPDFToolbar_tools_batch_Identifier {
  3465. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3466. model.password = listView.document.password ?? ""
  3467. self.showBatchWindow(type: .convertPDF, files: [], fileModels: [model])
  3468. }
  3469. if viewManager.subToolMode == .None {
  3470. viewManager.showRightSide = false
  3471. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3472. viewManager.showRightSide = true
  3473. }
  3474. self.refreshToolbarRightViewInfo()
  3475. toolbarViewModeChanged()
  3476. } else if itemIdentifier == KMPDFToolbar_ViewDisplay_Identifier {
  3477. //MARK: -Display
  3478. updatePDFDisplaySettingView()
  3479. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Right_Identifiers).contains(itemIdentifier) {
  3480. if(itemIdentifier == KMPDFToolbar_undo_Identifier) {
  3481. //MARK: -Undo
  3482. listView.undoManager?.undo()
  3483. } else if(itemIdentifier == KMPDFToolbar_redo_Identifier) {
  3484. //MARK: -Redo
  3485. listView.undoManager?.redo()
  3486. } else if(itemIdentifier == KMPDFToolbar_fileInfo_Identifier) {
  3487. self.showFileInfo()
  3488. } else if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier ||
  3489. itemIdentifier == KMPDFToolbar_share_Flattened_Identifier ||
  3490. itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  3491. //MARK: -Share
  3492. if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier) {
  3493. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  3494. shareDocument(sender: view)
  3495. }
  3496. } else if(itemIdentifier == KMPDFToolbar_share_Flattened_Identifier) {
  3497. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  3498. shareFlatten(sender: view)
  3499. }
  3500. } else if(itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  3501. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  3502. shareOriginalPDF(sender: view)
  3503. }
  3504. }
  3505. } else if itemIdentifier == KMPDFToolbar_save_Identifier {
  3506. myDocument?.save(nil)
  3507. } else if itemIdentifier == KMPDFToolbar_print_Identifier {
  3508. self.showPrintWindow()
  3509. } else if itemIdentifier == KMPDFToolbar_tts_Identifier {
  3510. self.showTTSWindow()
  3511. } else if itemIdentifier == KMPDFToolbar_ppt_Identifier {
  3512. self.togglePresentation(nil)
  3513. } else if itemIdentifier == KMPDFToolbar_batch_Identifier {
  3514. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3515. model.password = listView.document.password ?? ""
  3516. self.showBatchWindow(type: .convertPDF, files: [], fileModels: [model])
  3517. }
  3518. } else if itemIdentifier == KMPDFToolbar_PageEdit_Identifier {
  3519. //MARK: -页面编辑
  3520. if viewManager.isPageEditMode == true {
  3521. enterPageEditMode()
  3522. } else {
  3523. exitPageEditMode()
  3524. }
  3525. } else if itemIdentifier == KMPDFToolbar_rightView_Identifier {
  3526. //MARK: -属性栏
  3527. self.refreshToolbarRightViewInfo()
  3528. } else {
  3529. print("click else")
  3530. }
  3531. refreshToolbarViewHeightInfo()
  3532. refreshRightSide()
  3533. }
  3534. func kmPDFToolbarControllerDidSelectTextDidBeginEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  3535. }
  3536. func kmPDFToolbarControllerDidSelectTextDidChange(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  3537. }
  3538. func kmPDFToolbarControllerDidSelectTextDidEndEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  3539. if view.properties == toolbarManager.page_pageInfo_Property {
  3540. if viewManager.isPageEditMode == true {
  3541. let fileAttribute = KMNFileAttribute()
  3542. fileAttribute.password = listView.document?.password ?? ""
  3543. fileAttribute.pdfDocument = listView.document
  3544. fileAttribute.filePath = listView.document?.documentURL.path ?? ""
  3545. fileAttribute.bAllPage = false
  3546. fileAttribute.pagesType = .PagesString
  3547. fileAttribute.pagesString = view.properties.text ?? ""
  3548. let fetchSelectPages = fileAttribute.fetchSelectPages()
  3549. if (fetchSelectPages.isEmpty) {
  3550. let alert = NSAlert()
  3551. alert.alertStyle = .critical
  3552. alert.messageText = String(format: "%@ %@", fileAttribute.filePath.lastPathComponent, KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  3553. alert.runModal()
  3554. toolbarManager.page_pageInfo_Property.text = ""
  3555. controller.refreshSecondToolbarItemsState()
  3556. } else {
  3557. var tIndexPaths: Set<IndexPath> = []
  3558. for i in 0 ..< fetchSelectPages.count {
  3559. tIndexPaths.insert(IndexPath(item: (fetchSelectPages[i] - 1), section: 0))
  3560. }
  3561. pageEditViewController?.selectionIndexPaths = tIndexPaths
  3562. }
  3563. }
  3564. }
  3565. }
  3566. func kmPDFToolbarControllerDidExitPageEditMode(_ controller: KMPDFToolbarController) {
  3567. exitPageEditMode()
  3568. }
  3569. }
  3570. //MARK: - KMRightSideControllerDelegate右边属性栏代理
  3571. extension KMMainViewController: KMRightSideControllerDelegate {
  3572. func kmRightSideControllerRotateLeft(_ annotations: [CPDFStampAnnotation], withPDFView pdfView: CPDFListView?) {
  3573. CPDFStampAnnotation.rotateLeft(annotations, withPDFView: pdfView)
  3574. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).kmRightSideControllerRotateRight(annotations, withPDFView: pdfView)
  3575. }
  3576. func kmRightSideControllerRotateRight(_ annotations: [CPDFStampAnnotation], withPDFView pdfView: CPDFListView?) {
  3577. CPDFStampAnnotation.rotateRight(annotations, withPDFView: pdfView)
  3578. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).kmRightSideControllerRotateLeft(annotations, withPDFView: pdfView)
  3579. }
  3580. func kmRightSideControllerDidContendVCUpdated(_ controller: KMRightSideController) {
  3581. //MARK: -Crop
  3582. if (controller.contentViewController is KMCropPropertyController) {
  3583. if let cropVC = rightSideController?.edit_cropController {
  3584. cropVC.pdfView = controller.pdfView
  3585. if cropVC.delegate == nil {
  3586. cropVC.delegate = cropController
  3587. }
  3588. cropVC.reloadData()
  3589. }
  3590. }
  3591. reloadPopUIWindow()
  3592. }
  3593. func kmRightSideControllerOCRShowTypeChange(_ controller: KMRightSideController, _ type: KMOCRShowType) {
  3594. if type == .area {
  3595. self.listView.toolMode = .COCRToolMode
  3596. self.showOCRToolAlert(KMLocalizedString("Please select the area that needs OCR and click the “OCR” button to start"))
  3597. } else {
  3598. self.listView.toolMode = .CTextToolMode
  3599. }
  3600. }
  3601. func kmRightSideControllerOCRDoneAction(_ controller: KMRightSideController, _ model: KMOCRModel) {
  3602. if model.showType == .area {
  3603. self.convertOCRSaveAsTXT(text: model.text)
  3604. } else {
  3605. if model.saveAsPDF {
  3606. if model.saveType == .PDF {
  3607. } else {
  3608. }
  3609. } else {
  3610. }
  3611. self.convertOCR(document: self.listView.document, model: model)
  3612. }
  3613. }
  3614. //测量设置界面
  3615. func kmRightSideControllerShowMeasureSetting(_ controller: KMRightSideController) {
  3616. showMeasureSettingWindow()
  3617. }
  3618. }
  3619. //MARK: - KMNDisplayViewControllerDelegate代理
  3620. extension KMMainViewController: KMNDisplayViewControllerDelegate {
  3621. //Display Mode
  3622. func displayViewControllerDidDisplayModeChanged(_ controller: KMNDisplayViewController) {
  3623. listView.layoutDocumentView()
  3624. }
  3625. //阅读模式
  3626. func displayViewControllerDidReadModeUpdated(_ controller: KMNDisplayViewController) {
  3627. if viewManager.isPDFReadMode {
  3628. openPDFReadMode()
  3629. } else {
  3630. exitPDFReadMode()
  3631. }
  3632. }
  3633. //PPT
  3634. func displayViewControllerDidGotoSlideShow(_ controller: KMNDisplayViewController) {
  3635. togglePresentation(nil)
  3636. }
  3637. //SplitView
  3638. func displayViewControllerDidSplitModeChanged(_ controller: KMNDisplayViewController) {
  3639. reloadPDFSplitInfo()
  3640. }
  3641. func displayViewControllerDidSplitFileChanged(_ controller: KMNDisplayViewController) {
  3642. splitPDFController?.reloadData()
  3643. }
  3644. func displayViewControllerDidToolbarStateChanged(_ controller: KMNDisplayViewController) {
  3645. splitPDFController?.refreshToolbarState()
  3646. reloadPDFPageNumberToolbar()
  3647. }
  3648. }
  3649. //MARK: - PPT
  3650. extension KMMainViewController: KMInteractionProviderProtocol {
  3651. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  3652. if(interactionMode == .presentation) {
  3653. if listView.presentationDrawView == nil {
  3654. listView.createPresentationDraw()
  3655. }
  3656. presentationTopViewController = KMPresentationTopViewController.init(nibName: "KMPresentationTopViewController", bundle: nil)
  3657. presentationTopViewController?.pdfView = listView
  3658. presentationTopViewController?.delegate = self
  3659. presentationTopViewController?.isSelectionPre = true
  3660. listView.isPresentationMode = true
  3661. presentationTopViewController?.view.frame = CGRect(x: 0, y: (fullScreenWindow.contentView?.bounds.height ?? 0) - 42, width: fullScreenWindow.contentView?.bounds.width ?? 0, height: 42)
  3662. if((presentationTopViewController) != nil) {
  3663. fullScreenWindow.contentView?.addSubview(presentationTopViewController!.view)
  3664. }
  3665. } else {
  3666. listView.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  3667. }
  3668. fullScreenWindow.contentView?.addSubview(listView)
  3669. if(interactionMode == .presentation) {
  3670. let frame = fullScreenWindow.frame
  3671. listView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-42)
  3672. listView.autoresizingMask = [.width, .maxYMargin]
  3673. }
  3674. return view
  3675. }
  3676. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  3677. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3678. return
  3679. }
  3680. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  3681. if interactionMode == .presentation {
  3682. let backgroundColor = NSColor.black
  3683. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  3684. let wasInteractionMode = self.interactionMode
  3685. if wasInteractionMode == .normal {
  3686. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  3687. }
  3688. if wasInteractionMode == .legacyFullScreen {
  3689. self.enterPresentationMode()
  3690. self.listView.frame = (self.view.window?.contentView?.bounds)!
  3691. self.view.window?.contentView?.addSubview(listView)
  3692. // self.view.window?.backgroundColor = backgroundColor
  3693. self.view.window?.level = level
  3694. self.listView.layoutDocumentView()
  3695. self.listView.requiresDisplay()
  3696. }
  3697. } else {
  3698. KMPrint("2")
  3699. }
  3700. }
  3701. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  3702. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3703. return
  3704. }
  3705. if self.interactionMode == .presentation {
  3706. self.listView.layoutDocumentView()
  3707. self.listView.requiresDisplay()
  3708. }
  3709. }
  3710. @objc func willShowFullScreenNotification(_ sender: Notification) {
  3711. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3712. return
  3713. }
  3714. if self.interactionMode == .presentation {
  3715. let view = self.view.window?.firstResponder as? NSView
  3716. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  3717. self.view.window?.makeFirstResponder(nil)
  3718. }
  3719. }
  3720. }
  3721. @objc func didShowFullScreenNotification(_ sender: Notification) {
  3722. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3723. return
  3724. }
  3725. if self.interactionMode == .presentation {
  3726. self.enterPresentationMode()
  3727. }
  3728. }
  3729. }
  3730. // MARK: -KMPresentationTopViewControllerDelegate (幻灯片)
  3731. extension KMMainViewController: KMPresentationTopViewControllerDelegate {
  3732. func presentationTopViewExit(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  3733. self.exitFullScreen()
  3734. }
  3735. func presentationTopViewClear(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  3736. listView.presentationDrawView?.clear()
  3737. }
  3738. func presentationTopViewUndo(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  3739. let presentationDrawView = listView.presentationDrawView
  3740. if presentationDrawView?.canUndo() == true {
  3741. presentationDrawView?.undo()
  3742. }
  3743. }
  3744. func presentationTopViewType(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton, isSeletion: Bool) {
  3745. listView.isPresentationMode = isSeletion
  3746. if listView.isEnterPresentationDrawMode() == true {
  3747. listView.exitPresentationDrawMode()
  3748. }
  3749. }
  3750. func presentationTopViewDrawColor(_ presentationTopViewController: KMPresentationTopViewController, withView: NSView,color:NSColor?) {
  3751. if color == nil{
  3752. listView.exitPresentationDrawMode()
  3753. } else {
  3754. if listView.isEnterPresentationDrawMode() == false {
  3755. listView.enterPresentationDrawMode()
  3756. }
  3757. listView.changePresentationDrawModelColor(color)
  3758. }
  3759. }
  3760. }
  3761. //MARK: - KMSplitPDFViewControllerDelegate SplitPDFView分屏视图
  3762. extension KMMainViewController: KMSplitPDFViewControllerDelegate {
  3763. func splitPDFViewControllerDidUpdateFilePath(_ controller: KMSplitPDFViewController) {
  3764. displaySettingController?.reloadData()
  3765. }
  3766. func splitPDFViewControllerDidUpdatePDFScale(_ controller: KMSplitPDFViewController) {
  3767. if let scaleFactor = controller.pdfView?.scaleFactor {
  3768. listView.scaleFactor = scaleFactor
  3769. }
  3770. }
  3771. func splitPDFViewControllerDidUpdatePDFPageIndex(_ controller: KMSplitPDFViewController) {
  3772. if let pageIndex = controller.pdfView?.currentPageIndex {
  3773. listView.go(toPageIndex: pageIndex, animated: false)
  3774. }
  3775. }
  3776. }
  3777. //MARK: - Edit编辑相关代理
  3778. extension KMMainViewController: KMEditToolbarViewDelegate {
  3779. func kmEditToolbarViewDidUpdateMode(_ view: KMEditToolbarView) {
  3780. if view.editType == .watermark {
  3781. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3782. watermarkViewController?.reloadData()
  3783. watermarkViewController?.loadData()
  3784. } else if view.editType == .background {
  3785. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3786. backgroundViewController?.resetUI()
  3787. backgroundViewController?.reloadData()
  3788. } else if view.editType == .header_Footer {
  3789. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3790. headerFooterViewController?.resetUI()
  3791. headerFooterViewController?.reloadData()
  3792. } else if view.editType == .bates {
  3793. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3794. batesViewController?.resetUI()
  3795. batesViewController?.reloadData()
  3796. }
  3797. }
  3798. func kmEditToolbarViewDidChooseBatch(_ view: KMEditToolbarView) {
  3799. if view.editType == .watermark {
  3800. self.showBatchWindow(type: .watermark, files: nil)
  3801. } else if view.editType == .background {
  3802. self.showBatchWindow(type: .background, files: nil)
  3803. } else if view.editType == .header_Footer {
  3804. self.showBatchWindow(type: .headerAndFooter, files: nil)
  3805. } else if view.editType == .bates {
  3806. self.showBatchWindow(type: .batesNumber, files: nil)
  3807. }
  3808. }
  3809. func kmEditToolbarViewDidChooseApply(_ view: KMEditToolbarView) {
  3810. let pageInfo = view.pageRangeSelectView.getSelectedPageIndex(listView.document)
  3811. let pageIndex = pageInfo.0
  3812. let isCurrentPage = pageInfo.1
  3813. if pageIndex.isEmpty {
  3814. let alert = NSAlert()
  3815. alert.alertStyle = .critical
  3816. alert.messageText = KMLocalizedString("Invalid page range or the page number is out of range. Please try again.")
  3817. alert.runModal()
  3818. return
  3819. }
  3820. var pageString = view.pageRangeSelectView.getSelectedPageString(listView.document, pageIndex)
  3821. if isCurrentPage {
  3822. pageString = String(format: "%ld", listView.currentPageIndex)
  3823. }
  3824. if view.editType == .watermark {
  3825. if let model = watermarkViewController?.currentWatermarkData {
  3826. let watermark = KMWatermarkModel.returnWaterMarkWith(model, listView.document)
  3827. watermark.pageString = pageString
  3828. listView.document.addWatermark(watermark)
  3829. listView.layoutDocumentView()
  3830. }
  3831. exitEditToolbarView()
  3832. } else if view.editType == .background {
  3833. if let model = backgroundViewController?.backgroundModel {
  3834. if let background = listView.document.background() {
  3835. KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  3836. background.pageString = pageString
  3837. background.update()
  3838. listView.document?.refreshPageData()
  3839. listView.layoutDocumentView()
  3840. }
  3841. }
  3842. exitEditToolbarView()
  3843. } else if view.editType == .header_Footer {
  3844. if let model = headerFooterViewController?.headerFooterModel {
  3845. if let headerFooter = listView.document.headerFooter() {
  3846. KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(listView.document.pageCount))
  3847. headerFooter.pageString = pageString
  3848. headerFooter.update()
  3849. listView.document?.refreshPageData()
  3850. listView.layoutDocumentView()
  3851. }
  3852. }
  3853. exitEditToolbarView()
  3854. } else if view.editType == .bates {
  3855. if let model = batesViewController?.batesModel {
  3856. if let bates = listView.document.bates() {
  3857. KMBatesManager.defaultManager.updateCPDFBates(bates, withModel: model, Int(listView.document.pageCount))
  3858. bates.pageString = pageString
  3859. bates.update()
  3860. listView.document?.refreshPageData()
  3861. listView.layoutDocumentView()
  3862. }
  3863. }
  3864. exitEditToolbarView()
  3865. }
  3866. }
  3867. func kmEditToolbarViewDidChooseExit(_ view: KMEditToolbarView) {
  3868. if view.applyEnable {
  3869. let alert = NSAlert()
  3870. if view.editType == .watermark {
  3871. alert.messageText = NSLocalizedString("There are unapplied Watermark settings, do you want to apply them?", comment: "")
  3872. } else if view.editType == .background {
  3873. alert.messageText = NSLocalizedString("There are unapplied Background settings, do you want to apply them?", comment: "")
  3874. } else if view.editType == .header_Footer {
  3875. alert.messageText = NSLocalizedString("There are unapplied Header & Footer settings, do you want to apply them?", comment: "")
  3876. } else if view.editType == .bates {
  3877. alert.messageText = NSLocalizedString("There are unapplied Bates settings, do you want to apply them?", comment: "")
  3878. }
  3879. alert.informativeText = NSLocalizedString("If not, the changes will be lost.", comment: "")
  3880. alert.addButton(withTitle: NSLocalizedString("Apply", comment: ""))
  3881. alert.addButton(withTitle: NSLocalizedString("Don't Apply", comment: ""))
  3882. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3883. let result = alert.runModal()
  3884. if (result == .alertFirstButtonReturn) {
  3885. self.kmEditToolbarViewDidChooseApply(view)
  3886. } else if (result == .alertSecondButtonReturn) {
  3887. //"Don't Apply"
  3888. exitEditToolbarView()
  3889. } else if (result == .alertThirdButtonReturn) {
  3890. //Cancel
  3891. }
  3892. } else {
  3893. exitEditToolbarView()
  3894. }
  3895. }
  3896. }
  3897. //MARK: - KMCropControllerDelegate 裁剪相关代理
  3898. extension KMMainViewController: KMCropControllerDelegate {
  3899. func kmCropControllerDidCrop(_ controller: KMCropController, _ cropRect: CGRect, _ view: KMPageRangeSelectView) {
  3900. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  3901. let indexs = rangeSelectResult.0
  3902. let isCurrentPage = rangeSelectResult.1
  3903. var uIndexs: [UInt] = []
  3904. for index in indexs {
  3905. if index > 0 {
  3906. uIndexs.append(UInt(index-1))
  3907. }
  3908. }
  3909. if isCurrentPage {
  3910. uIndexs = [UInt(listView.currentPageIndex)]
  3911. }
  3912. cropPages(atIndexs: uIndexs, to: [cropRect])
  3913. removeCropController()
  3914. viewManager.subToolMode = .None
  3915. if let toolbarVC = self.pdfToolbarController {
  3916. toolbarVC.refreshSecondToolbarItemsState()
  3917. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  3918. }
  3919. }
  3920. func kmCropControllerDidCropSeparate(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  3921. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  3922. let indexs = rangeSelectResult.0
  3923. let isCurrentPage = rangeSelectResult.1
  3924. var rectArray: Array<NSRect> = []
  3925. var uIndexs: [UInt] = []
  3926. for index in indexs {
  3927. if index > 0 {
  3928. uIndexs.append(UInt(index-1))
  3929. let page = self.listView.document.page(at: UInt(index-1))
  3930. let rect = KMCropTools.getPageForegroundBox(page!)
  3931. rectArray.append(rect)
  3932. }
  3933. }
  3934. if isCurrentPage {
  3935. uIndexs = [UInt(listView.currentPageIndex)]
  3936. }
  3937. cropPages(atIndexs: uIndexs, to: rectArray)
  3938. removeCropController()
  3939. viewManager.subToolMode = .None
  3940. if let toolbarVC = self.pdfToolbarController {
  3941. toolbarVC.refreshSecondToolbarItemsState()
  3942. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  3943. }
  3944. }
  3945. func kmCropControllerDidCropAuto(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  3946. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  3947. let indexs = rangeSelectResult.0
  3948. let isCurrentPage = rangeSelectResult.1
  3949. var uIndexs: [UInt] = []
  3950. for index in indexs {
  3951. if index > 0 {
  3952. uIndexs.append(UInt(index-1))
  3953. }
  3954. }
  3955. if isCurrentPage {
  3956. uIndexs = [UInt(listView.currentPageIndex)]
  3957. }
  3958. auto_cropPagesWhiteMargin(uIndexs)
  3959. removeCropController()
  3960. viewManager.subToolMode = .None
  3961. if let toolbarVC = self.pdfToolbarController {
  3962. toolbarVC.refreshSecondToolbarItemsState()
  3963. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  3964. }
  3965. }
  3966. func kmCropControllerDidChangedSelectionOrMagnification(_ controller: KMCropController) {
  3967. if let cropVC = rightSideController?.edit_cropController {
  3968. if cropVC.pdfView != controller.pdfView {
  3969. cropVC.pdfView = controller.pdfView
  3970. }
  3971. cropVC.cropSeparateOn = false
  3972. cropVC.cropAutoOn = false
  3973. cropVC.reloadData()
  3974. }
  3975. }
  3976. }
  3977. //MARK: - KMWatermarkControllerDelegate 水印相关代理
  3978. extension KMMainViewController: KMWatermarkControllerDelegate {
  3979. func kmWatermarkControllerDidUpdateMode(_ view: KMWatermarkController) {
  3980. editToolbarView?.editSubType = view.editSubType
  3981. editToolbarView?.reloadData()
  3982. }
  3983. func kmWatermarkControllerDidWatermarkUpdated(_ view: KMWatermarkController) {
  3984. var applyEnable = true
  3985. if let model = view.currentWatermarkData {
  3986. if model.watermarkType == .text {
  3987. if model.text == nil || model.text?.count == 0 {
  3988. applyEnable = false
  3989. }
  3990. } else if model.watermarkType == .image {
  3991. if model.imagePath == nil {
  3992. applyEnable = false
  3993. }
  3994. }
  3995. } else {
  3996. applyEnable = false
  3997. }
  3998. editToolbarView?.applyEnable = applyEnable
  3999. editToolbarView?.reloadData()
  4000. }
  4001. }
  4002. //MARK: - KMBackgroundControllerDelegate 背景代理
  4003. extension KMMainViewController: KMBackgroundControllerDelegate {
  4004. func kmBackgroundControllerDidUpdateMode(_ view: KMBackgroundController) {
  4005. editToolbarView?.editSubType = view.editSubType
  4006. }
  4007. func kmBackgroundControllerDidBGDataUpdated(_ view: KMBackgroundController) {
  4008. var applyEnable = true
  4009. if let model = view.backgroundModel {
  4010. if model.type == .image {
  4011. if model.imagePath == nil {
  4012. applyEnable = false
  4013. }
  4014. }
  4015. } else {
  4016. applyEnable = false
  4017. }
  4018. editToolbarView?.applyEnable = applyEnable
  4019. editToolbarView?.reloadData()
  4020. }
  4021. }
  4022. //MARK: - KMHeaderFooterControllerDelegate 页眉页脚代理
  4023. extension KMMainViewController: KMHeaderFooterControllerDelegate {
  4024. func kmHeaderFooterControllerDidUpdateModeType(_ view: KMHeaderFooterController) {
  4025. editToolbarView?.editSubType = view.editSubType
  4026. }
  4027. func kmHeaderFooterControllerDidModelDataUpdated(_ view: KMHeaderFooterController) {
  4028. var applyEnable = true
  4029. if let model = view.headerFooterModel {
  4030. if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
  4031. model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
  4032. applyEnable = false
  4033. }
  4034. } else {
  4035. applyEnable = false
  4036. }
  4037. editToolbarView?.applyEnable = applyEnable
  4038. editToolbarView?.reloadData()
  4039. }
  4040. }
  4041. //MARK: - KMBatesControllerDelegate Bates贝茨码代理
  4042. extension KMMainViewController: KMBatesControllerDelegate {
  4043. func kmBatesControllerDidUpdateMode(_ view: KMBatesController) {
  4044. editToolbarView?.editSubType = view.editSubType
  4045. editToolbarView?.reloadData()
  4046. }
  4047. func kmBatesControllerDidModelDataUpdated(_ view: KMBatesController) {
  4048. var applyEnable = true
  4049. if let model = view.batesModel {
  4050. if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
  4051. model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
  4052. applyEnable = false
  4053. }
  4054. } else {
  4055. applyEnable = false
  4056. }
  4057. editToolbarView?.applyEnable = applyEnable
  4058. editToolbarView?.reloadData()
  4059. }
  4060. }
  4061. //MARK: - CPDFViewDelegate PDFView代理
  4062. extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
  4063. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  4064. sideBarController?.reloadPageTurnerData()
  4065. documentLoadComplete()
  4066. }
  4067. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  4068. sideBarController?.reloadPageTurnerData()
  4069. botaViewController?.currentPageDidChangedAction(listView: listView)
  4070. //分屏视图
  4071. reloadPDFPageNumberToolbar()
  4072. if viewManager.splitSyncScroll {
  4073. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  4074. splitPDFController?.outPDFFirst = true
  4075. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  4076. var index = pdfView.currentPageIndex
  4077. if index > document.pageCount {
  4078. index = Int(splitPDFView.document.pageCount - 1)
  4079. }
  4080. splitPDFView.go(toPageIndex: index, animated: false)
  4081. }
  4082. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4083. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4084. } else if splitPDFController?.outPDFFirst == true {
  4085. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  4086. var index = pdfView.currentPageIndex
  4087. if index > document.pageCount {
  4088. index = Int(splitPDFView.document.pageCount - 1)
  4089. }
  4090. splitPDFView.go(toPageIndex: index, animated: false)
  4091. }
  4092. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4093. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4094. }
  4095. }
  4096. //水印
  4097. updateEditModeDocumentWhenPageChanged()
  4098. //
  4099. }
  4100. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  4101. pdfToolbarController?.reloadSelectZoomView()
  4102. reloadPDFPageNumberToolbar()
  4103. reloadPopUIWindow()
  4104. //分屏视图
  4105. if viewManager.splitSyncScroll {
  4106. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  4107. splitPDFController?.outPDFFirst = true
  4108. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4109. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4110. } else if splitPDFController?.outPDFFirst == true {
  4111. if let splitPDFView = splitPDFController?.pdfView {
  4112. splitPDFView.scaleFactor = pdfView.scaleFactor
  4113. }
  4114. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4115. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4116. }
  4117. }
  4118. }
  4119. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  4120. if let urlString = url, urlString == Store_Link {
  4121. //跳转订阅比较表
  4122. return
  4123. }
  4124. if url.hasPrefix("smb://") {
  4125. NSWorkspace.shared.openFile(url)
  4126. } else {
  4127. KMTools.openURL(urlString: url)
  4128. }
  4129. }
  4130. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  4131. KMPrint("pdfViewPerformURL")
  4132. if content != nil {
  4133. NSWorkspace.shared.open(URL(string: content)!)
  4134. } else {
  4135. let alert = NSAlert()
  4136. alert.alertStyle = .critical
  4137. alert.informativeText = NSLocalizedString("The hyperlink is invalid.", comment: "")
  4138. alert.messageText = ""
  4139. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  4140. alert.runModal()
  4141. return
  4142. }
  4143. }
  4144. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  4145. KMPrint("pdfViewPerformPrint")
  4146. self.showPrintWindow()
  4147. }
  4148. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  4149. KMPrint("pdfViewPerformGo")
  4150. }
  4151. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  4152. KMPrint("pdfViewOpenPDF")
  4153. }
  4154. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  4155. KMPrint("pdfViewPerformReset")
  4156. pdfView.document?.resetForm()
  4157. }
  4158. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  4159. KMPrint("pdfViewEditingBlockDidChanged")
  4160. }
  4161. func pdfViewAsBookBookmark() -> NSImage! {
  4162. return NSImage(named: "KMImageNameBookmarkIcon")!
  4163. }
  4164. //MARK: -编辑模块
  4165. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  4166. // 文本区块 选中文本已经变化
  4167. reloadPopUIWindow()
  4168. }
  4169. func pdfViewPDFSelectionAttributeDidChanged(_ pdfView: CPDFView!) {
  4170. reloadPopUIWindow()
  4171. }
  4172. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  4173. //编辑模块变化
  4174. rightSideController?.reloadDataWithPDFView(pdfView: (pdfView as! CPDFListView))
  4175. if pdfView is CPDFListView {
  4176. (pdfView as! CPDFListView).isEditImage = false
  4177. }
  4178. if let areas = pdfView.editingAreas(), areas.count > 0 {
  4179. if viewManager.showRightSide == false && SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  4180. viewManager.showRightSide = true
  4181. self.refreshToolbarRightViewInfo()
  4182. }
  4183. } else {
  4184. if viewManager.subToolMode == .None {
  4185. viewManager.showRightSide = false
  4186. self.refreshToolbarRightViewInfo()
  4187. }
  4188. }
  4189. reloadPopUIWindow()
  4190. }
  4191. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  4192. if editArea != nil && (editArea is CPDFEditImageArea){
  4193. self.listView.cropAreas = editArea as? CPDFEditImageArea
  4194. }
  4195. reloadPopUIWindow()
  4196. }
  4197. //编辑PDF 创建图片区域回调
  4198. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  4199. if (pdfView as! CPDFListView).isEditImage {
  4200. return
  4201. }
  4202. if listView.editingAreas().count > 0 {
  4203. pdfView.updateEditing([])
  4204. return
  4205. }
  4206. let panel = NSOpenPanel()
  4207. panel.allowsMultipleSelection = false
  4208. panel.allowedFileTypes = ["png","jpg"]
  4209. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  4210. if response == .OK {
  4211. var filePath = panel.url?.path
  4212. let image = NSImage.init(contentsOf: panel.url!)
  4213. //图片自适应范围
  4214. if image != nil {
  4215. var imageRect = rect
  4216. let imageSize = image!.size
  4217. var previewSize = rect.size
  4218. var isChangeSize = false
  4219. if previewSize.width == 0 && previewSize.height == 0 {
  4220. previewSize = CGSize(width: 500, height: 500)
  4221. isChangeSize = true
  4222. }
  4223. var scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  4224. if scale < 1 { // 大于 500
  4225. } else {
  4226. let wh = max(imageSize.width, imageSize.height)
  4227. if wh >= 72 {
  4228. scale = min(scale, 1)
  4229. } else {
  4230. scale = min(72 / imageSize.width, 72 / imageSize.height)
  4231. }
  4232. }
  4233. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  4234. if isChangeSize {
  4235. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  4236. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  4237. } else {
  4238. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  4239. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  4240. }
  4241. imageRect.size = newSize
  4242. let limitWidth = 1920.0
  4243. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  4244. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  4245. targetSize: CGSize(width: limitWidth, height: limitWidth),
  4246. maxSizeInBytes: 1024 * 1024 * 5,
  4247. targetCompression: 1.0)
  4248. }
  4249. //自适应page
  4250. let pageRect = self.listView.currentPage().bounds ?? .zero
  4251. if imageRect.width > pageRect.width ||
  4252. imageRect.height > pageRect.height {
  4253. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  4254. imageRect = CGRect(x: imageRect.origin.x,
  4255. y: imageRect.origin.y,
  4256. width: imageRect.width * pageScale,
  4257. height: imageRect.height * pageScale)
  4258. }
  4259. if imageRect.origin.x < 0 {
  4260. imageRect.origin.x = 5
  4261. }
  4262. if imageRect.origin.y < 0 {
  4263. imageRect.origin.y = 5
  4264. }
  4265. if imageRect.origin.x + imageRect.width > pageRect.width ||
  4266. imageRect.origin.y + imageRect.height > pageRect.height {
  4267. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  4268. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  4269. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  4270. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  4271. }
  4272. DispatchQueue.main.async {
  4273. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  4274. }
  4275. }
  4276. }
  4277. }
  4278. }
  4279. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  4280. let areas = self.listView.km_EditingAreas()
  4281. if let area = areas.last {
  4282. if let data = area as? CPDFEditTextArea {
  4283. if let str = data.editTextAreaString(), str.isEmpty {
  4284. self.listView.remove(with: [area])
  4285. } else {
  4286. self.listView.updateEditing([])
  4287. return
  4288. }
  4289. }
  4290. }
  4291. var newRect = rect
  4292. if rect.size.equalTo(.zero) {
  4293. newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  4294. } else {
  4295. newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  4296. }
  4297. let fontSize = CPDFEditTextArea.defaultFontSize()
  4298. let fontColor = CPDFEditTextArea.defaultColor()
  4299. let fontAlign = CPDFEditTextArea.defaultFontAlignment()
  4300. NSColorPanel.shared.color = fontColor
  4301. let attri = CEditAttributes()
  4302. attri.cFont = CPDFFont(familyName: CPDFEditTextArea.defaultFontName(), fontStyle: CPDFEditTextArea.defaultFontStyle())
  4303. attri.fontColor = fontColor
  4304. attri.alignment = fontAlign
  4305. attri.fontSize = fontSize
  4306. attri.isBold = CPDFEditTextArea.defaultIsBold()
  4307. attri.isItalic = CPDFEditTextArea.defaultIsItality()
  4308. self.listView.createStringBounds(newRect, with: attri, page: page)
  4309. }
  4310. func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  4311. rightSideController?.reloadEditingAreas()
  4312. toggleClosePopUIWindow()
  4313. }
  4314. func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  4315. rightSideController?.reloadEditingAreas()
  4316. toggleClosePopUIWindow()
  4317. }
  4318. func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  4319. rightSideController?.reloadEditingAreas()
  4320. reloadPopUIWindow()
  4321. }
  4322. func pdfViewEditingSelectCharDidChanged(_ pdfView: CPDFView!) {
  4323. rightSideController?.reloadEditingAreas()
  4324. reloadPopUIWindow()
  4325. }
  4326. func pdfViewEditingExitCropMode(_ pdfView: CPDFView!, forEditing editingArea: CPDFEditImageArea!) {
  4327. rightSideController?.reloadEditingAreas()
  4328. toggleClosePopUIWindow()
  4329. }
  4330. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  4331. let areas = self.listView.km_editingImageAreas()
  4332. if areas.count == 1 {
  4333. if let data = areas.first as? CPDFEditImageArea {
  4334. let updating = self.listView.editAreaBoundUpdating
  4335. if updating {
  4336. self.listView.editAreaBoundUpdating = false
  4337. }
  4338. }
  4339. }
  4340. }
  4341. func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  4342. if(editArea.isImageArea()) {
  4343. listView.cropAction()
  4344. }
  4345. }
  4346. //MARK: - 键盘事件
  4347. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  4348. let command = theEvent.modifierFlags.contains(.command)
  4349. let control = theEvent.modifierFlags.contains(.control)
  4350. let shift = theEvent.modifierFlags.contains(.shift)
  4351. KMPrint(theEvent.keyCode)
  4352. if self.listView.isEditing() == true {
  4353. if control && theEvent.keyCode == 11 { // ctr + b
  4354. self.listView.setEditingTextarea_Bold()
  4355. rightSideController?.reloadEditingAreas()
  4356. return false
  4357. } else if control && theEvent.keyCode == 34 { // ctr +i
  4358. self.listView.setEditingTextarea_Italic()
  4359. rightSideController?.reloadEditingAreas()
  4360. return false
  4361. } else if theEvent.keyCode == 36 { // enter
  4362. if self.listView.isCropMode {
  4363. self.listView.cropComfirmAction()
  4364. rightSideController?.reloadEditingAreas()
  4365. return false
  4366. }
  4367. } else if theEvent.keyCode == 53 { // Cancel
  4368. if self.listView.isCropMode {
  4369. self.listView.cropCancelAction()
  4370. rightSideController?.reloadEditingAreas()
  4371. return false
  4372. }
  4373. }
  4374. }
  4375. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  4376. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  4377. return false
  4378. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  4379. return false
  4380. } else if (theEvent.keyCode == 123) { // 向左
  4381. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  4382. return false
  4383. } else {
  4384. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  4385. self.listView.goToPreviousPage(nil)
  4386. return false
  4387. }
  4388. }
  4389. } else if (theEvent.keyCode == 126) { // 向上
  4390. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  4391. return false
  4392. } else {
  4393. if (self.listView.isContinousScroll()) {
  4394. return true
  4395. }
  4396. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  4397. self.listView.goToPreviousPage(nil)
  4398. return false
  4399. }
  4400. }
  4401. } else if (theEvent.keyCode == 124) { // 向右
  4402. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  4403. return false
  4404. } else {
  4405. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  4406. self.listView.goToNextPage(nil)
  4407. return false
  4408. }
  4409. }
  4410. } else if (theEvent.keyCode == 125) { // 向下
  4411. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  4412. return false
  4413. } else {
  4414. if (self.listView.isContinousScroll()) {
  4415. return true
  4416. }
  4417. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  4418. self.listView.goToNextPage(nil)
  4419. return false
  4420. }
  4421. }
  4422. } else if (theEvent.keyCode == 36) {
  4423. if self.listView.shouAddEditAreaType() == .image || self.listView.shouAddEditAreaType() == .text {
  4424. if self.listView.isEditImage {
  4425. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  4426. }
  4427. }
  4428. } else if shift && theEvent.keyCode == 18 {
  4429. //Shift + 1
  4430. updatePDFViewToolsType(.Select)
  4431. } else if shift && theEvent.keyCode == 19 {
  4432. //Shift + 2
  4433. updatePDFViewToolsType(.Scroll)
  4434. } else if shift && theEvent.keyCode == 20 {
  4435. //Shift + 3
  4436. updatePDFViewToolsType(.Content_Selection)
  4437. } else if shift && theEvent.keyCode == 21 {
  4438. //Shift + 4
  4439. updatePDFViewToolsType(.Magnify)
  4440. } else if shift && theEvent.keyCode == 23 {
  4441. //Shift + 5
  4442. updatePDFViewToolsType(.AreaZoom)
  4443. } else if theEvent.keyCode == 53 {
  4444. //ESC
  4445. self.exitFullScreen()
  4446. if viewManager.isPDFReadMode {
  4447. self.exitPDFReadMode()
  4448. }
  4449. self.leftSideViewCancelSelect()
  4450. }
  4451. return true
  4452. }
  4453. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  4454. guard let action = menuItem.action else {
  4455. isTakesEffect.pointee = false
  4456. return false
  4457. }
  4458. isTakesEffect.pointee = false
  4459. return false
  4460. }
  4461. //MARK: - CPDFListViewDelegate
  4462. func pdfListViewChangedToolMode(_ pdfListView: CPDFListView!, for toolMode: CToolMode) {
  4463. reloadPopUIWindow()
  4464. }
  4465. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  4466. if(annotationType == .unkown) {
  4467. toggleCloseRightSide()
  4468. if viewManager.subToolMode != .None {
  4469. viewManager.subToolMode = .None
  4470. pdfToolbarController?.cancelSelectedSecondToolbarItems(viewManager.toolMode)
  4471. pdfToolbarController?.refreshSecondToolbarItemsState()
  4472. }
  4473. cancelMeasureType()
  4474. } else if annotationType == .measureLine ||
  4475. annotationType == .measurePolyLine ||
  4476. annotationType == .measurePolyGon ||
  4477. annotationType == .measureSquare {
  4478. refreshMeasureInfo()
  4479. } else {
  4480. cancelMeasureType()
  4481. }
  4482. }
  4483. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  4484. self.view.window?.makeFirstResponder(self.listView)
  4485. reloadPopUIWindow()
  4486. if isRightMenu {
  4487. } else if annotations.count > 0 {
  4488. if self.viewManager.isPDFReadMode {
  4489. toggleCloseRightSide()
  4490. } else {
  4491. let isMultiAnnotations = pdfListView.isMultiAnnotation(annotations)
  4492. if isMultiAnnotations == true {
  4493. viewManager.showRightSide = false
  4494. } else {
  4495. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  4496. viewManager.showRightSide = true
  4497. }
  4498. }
  4499. refreshToolbarRightViewInfo()
  4500. }
  4501. } else if (annotations.count == 0){
  4502. if pdfListView.annotationType == .unkown {
  4503. viewManager.showRightSide = false
  4504. } else {
  4505. if self.viewManager.isPDFReadMode {
  4506. viewManager.showRightSide = false
  4507. } else {
  4508. viewManager.showRightSide = true
  4509. }
  4510. }
  4511. refreshToolbarRightViewInfo()
  4512. }
  4513. self.refreshMeasureInfo()
  4514. //
  4515. pdfToolbarController?.pdfViewActiveAnnotationsChanged()
  4516. }
  4517. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
  4518. var pagePoint = CGPoint.zero
  4519. let point = theEvent.locationInWindow
  4520. let isShowPopUI:Bool = !SettingsManager.sharedInstance.showQuickActionBar
  4521. if let page = pdfListView.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  4522. if view.window?.interactionMode == .presentation {
  4523. let menuStruct = clickPresentationMenu(point: pagePoint)
  4524. groupListMenuGroup?.groupDelegate = self
  4525. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4526. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4527. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: pdfListView)
  4528. } else {
  4529. var menuStringArr: [String] = []
  4530. let activeAnnotations = pdfListView.activeAnnotations as? [CPDFAnnotation]
  4531. if activeAnnotations?.count ?? 0 > 1 {
  4532. var isSameAnnotation = true
  4533. let firstAnnotation = activeAnnotations?.first
  4534. for i in 1..<(activeAnnotations?.count ?? 1) {
  4535. if firstAnnotation?.type != activeAnnotations?[i].type {
  4536. isSameAnnotation = false
  4537. break
  4538. }
  4539. }
  4540. if isSameAnnotation {
  4541. if firstAnnotation?.isKind(of: CPDFMarkupAnnotation.self) == true {
  4542. menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
  4543. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4544. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4545. } else {
  4546. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4547. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4548. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4549. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4550. }
  4551. if(isShowPopUI){
  4552. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4553. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4554. }
  4555. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  4556. if firstAnnotation?.isKind(of: CPDFLinkAnnotation.self) == true || firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
  4557. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4558. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4559. }
  4560. } else {
  4561. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4562. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4563. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4564. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4565. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  4566. if firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
  4567. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4568. }
  4569. }
  4570. } else if activeAnnotations?.count == 1 {
  4571. if pdfListView.activeAnnotation.isKind(of: CPDFMarkupAnnotation.self) {
  4572. menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
  4573. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4574. if(isShowPopUI){
  4575. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4576. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4577. }
  4578. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4579. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  4580. } else if pdfListView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self) {
  4581. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4582. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4583. menuStringArr.append(PDFViewMenuIdentifier_Redact_Apply)
  4584. menuStringArr.append(PDFViewMenuIdentifier_Redact_Multipage)
  4585. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4586. menuStringArr.append(PDFViewMenuIdentifier_Normal_RedactProperties)
  4587. menuStringArr.append(PDFViewMenuIdentifier_Redact_Default)
  4588. } else if listView.activeAnnotation.isKind(of: CPDFLinkAnnotation.self) {
  4589. let link = listView.activeAnnotation as? CPDFLinkAnnotation
  4590. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4591. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4592. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4593. if(isShowPopUI){
  4594. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4595. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4596. }
  4597. } else if pdfListView.activeAnnotation.isKind(of: CPDFWidgetAnnotation.self) {
  4598. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4599. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4600. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4601. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4602. if(isShowPopUI){
  4603. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4604. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4605. }
  4606. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  4607. } else {
  4608. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4609. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4610. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4611. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4612. if pdfListView.activeAnnotation.isKind(of: CPDFTextAnnotation.self) ||
  4613. pdfListView.activeAnnotation.isKind(of: CPDFFreeTextAnnotation.self) {
  4614. } else {
  4615. menuStringArr.append(PDFViewMenuIdentifier_Normal_Content)
  4616. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4617. }
  4618. if(isShowPopUI){
  4619. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4620. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4621. }
  4622. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  4623. }
  4624. } else {
  4625. let currentSelection = pdfListView.currentSelection
  4626. if currentSelection != nil {
  4627. if currentSelection?.selectionType() == .text {
  4628. menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
  4629. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4630. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4631. if pdfListView.canPaste() {
  4632. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  4633. }
  4634. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4635. menuStringArr.append(PDFViewMenuIdentifier_Normal_Hight)
  4636. menuStringArr.append(PDFViewMenuIdentifier_Normal_Underline)
  4637. menuStringArr.append(PDFViewMenuIdentifier_Normal_StrikeOut)
  4638. menuStringArr.append(PDFViewMenuIdentifier_Normal_Squiggly)
  4639. menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
  4640. menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
  4641. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4642. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddOutLine)
  4643. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  4644. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4645. menuStringArr.append(PDFViewMenuIdentifier_Normal_TTS)
  4646. menuStringArr.append(PDFViewMenuIdentifier_Normal_SearchText)
  4647. } else if currentSelection?.selectionType() == .image {
  4648. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4649. if pdfListView.canPaste() {
  4650. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  4651. }
  4652. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4653. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  4654. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4655. menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
  4656. menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
  4657. }
  4658. } else {
  4659. if pdfListView.toolMode == .CFormToolMode {
  4660. if pdfListView.canPaste() {
  4661. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  4662. }
  4663. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4664. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllForm)
  4665. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4666. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  4667. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowFormName)
  4668. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  4669. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4670. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  4671. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4672. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  4673. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4674. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4675. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4676. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4677. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4678. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  4679. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4680. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  4681. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4682. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  4683. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  4684. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  4685. } else if pdfListView.toolMode == .CRedactToolMode {
  4686. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllText)
  4687. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4688. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  4689. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4690. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  4691. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4692. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4693. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4694. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4695. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4696. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  4697. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4698. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  4699. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4700. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  4701. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  4702. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  4703. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4704. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  4705. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  4706. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  4707. } else {
  4708. if(listView.viewSplitMode != .disable) {
  4709. menuStringArr.append(PDFViewMenuIdentifier_Split_ViewMode)
  4710. menuStringArr.append(PDFViewMenuIdentifier_Split_Sync)
  4711. menuStringArr.append(PDFViewMenuIdentifier_Split_ShowBar)
  4712. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4713. } else {
  4714. menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
  4715. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4716. if pdfListView == listView {
  4717. if pdfListView.canPaste() {
  4718. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  4719. }
  4720. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllText)
  4721. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllAnnotation)
  4722. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4723. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowAnnotation)
  4724. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4725. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  4726. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4727. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  4728. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4729. }
  4730. }
  4731. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4732. if(listView.viewSplitMode != .disable) {
  4733. } else {
  4734. menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
  4735. }
  4736. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4737. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4738. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4739. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  4740. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4741. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  4742. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4743. menuStringArr.append(PDFViewMenuIdentifier_Normal_AutoScroll)
  4744. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4745. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  4746. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  4747. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  4748. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4749. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  4750. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  4751. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  4752. }
  4753. }
  4754. }
  4755. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
  4756. groupListMenuGroup?.groupDelegate = self
  4757. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4758. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4759. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: nil)
  4760. }
  4761. } else {
  4762. var menuStringArr: [String] = []
  4763. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4764. menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
  4765. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4766. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4767. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4768. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  4769. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  4770. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  4771. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
  4772. groupListMenuGroup?.groupDelegate = self
  4773. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4774. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4775. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: pdfListView)
  4776. }
  4777. reloadPopUIWindow()
  4778. }
  4779. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  4780. var windowPoint = listView.convert(point, from: page)
  4781. let view: NSView? = nil
  4782. windowPoint = listView.convert(windowPoint, to: view)
  4783. if self.view.window?.interactionMode == .presentation {
  4784. let menuStruct = clickPresentationMenu(point: point)
  4785. groupListMenuGroup?.groupDelegate = self
  4786. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4787. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4788. groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: listView)
  4789. } else {
  4790. let isShowPopUI:Bool = !SettingsManager.sharedInstance.showQuickActionBar
  4791. var menuStringArr: [String] = []
  4792. let editingAreas = listView.km_EditingAreas()
  4793. let firstEditingArea = editingAreas.first
  4794. if editingAreas.count > 1 {
  4795. var isSameEditingArea = true
  4796. if(firstEditingArea?.isTextArea() == true) {
  4797. for i in 1..<(editingAreas.count) {
  4798. if !editingAreas[i].isTextArea() {
  4799. isSameEditingArea = false
  4800. break
  4801. }
  4802. }
  4803. } else if (firstEditingArea?.isImageArea() == true) {
  4804. for i in 1..<(editingAreas.count) {
  4805. if !editingAreas[i].isImageArea() {
  4806. isSameEditingArea = false
  4807. break
  4808. }
  4809. }
  4810. }
  4811. if(isSameEditingArea) {
  4812. if (firstEditingArea?.isTextArea() == true) {
  4813. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4814. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4815. if listView.isSupportPastMatchStyle() {
  4816. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  4817. }
  4818. if listView.isSupportPast() {
  4819. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4820. }
  4821. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4822. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4823. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4824. menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
  4825. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
  4826. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
  4827. if(isShowPopUI){
  4828. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4829. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4830. }
  4831. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4832. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4833. } else if (firstEditingArea?.isImageArea() == true) {
  4834. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4835. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4836. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4837. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4838. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
  4839. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
  4840. menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
  4841. menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
  4842. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4843. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  4844. if(isShowPopUI){
  4845. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4846. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4847. }
  4848. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4849. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4850. }
  4851. } else {
  4852. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4853. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4854. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4855. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4856. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4857. }
  4858. } else if editingAreas.count == 1 {
  4859. if firstEditingArea?.isTextArea() == true {
  4860. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  4861. if listView.isSupportPast() {
  4862. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4863. }
  4864. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4865. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4866. } else {
  4867. let editState = listView.editStatus()
  4868. if (editState == .editSelectText) {// 选择文本
  4869. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4870. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4871. if listView.isSupportPast() {
  4872. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4873. }
  4874. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4875. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4876. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4877. } else {
  4878. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4879. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4880. if listView.isSupportPastMatchStyle() {
  4881. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  4882. }
  4883. if listView.isSupportPast() {
  4884. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4885. }
  4886. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4887. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4888. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4889. }
  4890. menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
  4891. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
  4892. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
  4893. if(isShowPopUI){
  4894. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4895. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4896. }
  4897. }
  4898. } else if firstEditingArea?.isImageArea() == true {
  4899. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4900. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4901. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4902. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4903. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
  4904. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
  4905. menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
  4906. menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
  4907. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4908. menuStringArr.append(PDFViewMenuIdentifier_Edit_Crop)
  4909. menuStringArr.append(PDFViewMenuIdentifier_Edit_Replace)
  4910. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  4911. if(isShowPopUI){
  4912. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4913. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4914. }
  4915. }
  4916. } else {
  4917. if(listView.isSupportPastMatchStyle()) {
  4918. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  4919. }
  4920. if(listView.isSupportPast()) {
  4921. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4922. }
  4923. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4924. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4925. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddText)
  4926. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddImage)
  4927. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddLink)
  4928. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4929. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  4930. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4931. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  4932. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4933. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4934. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4935. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4936. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4937. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  4938. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4939. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  4940. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4941. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  4942. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  4943. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  4944. }
  4945. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: nil, listView: listView)
  4946. groupListMenuGroup?.groupDelegate = self
  4947. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4948. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4949. groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: listView)
  4950. }
  4951. return []
  4952. }
  4953. func pdfListViewMobileAnnotationBegan(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  4954. toggleClosePopUIWindow()
  4955. }
  4956. func pdfListViewMobileAnnotationMove(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  4957. toggleClosePopUIWindow()
  4958. }
  4959. func pdfListViewMobileAnnotationEnd(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  4960. reloadPopUIWindow()
  4961. }
  4962. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  4963. var pageIndexes = IndexSet()
  4964. pageIndexes.insert(Int(pdfPage.pageIndex()))
  4965. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  4966. botaViewController?.reloadData()
  4967. alertTipViewController.reloadFormAlertUI()
  4968. alertTipViewController.reloadAlertUIFrame()
  4969. }
  4970. func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  4971. var pageIndexes = IndexSet()
  4972. pageIndexes.insert(Int(pdfPage.pageIndex()))
  4973. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  4974. botaViewController?.reloadData()
  4975. alertTipViewController.reloadFormAlertUI()
  4976. alertTipViewController.reloadAlertUIFrame()
  4977. }
  4978. func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  4979. if anotation.isKind(of: CPDFSignatureWidgetAnnotation.self) {
  4980. if let signatureWidgetAnnotation = anotation as? CPDFSignatureWidgetAnnotation {
  4981. let signature = signatureWidgetAnnotation.signature()
  4982. if ((signature) != nil) {
  4983. popUpSignatureWidgetState(signature!, listView)
  4984. } else {
  4985. let widget = CPDFSignatureWidgetAnnotation.init(PDFListViewNoteWith: listView.document)
  4986. widget.bounds = NSMakeRect(-1000, -1000, 545, 178);
  4987. anotation.page.addAnnotation(widget)
  4988. let configWindowVC = DSignatureConfigWindowController.init(windowNibName: "DSignatureConfigWindowController")
  4989. configWindowVC.viewType = .fileList;
  4990. configWindowVC.appearanceWidget = widget;
  4991. configWindowVC.isCreatDS = false
  4992. configWindowVC.complentionHandle = {[weak self] isSign, dic, config, isLock in
  4993. widget.page.removeAnnotation(widget)
  4994. if isSign {
  4995. if (dic.object(forKey: SAVEFILEPATH_KEY) != nil) {
  4996. let p12Path = dic.object(forKey: SAVEFILEPATH_KEY) as! String
  4997. let password = dic.object(forKey: PASSWORD_KEY)
  4998. if p12Path.count > 0 {
  4999. self?.writeSignatureToWidget(signatureWidgetAnnotation, p12Path, password as! String, config, isLock)
  5000. }
  5001. }
  5002. } else {
  5003. if signatureWidgetAnnotation.isSignSignatureAdd() == true {
  5004. self?.listView.remove(anotation)
  5005. }
  5006. }
  5007. }
  5008. configWindowVC.actionBlock = {[weak self] controller, type in
  5009. if (type == .cancel) {
  5010. NSApplication.shared.stopModal()
  5011. controller.window?.orderOut(nil)
  5012. controller.window?.close()
  5013. widget.page.removeAnnotation(widget)
  5014. if signatureWidgetAnnotation.isSignSignatureAdd() == true {
  5015. self?.listView.remove(anotation)
  5016. } else {
  5017. self?.listView.setNeedsDisplayAnnotationViewFor(anotation.page)
  5018. }
  5019. } else if (type == .confirm) {
  5020. NSApplication.shared.stopModal()
  5021. controller.window?.orderOut(nil)
  5022. controller.window?.close()
  5023. }
  5024. }
  5025. configWindowVC.window?.center()
  5026. NSApplication.shared.runModal(for: configWindowVC.window!)
  5027. }
  5028. }
  5029. } else if anotation.isKind(of: CPDFRedactAnnotation.self) {
  5030. if let redactAnnotation = anotation as? CPDFRedactAnnotation {
  5031. let properties = KMRedactPropertiesWindowController()
  5032. properties.readactAnnotation = redactAnnotation
  5033. properties.own_beginSheetModal(for: self.view.window) { result in
  5034. }
  5035. properties.callback = { [weak self] annotation in
  5036. if let page = annotation?.page {
  5037. self?.listView.setNeedsDisplayAnnotationViewFor(page)
  5038. }
  5039. }
  5040. }
  5041. }
  5042. }
  5043. func pdfListViewSplitModeShowBar() -> Bool {
  5044. return viewManager.splitShowBottomBar
  5045. }
  5046. func pdfListViewEndEditMode(_ pdfListView: CPDFListView!) {
  5047. let document = listView.document
  5048. if(document != nil) {
  5049. for i in 0..<document!.pageCount {
  5050. let thumbnail = KMNThumbnail.init(document: document!, currentPageIndex: Int(i))
  5051. thumbnail.removeCacheImage()
  5052. }
  5053. }
  5054. botaViewController?.reloadData()
  5055. }
  5056. func pdfListViewAddEditAreaTypeChanged(_ pdfListView: CPDFListView!) {
  5057. if self.listView.shouAddEditAreaType() != .text && self.listView.shouAddEditAreaType() != .image {
  5058. if viewManager.subToolMode != .None {
  5059. viewManager.subToolMode = .None
  5060. pdfToolbarController?.cancelSelectedSecondToolbarItems(viewManager.toolMode)
  5061. pdfToolbarController?.refreshSecondToolbarItemsState()
  5062. }
  5063. }
  5064. }
  5065. //MARK: -Crop
  5066. func pdfListViewChangedSelectionOrMagnification(_ pdfListView: CPDFListView!) {
  5067. reloadPopUIWindow()
  5068. }
  5069. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  5070. if (!self.listView.isEqual(to: pdfListView)) {
  5071. return
  5072. }
  5073. if (self.listView.toolMode != .CSelectToolMode) {
  5074. return
  5075. }
  5076. reloadPopUIWindow()
  5077. }
  5078. func pdfListViewHaveDocumentAttribute() -> Bool {
  5079. if(!self.listView.document.allowsCopying) {
  5080. self.removeOwnerPassword()
  5081. return false
  5082. }
  5083. return true
  5084. }
  5085. func pdfListViewShowTipView() -> Bool {
  5086. let popWindow = KMNPopAnnotationWindowController.shared
  5087. if popWindow.window?.isVisible == true {
  5088. return true
  5089. }
  5090. return false
  5091. }
  5092. func pdfListViewAnnotationEditModeChange(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  5093. reloadPopUIWindow()
  5094. }
  5095. func pdfListViewAnnotationChange(_ color: NSColor!, forActiveAnnotation annotation: CPDFAnnotation!) {
  5096. rightSideController?.reloadData()
  5097. NotificationCenter.default.post(name: toolbarImageColorChangedNotificationName, object: nil)
  5098. }
  5099. //MARK: -Measure
  5100. func pdfListViewAnnotationMeasureInfoChange(_ pdfListView: CPDFListView!, with annotation: CPDFAnnotation!) {
  5101. guard let data = annotation else {
  5102. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  5103. distanceMeasureInfoWindowController?.clearData()
  5104. }
  5105. return
  5106. }
  5107. if let lineAnnotation = annotation as? CPDFLineAnnotation {
  5108. handleLineAnnotation(lineAnnotation)
  5109. } else if let polylineAnnotation = annotation as? CPDFPolylineAnnotation {
  5110. handlePolylineAnnotation(polylineAnnotation)
  5111. } else if let polygonAnnotation = annotation as? CPDFPolygonAnnotation {
  5112. handlePolygonAnnotation(polygonAnnotation)
  5113. }
  5114. }
  5115. func pdfListViewMeasureCancel(_ pdfListView: CPDFListView!) {
  5116. cancelMeasureType()
  5117. }
  5118. private func handleLineAnnotation(_ annotation: CPDFLineAnnotation) {
  5119. if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  5120. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  5121. distanceMeasureInfoWindowController?.showWindow(self)
  5122. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  5123. areaMeasureInfoWindowController?.hideFloatingWindow()
  5124. distanceMeasureInfoWindowController?.showWindow(self)
  5125. } else if distanceMeasureInfoWindowController?.window?.isVisible == false {
  5126. distanceMeasureInfoWindowController?.showWindow(self)
  5127. }
  5128. let measureInfo = annotation.measureInfo
  5129. let startPoint = annotation.startPoint
  5130. let endPoint = annotation.endPoint
  5131. let angle = atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x) * (180.0 / .pi)
  5132. distanceMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  5133. distanceMeasureInfoWindowController?.xLabel.stringValue = String(format: "%.0f", abs(endPoint.x - startPoint.x))
  5134. distanceMeasureInfoWindowController?.yLabel.stringValue = String(format: "%.0f", abs(endPoint.y - startPoint.y))
  5135. distanceMeasureInfoWindowController?.reloadData(with: measureInfo!)
  5136. }
  5137. private func handlePolylineAnnotation(_ annotation: CPDFPolylineAnnotation) {
  5138. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  5139. distanceMeasureInfoWindowController?.hideFloatingWindow()
  5140. perimeterMeasureInfoWindowController?.showWindow(self)
  5141. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  5142. areaMeasureInfoWindowController?.hideFloatingWindow()
  5143. perimeterMeasureInfoWindowController?.showWindow(self)
  5144. } else if perimeterMeasureInfoWindowController?.window?.isVisible == false {
  5145. perimeterMeasureInfoWindowController?.showWindow(self)
  5146. }
  5147. let measureInfo = annotation.measureInfo
  5148. let savePoints = annotation.savePoints()
  5149. var angle: CGFloat = 0
  5150. if savePoints.count >= 3 {
  5151. let count = savePoints.count
  5152. let startPoint = savePoints[count - 3].pointValue
  5153. let midPoint = savePoints[count - 2].pointValue
  5154. let endPoint = savePoints.last!.pointValue
  5155. angle = angleBetweenPoints(startPoint, midPoint, endPoint)
  5156. }
  5157. angle = 180 - angle
  5158. perimeterMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  5159. perimeterMeasureInfoWindowController?.reloadData(with: measureInfo!)
  5160. }
  5161. private func handlePolygonAnnotation(_ annotation: CPDFPolygonAnnotation) {
  5162. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  5163. distanceMeasureInfoWindowController?.hideFloatingWindow()
  5164. areaMeasureInfoWindowController?.showWindow(self)
  5165. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  5166. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  5167. areaMeasureInfoWindowController?.showWindow(self)
  5168. } else if areaMeasureInfoWindowController?.window?.isVisible == false {
  5169. areaMeasureInfoWindowController?.showWindow(self)
  5170. }
  5171. let measureInfo = annotation.measureInfo
  5172. let savePoints = annotation.savePoints
  5173. var angle: CGFloat = 0
  5174. if savePoints.count >= 3 {
  5175. let count = savePoints.count
  5176. let startPoint = (savePoints[count - 3] as AnyObject).pointValue
  5177. let midPoint = (savePoints[count - 2] as AnyObject).pointValue
  5178. let endPoint = (savePoints.lastObject as AnyObject).pointValue
  5179. angle = angleBetweenPoints(startPoint!, midPoint!, endPoint!)
  5180. }
  5181. angle = 180 - angle
  5182. areaMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  5183. areaMeasureInfoWindowController?.reloadData(measureInfo!)
  5184. }
  5185. private func angleBetweenPoints(_ startPoint: CGPoint, _ midPoint: CGPoint, _ endPoint: CGPoint) -> CGFloat {
  5186. let vector1 = CGPoint(x: midPoint.x - startPoint.x, y: midPoint.y - startPoint.y)
  5187. let vector2 = CGPoint(x: endPoint.x - midPoint.x, y: endPoint.y - midPoint.y)
  5188. let dotProduct = vector1.x * vector2.x + vector1.y * vector2.y
  5189. let magnitude1 = sqrt(vector1.x * vector1.x + vector1.y * vector1.y)
  5190. let magnitude2 = sqrt(vector2.x * vector2.x + vector2.y * vector2.y)
  5191. return acos(dotProduct / (magnitude1 * magnitude2)) * (180.0 / .pi)
  5192. }
  5193. @objc func pdfUpdatedFinish() {
  5194. splitPDFController?.inPDFFirst = false
  5195. splitPDFController?.outPDFFirst = false
  5196. }
  5197. //MARK: - Notification
  5198. @objc private func pdfViewScrollViewDidScroll(_ noti: Notification) {
  5199. reloadPopUIWindow()
  5200. if listView.popOver?.isShown == true {
  5201. listView.popOver?.close()
  5202. }
  5203. }
  5204. func pageCountChangedNotification(_ sender: Notification) {
  5205. guard let document = sender.object as? CPDFDocument else {
  5206. return
  5207. }
  5208. botaViewController?.pageCountChangedAction(document: document)
  5209. }
  5210. func annotationsAttributeHasChange(_ sender: Notification) {
  5211. guard let dict = sender.object as? [String : Any] else {
  5212. return
  5213. }
  5214. if let anno = dict["object"] as? CPDFAnnotation {
  5215. let value = dict["keyPath"] as? String ?? ""
  5216. let didEnd = dict["didEnd"] as? Bool ?? false
  5217. if didEnd {
  5218. if value == CPDFAnnotationBoundsKey {
  5219. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  5220. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  5221. }
  5222. }
  5223. if anno.km_isMeasure() && anno.contents == nil {
  5224. anno.contents = anno.string() ?? ""
  5225. }
  5226. var pageIndexes = IndexSet()
  5227. pageIndexes.insert(Int(anno.page.pageIndex()))
  5228. reloadIfThumData(pageIndexs: pageIndexes)
  5229. reloadPopUIWindow()
  5230. } else {
  5231. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  5232. var pageIndexes = IndexSet()
  5233. pageIndexes.insert(Int(anno.page.pageIndex()))
  5234. reloadIfThumData(pageIndexs: pageIndexes)
  5235. reloadPopUIWindow()
  5236. }
  5237. }
  5238. }
  5239. }
  5240. func reloadThumData(pageIndexs: IndexSet) {
  5241. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(reloadIfThumData), object: pageIndexs)
  5242. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  5243. self.reloadIfThumData(pageIndexs: pageIndexs)
  5244. }
  5245. }
  5246. func reloadIfThumData(pageIndexs: IndexSet) {
  5247. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexs)
  5248. botaViewController?.reloadData()
  5249. }
  5250. @objc fileprivate func signatureStateChangeNoti(_ sender: Notification) {
  5251. guard let objecListView = sender.object as? CPDFListView else {
  5252. return
  5253. }
  5254. if listView == objecListView {
  5255. reloadDigitalSigns()
  5256. alertTipViewController.reloadDigitalAlertUI()
  5257. alertTipViewController.reloadAlertUIFrame()
  5258. let signatureWidget = listView.editAnnotation
  5259. if let signatureWidgetAnnotation = signatureWidget as? CPDFSignatureWidgetAnnotation {
  5260. let signature = signatureWidgetAnnotation.signature()
  5261. if signature == nil {
  5262. return
  5263. }
  5264. signaturestateVC.signature = signature
  5265. signaturestateVC.reloadData()
  5266. }
  5267. }
  5268. }
  5269. }
  5270. //MARK: - KMNThumbnailBaseViewDelegate
  5271. extension KMMainViewController: KMNThumbnailBaseViewDelegate {
  5272. func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int) {
  5273. exitPageEditMode()
  5274. if listView.currentPageIndex != currentIndex {
  5275. listView.go(toPageIndex: currentIndex, animated: true)
  5276. }
  5277. viewManager.isPageEditMode = false
  5278. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_PageEdit_Identifier)
  5279. }
  5280. func insertPDFThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, pdfDocment: CPDFDocument?) {
  5281. if(pdfDocment != nil) {
  5282. insertDocuments.insert(pdfDocment!)
  5283. }
  5284. }
  5285. func changeIndexPathsThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, selectionIndexPaths: Set<IndexPath>, selectionStrings: String) {
  5286. toolbarManager.page_pageInfo_Property.text = selectionStrings
  5287. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  5288. toolbarManager.page_pageInfo_Property.creatable = true
  5289. }
  5290. pdfToolbarController?.refreshSecondToolbarItemsState()
  5291. }
  5292. }
  5293. //MARK: - KMNLeftSideViewControllerDelegate
  5294. extension KMMainViewController: KMNLeftSideViewControllerDelegate {
  5295. func enterPageEditLeftSideViewController(leftSideViewController: KMNLeftSideViewController) {
  5296. if viewManager.isPageEditMode == false {
  5297. viewManager.isPageEditMode = true
  5298. if(pdfToolbarController != nil) {
  5299. kmPDFToolbarControllerDidToolbarItemClicked(pdfToolbarController!, KMPDFToolbar_PageEdit_Identifier)
  5300. pdfToolbarController?.resetSecondToolbar()
  5301. }
  5302. }
  5303. }
  5304. func changeSelectePageLeftSideViewController(leftSideViewController: KMNLeftSideViewController, pageIndex: Int) {
  5305. if(listView.currentPageIndex != pageIndex) {
  5306. listView.go(toPageIndex: pageIndex, animated: true)
  5307. }
  5308. }
  5309. func addBookmarkForLeftC(controller: KMNLeftSideViewController, bookmark: CPDFBookmark?, info: [String : Any]?) {
  5310. if let result = info?["result"] as? Bool {
  5311. if result == false {
  5312. if let targetV = listView.superview {
  5313. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("This page has been bookmarked"), type: .normal_custom, fromView: targetV, point:CGPointMake(targetV.frame.size.width/2, targetV.bounds.size.height-24))
  5314. }
  5315. }
  5316. }
  5317. }
  5318. func switchSearchPopWindow(controller: KMNLeftSideViewController) {
  5319. if(viewManager.pdfSideBarType == .search) {
  5320. toggleCloseLeftSide()
  5321. }
  5322. let handdler = controller.searchViewC.handdler
  5323. showSearchPopWindow(type: handdler.type, keyborad: handdler.searchKey, replaceText: handdler.replaceKey, results: handdler.searchResults)
  5324. }
  5325. func searchTypeDidChange(controller: KMNLeftSideViewController) {
  5326. let handdler = controller.searchViewC.handdler
  5327. if handdler.type == .replace {
  5328. viewManager.toolMode = .Edit
  5329. updatePDFViewAnnotationMode()
  5330. }
  5331. }
  5332. }
  5333. //MARK: - ComponentGroupDelegate
  5334. extension KMMainViewController: ComponentGroupDelegate {
  5335. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  5336. if menuItemProperty?.identifier == PDFViewMenuIdentifier_PageNext {
  5337. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5338. if objectListView.canGoToNextPage() {
  5339. objectListView.goToNextPage(nil)
  5340. }
  5341. }
  5342. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PagePrevious) {
  5343. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5344. if objectListView.canGoToPreviousPage() {
  5345. objectListView.goToPreviousPage(nil)
  5346. }
  5347. }
  5348. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageFirst) {
  5349. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5350. if objectListView.canGoToFirstPage() {
  5351. objectListView.goToFirstPage(nil)
  5352. }
  5353. }
  5354. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageLast) {
  5355. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5356. if objectListView.canGoToLastPage() {
  5357. objectListView.goToLastPage(nil)
  5358. }
  5359. }
  5360. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_LaserPoint) {
  5361. listView.exitPresentationDrawMode()
  5362. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Brush) {
  5363. listView.enterPresentationDrawMode()
  5364. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Exit) {
  5365. self.exitFullScreen()
  5366. } else if menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIRewrite {
  5367. viewManager.pdfSideBarType = .aiTools
  5368. sideBarController?.reloadData()
  5369. if let sideVC = sideBarController {
  5370. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  5371. }
  5372. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIProofread) {
  5373. viewManager.pdfSideBarType = .aiTools
  5374. sideBarController?.reloadData()
  5375. if let sideVC = sideBarController {
  5376. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  5377. }
  5378. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AITranslate) {
  5379. viewManager.pdfSideBarType = .aiTools
  5380. sideBarController?.reloadData()
  5381. if let sideVC = sideBarController {
  5382. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  5383. }
  5384. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Past) {
  5385. let theEvent = menuItemProperty?.representedObject
  5386. if let currentEvent = theEvent as? NSEvent {
  5387. var pagePoint = CGPoint.zero
  5388. if let page = listView.pageAndPoint(&pagePoint, for: currentEvent, nearest: false) {
  5389. listView.menuPointPaste(pagePoint, page: page, isRightPaste: true)
  5390. }
  5391. }
  5392. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllText) {
  5393. listView.selectAll(nil)
  5394. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddBook) {
  5395. menuItemBookMarkClick_add(sender: nil)
  5396. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TextTool) {
  5397. listView.toolMode = .CTextToolMode
  5398. listView.annotationType = .unkown
  5399. viewManager.viewToolsType = .Select
  5400. pdfToolbarController?.reloadToolsView()
  5401. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MoveTool) {
  5402. listView.toolMode = .CMoveToolMode
  5403. listView.annotationType = .unkown
  5404. viewManager.viewToolsType = .Scroll
  5405. pdfToolbarController?.reloadToolsView()
  5406. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectTool) {
  5407. listView.toolMode = .CSelectToolMode
  5408. listView.annotationType = .unkown
  5409. viewManager.viewToolsType = .Content_Selection
  5410. pdfToolbarController?.reloadToolsView()
  5411. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MagnifyTool) {
  5412. listView.toolMode = .CMagnifyToolMode
  5413. listView.annotationType = .unkown
  5414. viewManager.viewToolsType = .Magnify
  5415. pdfToolbarController?.reloadToolsView()
  5416. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectZoomTool) {
  5417. listView.toolMode = .CSelectZoomToolMode
  5418. listView.annotationType = .unkown
  5419. viewManager.viewToolsType = .AreaZoom
  5420. pdfToolbarController?.reloadToolsView()
  5421. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Single) {
  5422. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5423. objectListView.menuItemClick_SinglePage(nil)
  5424. }
  5425. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SingleContinuous) {
  5426. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5427. objectListView.menuItemClick_SinglePagesContinuous(nil)
  5428. }
  5429. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPages) {
  5430. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5431. objectListView.menuItemClick_TwoPages(nil)
  5432. }
  5433. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPagesContinuous) {
  5434. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5435. objectListView.menuItemClick_TwoPagesContinuous(nil)
  5436. }
  5437. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BookMode) {
  5438. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5439. objectListView.menuItemClick_BookMode(nil)
  5440. }
  5441. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ReadMode) {
  5442. viewManager.isPDFReadMode = !viewManager.isPDFReadMode
  5443. if viewManager.isPDFReadMode {
  5444. openPDFReadMode()
  5445. } else {
  5446. exitPDFReadMode()
  5447. }
  5448. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleWidth) {
  5449. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5450. objectListView.autoScales = true
  5451. }
  5452. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScalePage) {
  5453. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5454. let pageHeight = objectListView.currentPage()!.size.height
  5455. let pdfviewHeight = objectListView.bounds.size.height
  5456. objectListView.scaleFactor = pdfviewHeight/pageHeight
  5457. objectListView.autoScales = false
  5458. }
  5459. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleOrg) {
  5460. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5461. if objectListView.scaleFactor != 1.0 {
  5462. objectListView.scaleFactor = 1.0
  5463. objectListView.autoScales = false
  5464. }
  5465. }
  5466. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomIn) {
  5467. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5468. var scale = objectListView.scaleFactor
  5469. switch scale {
  5470. case 0...0.25:
  5471. scale += 0.25
  5472. case 0.25...3:
  5473. scale += 0.25
  5474. case 3.1...10:
  5475. scale += 0.4
  5476. case 10.1...100:
  5477. scale += 1
  5478. default:
  5479. scale += 1
  5480. }
  5481. objectListView.scaleFactor = scale
  5482. }
  5483. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomOut) {
  5484. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5485. var scale = objectListView.scaleFactor
  5486. switch scale {
  5487. case 0...0.25:
  5488. scale = 0
  5489. case 0.25...3:
  5490. scale -= 0.25
  5491. case 3.1...10:
  5492. scale -= 0.4
  5493. case 10.1...100:
  5494. scale -= 1
  5495. default:
  5496. scale -= 1
  5497. }
  5498. objectListView.scaleFactor = scale
  5499. }
  5500. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateLeft) {
  5501. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  5502. let objectListView = dic["Object"] as? CPDFListView
  5503. let theEvent = dic["theEvent"] as? NSEvent
  5504. if(objectListView != nil && theEvent != nil) {
  5505. var pagePoint = CGPoint.zero
  5506. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  5507. rotateLeft(page: page, listView: objectListView)
  5508. }
  5509. }
  5510. }
  5511. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateRight) {
  5512. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  5513. let objectListView = dic["Object"] as? CPDFListView
  5514. let theEvent = dic["theEvent"] as? NSEvent
  5515. if(objectListView != nil && theEvent != nil) {
  5516. var pagePoint = CGPoint.zero
  5517. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  5518. rotateRight(page: page, listView: objectListView)
  5519. }
  5520. }
  5521. }
  5522. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_EnterPageNum) {
  5523. sideBarController?.beginEditing()
  5524. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageBack) {
  5525. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5526. if(objectListView.canGoBack() == true) {
  5527. objectListView.goBack(nil)
  5528. }
  5529. }
  5530. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageForward) {
  5531. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  5532. if(objectListView.canGoForward() == true) {
  5533. objectListView.goForward(nil)
  5534. }
  5535. }
  5536. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AutoScroll) {
  5537. toggleAutoFlow(nil)
  5538. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightForm) {
  5539. highlightFormFiled(nil)
  5540. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightLink) {
  5541. highlightLinks(nil)
  5542. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RestForm) {
  5543. resetForm(nil)
  5544. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Search) {
  5545. if botaViewController != nil {
  5546. switchSearchPopWindow(controller: botaViewController!)
  5547. }
  5548. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Print) {
  5549. menuItemAction_print(nil)
  5550. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Properties) {
  5551. menuItemAction_property(nil)
  5552. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Copy) {
  5553. if(listView.isEditing() == true) {
  5554. listView.copyEditAreaAction()
  5555. } else {
  5556. listView.copy(nil)
  5557. }
  5558. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Hight) {
  5559. if let currentSelect = listView.currentSelection {
  5560. if(currentSelect.selectionType() == .text) {
  5561. listView.addAnnotation(with: .highlight, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  5562. listView.currentSelection = nil;
  5563. }
  5564. }
  5565. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Underline) {
  5566. if let currentSelect = listView.currentSelection {
  5567. if(currentSelect.selectionType() == .text) {
  5568. listView.addAnnotation(with: .underline, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  5569. listView.currentSelection = nil;
  5570. }
  5571. }
  5572. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Squiggly) {
  5573. if let currentSelect = listView.currentSelection {
  5574. if(currentSelect.selectionType() == .text) {
  5575. listView.addAnnotation(with: .squiggly, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  5576. listView.currentSelection = nil;
  5577. }
  5578. }
  5579. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_StrikeOut) {
  5580. if let currentSelect = listView.currentSelection {
  5581. if(currentSelect.selectionType() == .text) {
  5582. listView.addAnnotation(with: .strikeOut, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  5583. listView.currentSelection = nil;
  5584. }
  5585. }
  5586. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Square) {
  5587. if let currentSelect = listView.currentSelection {
  5588. listView.addAnnotation(with: .square, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  5589. listView.currentSelection = nil;
  5590. }
  5591. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Circle) {
  5592. if let currentSelect = listView.currentSelection {
  5593. listView.addAnnotation(with: .circle, selection: currentSelect, page: currentSelect.page, bounds: listView.currentSelection.bounds)
  5594. listView.currentSelection = nil;
  5595. }
  5596. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddOutLine) {
  5597. addOutLineItemAction()
  5598. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TTS) {
  5599. startSpeaking(nil)
  5600. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SearchText) {
  5601. searchBaiduAction()
  5602. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllForm) {
  5603. selectAllFormAnnotation()
  5604. listView.setNeedsDisplayForVisiblePages()
  5605. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowFormName) {
  5606. listView.showFormFieldName = true
  5607. listView.setNeedsDisplayForVisiblePages()
  5608. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllAnnotation) {
  5609. selectAllNomerAnnotation()
  5610. listView.setNeedsDisplayForVisiblePages()
  5611. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowAnnotation) {
  5612. let isHiden = listView.hideNotes
  5613. listView.hideNotes = !isHiden
  5614. listView.setNeedsDisplayForVisiblePages()
  5615. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_CopyText) {
  5616. var copyText:String = ""
  5617. let annotations = listView.activeAnnotations
  5618. for i in 0 ..< (annotations?.count ?? 0){
  5619. if let an = annotations?[i] as? CPDFMarkupAnnotation {
  5620. let markupContent = an.markupContent()
  5621. if markupContent.isEmpty == false {
  5622. if copyText.isEmpty == true {
  5623. copyText = markupContent
  5624. } else {
  5625. copyText = "\n" + markupContent
  5626. }
  5627. }
  5628. }
  5629. }
  5630. let pboard = NSPasteboard.general
  5631. if copyText.isEmpty == false {
  5632. pboard.clearContents()
  5633. pboard.writeObjects([copyText as NSPasteboardWriting])
  5634. }
  5635. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Cut) {
  5636. if(listView.isEditing() == true) {
  5637. listView.cutEditAreaAction()
  5638. } else {
  5639. listView.cut(nil)
  5640. }
  5641. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Delete) {
  5642. if(listView.isEditing() == true) {
  5643. listView.remove(with: listView.km_EditingAreas())
  5644. } else {
  5645. listView.delete(nil)
  5646. }
  5647. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowPopUI) {
  5648. UserDefaults.standard.setValue(true, forKey: settingsShowQuickActionBarKey)
  5649. SettingsManager.sharedInstance.showQuickActionBar = true
  5650. reloadPopUIWindow()
  5651. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_LinkReade) {
  5652. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortFirstAnnotation) {
  5653. listView.menuItemClick_BringFront(nil)
  5654. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortTopAnnotation) {
  5655. listView.menuItemClick_BringForward(nil)
  5656. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortBottomAnnotation) {
  5657. listView.menuItemClick_SendBackward(nil)
  5658. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortLastAnnotation) {
  5659. listView.menuItemClick_SendBack(nil)
  5660. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Content) {
  5661. if let activeAnnotation = listView.activeAnnotation {
  5662. listView.edit(activeAnnotation)
  5663. }
  5664. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Apply) {
  5665. redactApplyAction()
  5666. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Multipage) {
  5667. if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation {
  5668. redactMultipageAction(redactAnnotation: redactAnnotation)
  5669. }
  5670. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Default) {
  5671. if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation {
  5672. setPropertiesDefault(annotation: redactAnnotation)
  5673. }
  5674. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewSingleMode) {
  5675. listView.viewSplitMode = .disable
  5676. reloadPDFSplitInfo()
  5677. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewVerticalMode) {
  5678. listView.viewSplitMode = .vertical
  5679. reloadPDFSplitInfo()
  5680. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewHorizontalMode) {
  5681. listView.viewSplitMode = .horizontal
  5682. reloadPDFSplitInfo()
  5683. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_Sync) {
  5684. viewManager.splitSyncScroll = !viewManager.splitSyncScroll
  5685. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ShowBar) {
  5686. viewManager.splitShowBottomBar = !viewManager.splitShowBottomBar
  5687. splitPDFController?.refreshToolbarState()
  5688. reloadPDFPageNumberToolbar()
  5689. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_LeftAlight) {
  5690. if(listView.isEditing()) {
  5691. listView.changeEditingAreas(.left)
  5692. } else {
  5693. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
  5694. }
  5695. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_VerticallyAlight) {
  5696. if(listView.isEditing()) {
  5697. listView.changeEditingAreas(.vertical)
  5698. } else {
  5699. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
  5700. }
  5701. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RightAlight) {
  5702. if(listView.isEditing()) {
  5703. listView.changeEditingAreas(.right)
  5704. } else {
  5705. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
  5706. }
  5707. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TopAlight) {
  5708. if(listView.isEditing()) {
  5709. listView.changeEditingAreas(.top)
  5710. } else {
  5711. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
  5712. }
  5713. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HorizontallyAlight) {
  5714. if(listView.isEditing()) {
  5715. listView.changeEditingAreas(.horizontally)
  5716. } else {
  5717. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
  5718. }
  5719. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BottomAlight) {
  5720. if(listView.isEditing()) {
  5721. listView.changeEditingAreas(.bottom)
  5722. } else {
  5723. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
  5724. }
  5725. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeHorizontally) {
  5726. if(listView.isEditing()) {
  5727. listView.changeEditingAreas(.disHorizontally)
  5728. } else {
  5729. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
  5730. }
  5731. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeVertically) {
  5732. if(listView.isEditing()) {
  5733. listView.changeEditingAreas(.disVertical)
  5734. } else {
  5735. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
  5736. }
  5737. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportJPG) {
  5738. if(listView.isEditing() == true) {
  5739. listView.exportEditingImageAreasAction(format: "jpg")
  5740. } else {
  5741. if let currentSelection = listView.currentSelection {
  5742. if(currentSelection.selectionType() == .image) {
  5743. listView.exprotSelection(currentSelection, type: 1)
  5744. }
  5745. }
  5746. }
  5747. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPNG) {
  5748. if(listView.isEditing() == true) {
  5749. listView.exportEditingImageAreasAction(format: "png")
  5750. } else {
  5751. if let currentSelection = listView.currentSelection {
  5752. if(currentSelection.selectionType() == .image) {
  5753. listView.exprotSelection(currentSelection, type: 0)
  5754. }
  5755. }
  5756. }
  5757. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPDF) {
  5758. if(listView.isEditing() == true) {
  5759. listView.exportEditingImageAreasAction(format: "pdf")
  5760. } else {
  5761. if let currentSelection = listView.currentSelection {
  5762. if(currentSelection.selectionType() == .image) {
  5763. listView.exprotSelection(currentSelection, type: 2)
  5764. }
  5765. }
  5766. }
  5767. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Paste) {
  5768. listView.pasteEditAreaMatchStyleAction()
  5769. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_NoStylePaste) {
  5770. listView.pasteEditAreaAction()
  5771. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_SelectAll) {
  5772. if listView.km_EditingAreas().count <= 0 {
  5773. listView.selectAllAreaAction()
  5774. } else {
  5775. listView.selectAllAction(with: listView.km_EditingAreas().first)
  5776. }
  5777. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddLink) {
  5778. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_link_Identifier)
  5779. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddText) {
  5780. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_text_Identifier)
  5781. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddImage) {
  5782. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_image_Identifier)
  5783. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontBold) {
  5784. listView.setEditingTextarea_Bold()
  5785. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontItalic) {
  5786. listView.setEditingTextarea_Italic()
  5787. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontUnderline) {
  5788. listView.setEditingTextarea_Under()
  5789. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontStrikeout) {
  5790. listView.setEditingTextarea_Strikeout()
  5791. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomIn) {
  5792. listView.zoomInEditTextFontSize()
  5793. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomOut) {
  5794. listView.zoomInEditTextFontSize()
  5795. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontColor) {
  5796. let colorPanel = NSColorPanel.shared
  5797. colorPanel.setTarget(self)
  5798. colorPanel.setAction(#selector(editFontColorItemPanelAction(_:)))
  5799. colorPanel.orderFront(nil)
  5800. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH1Name) {
  5801. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h1)
  5802. self.updateEditPDFTextFontModel(model)
  5803. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH2Name) {
  5804. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h2)
  5805. self.updateEditPDFTextFontModel(model)
  5806. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH3Name) {
  5807. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h3)
  5808. self.updateEditPDFTextFontModel(model)
  5809. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB1Name) {
  5810. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b1)
  5811. self.updateEditPDFTextFontModel(model)
  5812. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB2Name) {
  5813. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b2)
  5814. self.updateEditPDFTextFontModel(model)
  5815. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB3Name) {
  5816. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b3)
  5817. self.updateEditPDFTextFontModel(model)
  5818. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontLeftAlight) {
  5819. listView.setEditingTextarea_Alignment(align:.left)
  5820. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontCenterAlight) {
  5821. listView.setEditingTextarea_Alignment(align:.center)
  5822. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontRightAlight) {
  5823. listView.setEditingTextarea_Alignment(align:.right)
  5824. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontJustAlight) {
  5825. listView.setEditingTextarea_Alignment(align:.justified)
  5826. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateLeft) {
  5827. listView.rotateEditingAreas(90)
  5828. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateRight) {
  5829. listView.rotateEditingAreas(-90)
  5830. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_HorizontalMirror) {
  5831. listView.reverseYAction()
  5832. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_VerticalMirror) {
  5833. listView.reverseXAction()
  5834. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Crop) {
  5835. listView.cropAction()
  5836. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Replace) {
  5837. listView.replaceImageEdit()
  5838. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RedactProperties) {
  5839. if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation{
  5840. showRedactProperty(readactAnnotation: redactAnnotation)
  5841. }
  5842. }
  5843. }
  5844. func componentGroupDidDismiss(group: ComponentGroup?) {
  5845. }
  5846. func updateEditPDFTextFontModel(_ model: KMEditPDFTextFontModel) {
  5847. let fontName = model.fontName
  5848. let fontStyle = model.fontStyle
  5849. let fontSize = model.fontSize
  5850. let bold = model.bold
  5851. let italic = model.italic
  5852. let alignment = model.alignment
  5853. let font = CPDFFont(familyName: fontName, fontStyle: fontStyle)
  5854. listView.setEditingTextarea_font(font: font)
  5855. listView.setEditingTextarea_FontSize(size: fontSize)
  5856. listView.setEditingTextarea(isBold: bold)
  5857. listView.setEditingTextarea(isItalic: italic)
  5858. listView.setEditingTextarea_Alignment(align: alignment)
  5859. }
  5860. }
  5861. // MARK: - KMSnapshotWindowControllerDelegate
  5862. extension KMMainViewController: KMSnapshotWindowControllerDelegate {
  5863. func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
  5864. }
  5865. func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
  5866. return CGRectZero
  5867. }
  5868. func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
  5869. }
  5870. }
  5871. // MARK: - CPDFDocumentDelegate
  5872. extension KMMainViewController: CPDFDocumentDelegate {
  5873. func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
  5874. }
  5875. func documentDidEndDocumentFind(_ document: CPDFDocument!) {
  5876. }
  5877. }
  5878. // MARK: - 测量代理CDistanceSettingWindowControllerDelegate
  5879. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  5880. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, updateMeasureInfo measureInfo: CPDFMeasureInfo?) {
  5881. if measureInfo != nil {
  5882. if self.listView.activeAnnotations.count > 0 {
  5883. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  5884. self.updateMeasureInfo((self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo, withNewMeasure: measureInfo)
  5885. } else if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  5886. self.updateMeasureInfo((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo, withNewMeasure: measureInfo)
  5887. } else if let data = self.listView.activeAnnotation as? CPDFLineAnnotation, data.isMeasure {
  5888. self.updateMeasureInfo(data.measureInfo, withNewMeasure: measureInfo)
  5889. }
  5890. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  5891. }
  5892. self.updateMeasureInfo(self.listView.distanceMeasureInfo, withNewMeasure: measureInfo)
  5893. self.updateMeasureInfo(self.listView.perimeterMeasureInfo, withNewMeasure: measureInfo)
  5894. self.updateMeasureInfo(self.listView.polygonAreaMeasureInfo, withNewMeasure: measureInfo)
  5895. self.updateMeasureInfo(self.listView.squareAreaMeasureInfo, withNewMeasure: measureInfo)
  5896. }
  5897. }
  5898. func updateMeasureInfo(_ measureInfo: CPDFMeasureInfo?, withNewMeasure newMeasure: CPDFMeasureInfo?) {
  5899. guard let measureInfo = measureInfo else { return }
  5900. guard let newMeasure = newMeasure else { return }
  5901. measureInfo.rulerBase = newMeasure.rulerBase
  5902. measureInfo.rulerTranslate = newMeasure.rulerTranslate
  5903. measureInfo.rulerBaseUnit = newMeasure.rulerBaseUnit
  5904. measureInfo.rulerTranslateUnit = newMeasure.rulerTranslateUnit
  5905. measureInfo.factor = newMeasure.factor
  5906. measureInfo.precision = newMeasure.precision
  5907. }
  5908. }
  5909. //MARK: - extension
  5910. extension KMMainViewController {
  5911. internal func removeNotifications() {
  5912. NotificationCenter.default.removeObserver(self)
  5913. }
  5914. func removeAllAnnotations() {
  5915. let alert = NSAlert()
  5916. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  5917. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  5918. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  5919. if (alert.runModal() != .alertFirstButtonReturn) {
  5920. return
  5921. }
  5922. DispatchQueue.main.async {
  5923. self.removeAllAnnotationsStore.store(t: self.listView)
  5924. }
  5925. }
  5926. //MARK: - AI
  5927. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  5928. if (self.document != nil) {
  5929. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  5930. } else {
  5931. AIChatInfoManager.defaultManager.currentFilePath = ""
  5932. }
  5933. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  5934. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  5935. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  5936. let documentArray = NSDocumentController.shared.documents
  5937. var didFileEdit: Bool = false
  5938. var curDoc: KMMainDocument!
  5939. for document in documentArray {
  5940. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  5941. didFileEdit = document.isDocumentEdited
  5942. curDoc = document as! KMMainDocument
  5943. break
  5944. }
  5945. }
  5946. if didFileEdit {
  5947. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  5948. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  5949. do {
  5950. try FileManager.default.removeItem(at: tempFileURL)
  5951. } catch {
  5952. }
  5953. }
  5954. if curDoc != nil {
  5955. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  5956. }
  5957. }
  5958. windowVC.window?.becomeMain()
  5959. }
  5960. }
  5961. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  5962. } else {
  5963. var windowRect = windowVC.window?.frame
  5964. windowRect!.origin.x = NSMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  5965. windowRect!.origin.y = NSMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  5966. windowVC.window?.setFrame(windowRect!, display: true)
  5967. windowVC.didSetOriginFrame = true
  5968. }
  5969. windowVC.eventLabel = "AITools_Tbr"
  5970. windowVC.showWindow(nil)
  5971. if (aiConfigType != .none) {
  5972. windowVC.eventLabel = "AITools_Start"
  5973. if self.listView.currentSelection?.string()?.isEmpty == false {
  5974. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  5975. }
  5976. windowVC.chooseAIFunctionWithType(aiConfigType)
  5977. }
  5978. }
  5979. @objc func aiTipIconViewShowStateChangeNoti() {
  5980. }
  5981. //MARK: - 引导
  5982. func loadFunctionGuide() -> Void {
  5983. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  5984. if self.view.window != nil {
  5985. self.loadOpenFileFunctionGuide(.openFileNormal)
  5986. }
  5987. }
  5988. }
  5989. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  5990. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  5991. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  5992. guard let guideWC = self.guideInfoWindowController else { return }
  5993. guideWC.type = .openFileNormal
  5994. // guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? .zero
  5995. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  5996. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  5997. }
  5998. guideWC.finishHandle = { [weak self] windowVC, type in
  5999. if type == .windowNewFinish ||
  6000. type == . windowDigitalFinish {
  6001. self?.checkFirstTrialController()
  6002. }
  6003. }
  6004. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  6005. self?.checkFirstTrialController()
  6006. }
  6007. var rect = self.view.window!.frame
  6008. rect.size.height -= 20
  6009. guideWC.window?.setFrame(rect, display: false)
  6010. guideWC.window?.minSize = rect.size
  6011. guideWC.window?.maxSize = rect.size
  6012. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  6013. guideWC.show()
  6014. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  6015. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  6016. guard let guideWC = self.guideInfoWindowController else { return }
  6017. guideWC.type = .digitalSignGuide
  6018. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  6019. guideWC.finishHandle = { [weak self] windowVC, type in
  6020. self?.checkFirstTrialController()
  6021. }
  6022. var rect = self.view.window!.frame
  6023. rect.size.height -= 20
  6024. guideWC.window?.setFrame(rect, display: false)
  6025. guideWC.window?.minSize = rect.size
  6026. guideWC.window?.maxSize = rect.size
  6027. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  6028. guideWC.show()
  6029. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  6030. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  6031. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  6032. guard let guideWC = self.guideInfoWindowController else { return }
  6033. guideWC.type = .pdfCompareGuide
  6034. guard let win = self.view.window else {
  6035. return
  6036. }
  6037. guideWC.finishHandle = { [weak self] winC, type in
  6038. if type == .windowNewFinish {
  6039. DispatchQueue.main.async {
  6040. self?.loadOpenFileFunctionGuide(.measureGuide)
  6041. }
  6042. return
  6043. }
  6044. }
  6045. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  6046. var rect = self.view.window!.frame
  6047. rect.size.height -= 20
  6048. guideWC.window?.setFrame(rect, display: false)
  6049. guideWC.window?.minSize = rect.size
  6050. guideWC.window?.maxSize = rect.size
  6051. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  6052. guideWC.show()
  6053. }
  6054. } else if showType == .measureGuide && KMGuideInfoWindowController.availableShow(.measureGuide) {
  6055. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  6056. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  6057. guard let guideWC = self.guideInfoWindowController else { return }
  6058. guard let _ = self.view.window else {
  6059. return
  6060. }
  6061. guideWC.type = .measureGuide
  6062. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  6063. var rect = self.view.window?.frame ?? .zero
  6064. rect.size.height -= 20
  6065. guideWC.window?.setFrame(rect, display: false)
  6066. guideWC.window?.minSize = rect.size
  6067. guideWC.window?.maxSize = rect.size
  6068. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  6069. guideWC.show()
  6070. }
  6071. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  6072. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  6073. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  6074. guard let guideWC = self.guideInfoWindowController else { return }
  6075. guideWC.type = .convertGuide
  6076. guard let win = self.view.window else {
  6077. return
  6078. }
  6079. guideWC.purchaseHandle = { [weak self] windowVC in
  6080. #if VERSION_DMG
  6081. if IAPProductsManager.default().isAvailableAllFunction() {
  6082. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  6083. //Convert:
  6084. } else {
  6085. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  6086. limitWC.continueBlock = { windowController in
  6087. }
  6088. limitWC.window?.center()
  6089. limitWC.showWindow(nil)
  6090. }
  6091. } else {
  6092. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  6093. }
  6094. #else
  6095. if IAPProductsManager.default().isAvailableAllFunction() {
  6096. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  6097. //Convert:
  6098. } else {
  6099. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  6100. vc.showWindow(nil)
  6101. }
  6102. } else {
  6103. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  6104. }
  6105. #endif
  6106. }
  6107. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  6108. var rect = self.view.window?.frame ?? .zero
  6109. rect.size.height -= 20
  6110. guideWC.window?.setFrame(rect, display: false)
  6111. guideWC.window?.minSize = rect.size
  6112. guideWC.window?.maxSize = rect.size
  6113. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  6114. guideWC.show()
  6115. }
  6116. } else {
  6117. }
  6118. }
  6119. func checkFirstTrialController() -> Void {
  6120. #if VERSION_DMG
  6121. //打开文档后引导相关
  6122. if VerificationManager.default().status == .none {
  6123. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  6124. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  6125. if lastVersion.isEmpty || lastVersion != appVersion {
  6126. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  6127. UserDefaults.standard.synchronize()
  6128. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  6129. }
  6130. }
  6131. #endif
  6132. }
  6133. // MARK: - Private Methods
  6134. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  6135. let url = URL(fileURLWithPath: filePath)
  6136. guard let document = PDFDocument(url: url) else {
  6137. return false
  6138. }
  6139. let pageCount = document.pageCount
  6140. return pageCount > 30
  6141. }
  6142. // MARK: - Redact 【标记密文】
  6143. func redactApplyAction() {
  6144. let returnCode = KMAlertTool.runModelForMainThread_r(message: "", informative: KMLocalizedString("This will permanently remove the redacted information from this document. Once you save this document, you won’t be able to retrieve the redacted information."), buttons: [KMLocalizedString("Apply"), KMLocalizedString("Cancel")])
  6145. if returnCode == .alertFirstButtonReturn {
  6146. DispatchQueue.main.async {
  6147. self.saveAsPath()
  6148. }
  6149. }
  6150. }
  6151. func redactMultipageAction(redactAnnotation:CPDFRedactAnnotation) {
  6152. let pagesWindowController = KMRedactSelectPagesWindowController(document: listView.document)
  6153. pagesWindowController.own_beginSheetModal(for: self.view.window) { result in
  6154. }
  6155. pagesWindowController.callback = { [weak self] pages in
  6156. if pages.count > 0 {
  6157. self?.listView.redactAddAnnotationPages(pages, redactAnnotation: redactAnnotation)
  6158. }
  6159. }
  6160. }
  6161. func setPropertiesDefault(annotation:CPDFRedactAnnotation) {
  6162. CPDFRedactAnnotation.update_defaultOutlineColor(annotation.borderColor())
  6163. CPDFRedactAnnotation.update_defaultFillColor(annotation.interiorColor())
  6164. CPDFRedactAnnotation.update_defaultTextColor(annotation.fontColor())
  6165. CPDFRedactAnnotation.update_defaultFontSize(annotation.fontSize)
  6166. CPDFRedactAnnotation.update_defaultFontAlignment(annotation.alignment())
  6167. CPDFRedactAnnotation.update_defaultOverlayText(annotation.overlayText())
  6168. }
  6169. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  6170. let windowController = KMRedactConfirmWindowController(type)
  6171. self.currentWindowController = windowController
  6172. self.view.window?.beginSheet(windowController.window!)
  6173. windowController.itemClick = { [weak self] index in
  6174. if (index == 2) { /// 取消
  6175. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  6176. self?.currentWindowController = nil
  6177. callback()
  6178. return
  6179. }
  6180. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  6181. self?.currentWindowController = nil
  6182. let panel = NSSavePanel()
  6183. panel.nameFieldStringValue = "[新文件]"+((self?.listView.document?.documentURL.lastPathComponent) ?? "")
  6184. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  6185. button.state = .on
  6186. panel.accessoryView = button
  6187. panel.isExtensionHidden = true
  6188. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  6189. if response != .OK {
  6190. callback()
  6191. return
  6192. }
  6193. if (type == .redactOne) {
  6194. let anno = self!.listView.activeAnnotation
  6195. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  6196. callback()
  6197. return
  6198. }
  6199. (anno as! CPDFRedactAnnotation).applyRedaction()
  6200. } else if (type == .redactAll) {
  6201. self?.listView.document?.applyRedactions()
  6202. } else if (type == .eraserOne) {
  6203. let anno = self!.listView.activeAnnotation
  6204. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  6205. callback()
  6206. return
  6207. }
  6208. anno?.page.erasureRedact(from: anno!.bounds)
  6209. } else if (type == .eraserAll) {
  6210. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  6211. if (result == false) {
  6212. callback()
  6213. return
  6214. }
  6215. }
  6216. }
  6217. self!.listView.document?.write(to: panel.url)
  6218. if (button.state == .on) {
  6219. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  6220. }
  6221. } else {
  6222. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  6223. }
  6224. callback()
  6225. }
  6226. }
  6227. }
  6228. // MARK: - 保存文档
  6229. internal func needSaveDocument() -> Bool {
  6230. if (self.isPDFDocumentEdited) {
  6231. return self.isPDFDocumentEdited
  6232. }
  6233. if (self.needSave) {
  6234. return self.needSave
  6235. }
  6236. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  6237. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  6238. return false
  6239. }
  6240. return true
  6241. }
  6242. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  6243. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  6244. if (overlook) {
  6245. document?.save(nil)
  6246. return
  6247. }
  6248. if (self.isPDFDocumentEdited) {
  6249. self.clearIsPDFDocumentEdited()
  6250. self.needSave = false
  6251. document?.save(nil)
  6252. return
  6253. }
  6254. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  6255. return
  6256. }
  6257. document?.save(nil)
  6258. }
  6259. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  6260. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  6261. if (overlook) {
  6262. DispatchQueue.main.async {
  6263. document?.save(nil)
  6264. callback()
  6265. }
  6266. return
  6267. }
  6268. if (self.isPDFDocumentEdited) {
  6269. self.clearIsPDFDocumentEdited()
  6270. self.needSave = false
  6271. DispatchQueue.main.async {
  6272. document?.save(nil)
  6273. callback()
  6274. }
  6275. return
  6276. }
  6277. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  6278. callback()
  6279. return
  6280. }
  6281. DispatchQueue.main.async {
  6282. document?.save(nil)
  6283. callback()
  6284. }
  6285. }
  6286. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  6287. // 显示进度
  6288. AutoSaveManager.manager.isSaving = true
  6289. self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
  6290. self.progressC?.maxValue = 3.0
  6291. self.progressC?.increment(by: 1.0)
  6292. // 保存文档
  6293. self.asyncSaveDocument { [weak self] params in
  6294. // 执行进度 [假进度]
  6295. self?.progressC?.increment(by: 1.0)
  6296. self?.progressC?.increment(by: 1.0)
  6297. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  6298. // 隐藏进度
  6299. self?.hiddenProgressWindow()
  6300. DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  6301. AutoSaveManager.manager.isSaving = false
  6302. }
  6303. // 回调
  6304. callback()
  6305. }
  6306. }
  6307. }
  6308. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  6309. self.document?.write(toFile: tempPath)
  6310. }
  6311. // MARK: - 定时保存
  6312. func addAutoSaveEvent() {
  6313. if (self.autoSaveTimer != nil) {
  6314. self.autoSaveTimer?.invalidate()
  6315. self.autoSaveTimer = nil
  6316. }
  6317. if self.document != nil {
  6318. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  6319. self?.autoSaveTimerAction(timer)
  6320. })
  6321. }
  6322. self.checkAutoSaveInfo()
  6323. }
  6324. func checkAutoSaveInfo() {
  6325. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  6326. return
  6327. }
  6328. if AutoSaveManager.manager.autoSaveAlertShow {
  6329. return
  6330. }
  6331. AutoSaveManager.manager.autoSaveDidEndAction = false
  6332. AutoSaveManager.manager.autoSaveAlertShow = true
  6333. let blockSaveWindow = AutoSavePopController()
  6334. blockSaveWindow.cancelHandle = { [weak self] windowController in
  6335. AutoSaveManager.manager.autoSaveDidEndAction = true
  6336. AutoSaveManager.manager.clearCache()
  6337. self?.km_quick_endSheet()
  6338. }
  6339. blockSaveWindow.confirmHandle = { [weak self] windowController in
  6340. self?.km_quick_endSheet()
  6341. self?.saveAutoSaveInfo()
  6342. }
  6343. self.km_beginSheet(windowC: blockSaveWindow)
  6344. }
  6345. func saveAutoSaveInfo() {
  6346. let openPanel = NSOpenPanel()
  6347. openPanel.canChooseDirectories = true
  6348. openPanel.canChooseFiles = false
  6349. openPanel.allowsMultipleSelection = false
  6350. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  6351. openPanel.beginSheetModal(for: win!) { result in
  6352. if (result == .OK) {
  6353. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  6354. for path in AutoSaveManager.manager.opendPaths ?? [] {
  6355. let _path = path as? String
  6356. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  6357. newPath = self.getValidFilePath(newPath)
  6358. do {
  6359. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  6360. } catch {
  6361. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  6362. }
  6363. }
  6364. AutoSaveManager.manager.clearCache()
  6365. }
  6366. AutoSaveManager.manager.autoSaveDidEndAction = true
  6367. }
  6368. }
  6369. func autoSaveTimerAction(_ timer: Timer) {
  6370. if (self.document == nil || self.listView.document?.documentURL.path == nil) {
  6371. return
  6372. }
  6373. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  6374. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  6375. return
  6376. }
  6377. if let data = self.document?.isLocked, data {
  6378. return
  6379. }
  6380. if AutoSaveManager.manager.autoSaveEnabled == false {
  6381. return
  6382. }
  6383. let documentArray = NSDocumentController.shared.documents
  6384. var didFileEdit = false
  6385. for doc in documentArray {
  6386. if doc.fileURL?.path == self.document?.documentURL.path {
  6387. didFileEdit = doc.isDocumentEdited
  6388. break
  6389. }
  6390. }
  6391. if (didFileEdit == false) {
  6392. return
  6393. }
  6394. AutoSaveManager.manager.isSaving = true
  6395. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView.document?.documentURL.path ?? "")
  6396. if (!self.document!.isLocked) {
  6397. self.document?.write(to: URL(fileURLWithPath: savePath))
  6398. }
  6399. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  6400. AutoSaveManager.manager.isSaving = false
  6401. }
  6402. }
  6403. func removeAutoSaveInfo() {
  6404. if self.autoSaveTimer != nil {
  6405. self.autoSaveTimer?.invalidate()
  6406. self.autoSaveTimer = nil
  6407. }
  6408. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  6409. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  6410. return
  6411. }
  6412. if AutoSaveManager.manager.autoSaveEnabled == false {
  6413. return
  6414. }
  6415. if self.document == nil || self.listView.document?.documentURL.path == nil {
  6416. return
  6417. }
  6418. AutoSaveManager.manager.removeAutoSavePath(self.listView.document?.documentURL.path ?? "")
  6419. }
  6420. // MARK: - 选择缩放模式
  6421. @objc public func selectZoom(_ type: KMPDFZoomType) {
  6422. switch type {
  6423. case .width:
  6424. self.listView.autoScales = true
  6425. break
  6426. case .fit:
  6427. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  6428. let pdfviewHeight = self.listView.bounds.size.height
  6429. self.listView.scaleFactor = pdfviewHeight/pageHeight
  6430. self.listView.autoScales = false
  6431. }
  6432. break
  6433. case .actualSize:
  6434. if self.listView.scaleFactor != 1.0 {
  6435. self.listView.scaleFactor = 1.0
  6436. self.listView.autoScales = false
  6437. }
  6438. break
  6439. case .zoom_In:
  6440. self.doZoomIn(nil)
  6441. break
  6442. case .zoom_Out:
  6443. self.doZoomOut(nil)
  6444. break
  6445. }
  6446. }
  6447. func doZoomIn(_ sender: Any?) {
  6448. if (self.listView.canZoomIn) {
  6449. self.listView.zoomIn(nil)
  6450. }
  6451. }
  6452. func doZoomOut(_ sender: Any?) {
  6453. if (self.listView.canZoomOut) {
  6454. self.listView.zoomOut(nil)
  6455. }
  6456. }
  6457. // MARK: - Event 监听
  6458. private func addEventMonitor() {
  6459. if (self.eventMonitor != nil) {
  6460. self.removeEventMonitor()
  6461. }
  6462. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .leftMouseDown, .leftMouseUp]) { [weak self] event in
  6463. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  6464. self?.listView.magnifyWheel(event)
  6465. return nil
  6466. } else if event.type == .leftMouseDown {
  6467. let point = event.locationInView(self?.listView ?? NSView())
  6468. let presentationDrawView = self?.listView.presentationDrawView
  6469. if let data = self?.interactionMode, data == .presentation,CGRectContainsPoint(self?.listView.frame ?? .zero, point),presentationDrawView?.isHidden == true { // 幻灯片模式下
  6470. if point.x >= (self?.listView.frame.maxX ?? 0) / 2 {
  6471. let can = self?.listView.canGoToNextPage() ?? false
  6472. if can {
  6473. self?.listView.goToNextPage(nil)
  6474. }
  6475. } else {
  6476. let can = self?.listView.canGoToPreviousPage() ?? false
  6477. if can {
  6478. self?.listView.goToPreviousPage(nil)
  6479. }
  6480. }
  6481. return nil
  6482. }
  6483. }
  6484. return event
  6485. }
  6486. }
  6487. private func removeEventMonitor() {
  6488. if (self.eventMonitor != nil) {
  6489. KMPrint("已移除事件监听")
  6490. NSEvent.removeMonitor(self.eventMonitor as Any)
  6491. self.eventMonitor = nil
  6492. }
  6493. }
  6494. func addKeyEventMonitor() {
  6495. if (self.keyEventMonitor != nil) {
  6496. self.removeKeyEventMonitor()
  6497. }
  6498. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  6499. if event.keyCode == 53 {
  6500. if self?.listView.annotationType == .freeText {
  6501. self?.listView.keyDown(with: event)
  6502. }
  6503. } else {
  6504. }
  6505. return event
  6506. }
  6507. }
  6508. func removeKeyEventMonitor() {
  6509. if (self.keyEventMonitor != nil) {
  6510. KMPrint("removeKeyEventMonitor 已移除事件监听")
  6511. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  6512. self.keyEventMonitor = nil
  6513. }
  6514. }
  6515. //MARK: - Mouse Event
  6516. override func mouseMoved(with event: NSEvent) {
  6517. self.view.window?.mouseMoved(with: event)
  6518. }
  6519. override func keyDown(with event: NSEvent) {
  6520. listView.keyDown(with: event)
  6521. }
  6522. // MARK: - Tools
  6523. func pdfViewCanHorizontalScroll() -> Bool {
  6524. let scroll = self.listView.scroll()
  6525. if (scroll == nil) {
  6526. return false
  6527. }
  6528. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  6529. }
  6530. func pdfViewCanVerticalScroll() -> Bool {
  6531. let scroll = self.listView.scroll()
  6532. if (scroll == nil) {
  6533. return false
  6534. }
  6535. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  6536. }
  6537. // MARK: - Public Methods
  6538. // 清理数据 [eg. 通知]
  6539. public func clearData() {
  6540. KMThumbnailCache.shared.clearCache()
  6541. self.removeNotifications()
  6542. if (self.listView.spellingTag() > 0) {
  6543. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  6544. }
  6545. self.removeAutoSaveInfo()
  6546. self.myDocument = nil
  6547. if textFieldSheet.window?.isVisible == true {
  6548. textFieldSheet.close()
  6549. }
  6550. if NSColorPanel.shared.isVisible == true {
  6551. NSColorPanel.shared.close()
  6552. }
  6553. if KMInfoWindowController.shared.window?.isVisible == true {
  6554. KMInfoWindowController.shared.close()
  6555. }
  6556. }
  6557. public func clearSecureOptions() {
  6558. self._secureOptions = nil
  6559. self.documentAttribute = nil
  6560. }
  6561. public func clearRemoveSecureFlag() {
  6562. self._removeSecureFlag = false
  6563. }
  6564. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  6565. km_synchronized(self) {
  6566. self.model.isPDFDocumentEdited = true
  6567. if type == .editText || type == .editImage {
  6568. }
  6569. if let _document = self.myDocument {
  6570. KMTools.setDocumentEditedState(document: _document)
  6571. }
  6572. }
  6573. }
  6574. public func clearIsPDFDocumentEdited() {
  6575. km_synchronized(self) {
  6576. self.model.isPDFDocumentEdited = false
  6577. }
  6578. }
  6579. func showSnapshots(setups: NSArray?) {
  6580. if self.listView.document != nil {
  6581. for setup in setups ?? [] {
  6582. let swc = KMSnapshotWindowController()
  6583. swc.delegate = self
  6584. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  6585. swc.setForceOnTop(self.interactionMode != .normal)
  6586. self.myDocument?.addWindowController(swc)
  6587. }
  6588. }
  6589. }
  6590. // MARK: - Noti Actions
  6591. internal func documentDidUnlockNotification(_ sender: Notification) {
  6592. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  6593. if (self.myDocument == nil) {
  6594. return
  6595. }
  6596. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  6597. self.hiddenSecureLimitTip()
  6598. }
  6599. let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
  6600. if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  6601. return
  6602. }
  6603. let type = SettingsManager.sharedInstance.keychainType
  6604. if (type == .never) {
  6605. return
  6606. }
  6607. if (type == .always) {
  6608. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  6609. return
  6610. }
  6611. // 保存到钥匙串
  6612. let alert = NSAlert()
  6613. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  6614. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  6615. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  6616. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  6617. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  6618. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  6619. return
  6620. }
  6621. }
  6622. }
  6623. internal func applicationWillTerminateNotification(_ sender: Notification) {
  6624. self.savePageNumberIfNeed()
  6625. self.saveDocument()
  6626. }
  6627. }