KMMainViewController.swift 343 KB

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