KMMainViewController.swift 333 KB

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