KMMainViewController.swift 325 KB

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