KMMainViewController.swift 370 KB

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