KMMainViewController.swift 372 KB

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