KMMainViewController.swift 322 KB

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