KMMainViewController.swift 324 KB

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