KMMainViewController.swift 328 KB

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