KMMainViewController.swift 374 KB

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