KMMainViewController.swift 357 KB

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