KMMainViewController.swift 332 KB

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