KMMainViewController.swift 371 KB

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