KMMainViewController.swift 344 KB

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