KMMainViewController.swift 346 KB

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