KMMainViewController.swift 323 KB

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