KMMainViewController.swift 326 KB

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