KMMainViewController.swift 323 KB

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