KMMainViewController.swift 425 KB

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