KMMainViewController.swift 421 KB

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