KMMainViewController.swift 375 KB

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