KMMainViewController.swift 323 KB

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