KMMainViewController.swift 318 KB

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