KMMainViewController.swift 348 KB

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