viewer.js 441 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2024 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. /******/ // The require scope
  23. /******/ var __webpack_require__ = {};
  24. /******/
  25. /************************************************************************/
  26. /******/ /* webpack/runtime/define property getters */
  27. /******/ (() => {
  28. /******/ // define getter functions for harmony exports
  29. /******/ __webpack_require__.d = (exports, definition) => {
  30. /******/ for(var key in definition) {
  31. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  32. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  33. /******/ }
  34. /******/ }
  35. /******/ };
  36. /******/ })();
  37. /******/
  38. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  39. /******/ (() => {
  40. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  41. /******/ })();
  42. /******/
  43. /************************************************************************/
  44. var __webpack_exports__ = {};
  45. // EXPORTS
  46. __webpack_require__.d(__webpack_exports__, {
  47. PDFViewerApplication: () => (/* reexport */ PDFViewerApplication),
  48. PDFViewerApplicationConstants: () => (/* binding */ AppConstants),
  49. PDFViewerApplicationOptions: () => (/* reexport */ AppOptions)
  50. });
  51. ;// CONCATENATED MODULE: ./web/ui_utils.js
  52. const DEFAULT_SCALE_VALUE = "auto";
  53. const DEFAULT_SCALE = 1.0;
  54. const DEFAULT_SCALE_DELTA = 1.1;
  55. const MIN_SCALE = 0.1;
  56. const MAX_SCALE = 10.0;
  57. const UNKNOWN_SCALE = 0;
  58. const MAX_AUTO_SCALE = 1.25;
  59. const SCROLLBAR_PADDING = 40;
  60. const VERTICAL_PADDING = 5;
  61. const RenderingStates = {
  62. INITIAL: 0,
  63. RUNNING: 1,
  64. PAUSED: 2,
  65. FINISHED: 3
  66. };
  67. const PresentationModeState = {
  68. UNKNOWN: 0,
  69. NORMAL: 1,
  70. CHANGING: 2,
  71. FULLSCREEN: 3
  72. };
  73. const SidebarView = {
  74. UNKNOWN: -1,
  75. NONE: 0,
  76. THUMBS: 1,
  77. OUTLINE: 2,
  78. ATTACHMENTS: 3,
  79. LAYERS: 4
  80. };
  81. const TextLayerMode = {
  82. DISABLE: 0,
  83. ENABLE: 1,
  84. ENABLE_PERMISSIONS: 2
  85. };
  86. const ScrollMode = {
  87. UNKNOWN: -1,
  88. VERTICAL: 0,
  89. HORIZONTAL: 1,
  90. WRAPPED: 2,
  91. PAGE: 3
  92. };
  93. const SpreadMode = {
  94. UNKNOWN: -1,
  95. NONE: 0,
  96. ODD: 1,
  97. EVEN: 2
  98. };
  99. const CursorTool = {
  100. SELECT: 0,
  101. HAND: 1,
  102. ZOOM: 2
  103. };
  104. const AutoPrintRegExp = /\bprint\s*\(/;
  105. class OutputScale {
  106. constructor() {
  107. const pixelRatio = window.devicePixelRatio || 1;
  108. this.sx = pixelRatio;
  109. this.sy = pixelRatio;
  110. }
  111. get scaled() {
  112. return this.sx !== 1 || this.sy !== 1;
  113. }
  114. }
  115. function scrollIntoView(element, spot, scrollMatches = false) {
  116. let parent = element.offsetParent;
  117. if (!parent) {
  118. console.error("offsetParent is not set -- cannot scroll");
  119. return;
  120. }
  121. let offsetY = element.offsetTop + element.clientTop;
  122. let offsetX = element.offsetLeft + element.clientLeft;
  123. while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) {
  124. offsetY += parent.offsetTop;
  125. offsetX += parent.offsetLeft;
  126. parent = parent.offsetParent;
  127. if (!parent) {
  128. return;
  129. }
  130. }
  131. if (spot) {
  132. if (spot.top !== undefined) {
  133. offsetY += spot.top;
  134. }
  135. if (spot.left !== undefined) {
  136. offsetX += spot.left;
  137. parent.scrollLeft = offsetX;
  138. }
  139. }
  140. parent.scrollTop = offsetY;
  141. }
  142. function watchScroll(viewAreaElement, callback, abortSignal = undefined) {
  143. const debounceScroll = function (evt) {
  144. if (rAF) {
  145. return;
  146. }
  147. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  148. rAF = null;
  149. const currentX = viewAreaElement.scrollLeft;
  150. const lastX = state.lastX;
  151. if (currentX !== lastX) {
  152. state.right = currentX > lastX;
  153. }
  154. state.lastX = currentX;
  155. const currentY = viewAreaElement.scrollTop;
  156. const lastY = state.lastY;
  157. if (currentY !== lastY) {
  158. state.down = currentY > lastY;
  159. }
  160. state.lastY = currentY;
  161. callback(state);
  162. });
  163. };
  164. const state = {
  165. right: true,
  166. down: true,
  167. lastX: viewAreaElement.scrollLeft,
  168. lastY: viewAreaElement.scrollTop,
  169. _eventHandler: debounceScroll
  170. };
  171. let rAF = null;
  172. viewAreaElement.addEventListener("scroll", debounceScroll, {
  173. useCapture: true,
  174. signal: abortSignal
  175. });
  176. abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), {
  177. once: true
  178. });
  179. return state;
  180. }
  181. function parseQueryString(query) {
  182. const params = new Map();
  183. for (const [key, value] of new URLSearchParams(query)) {
  184. params.set(key.toLowerCase(), value);
  185. }
  186. return params;
  187. }
  188. const InvisibleCharsRegExp = /[\x00-\x1F]/g;
  189. function removeNullCharacters(str, replaceInvisible = false) {
  190. if (!InvisibleCharsRegExp.test(str)) {
  191. return str;
  192. }
  193. if (replaceInvisible) {
  194. return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " ");
  195. }
  196. return str.replaceAll("\x00", "");
  197. }
  198. function binarySearchFirstItem(items, condition, start = 0) {
  199. let minIndex = start;
  200. let maxIndex = items.length - 1;
  201. if (maxIndex < 0 || !condition(items[maxIndex])) {
  202. return items.length;
  203. }
  204. if (condition(items[minIndex])) {
  205. return minIndex;
  206. }
  207. while (minIndex < maxIndex) {
  208. const currentIndex = minIndex + maxIndex >> 1;
  209. const currentItem = items[currentIndex];
  210. if (condition(currentItem)) {
  211. maxIndex = currentIndex;
  212. } else {
  213. minIndex = currentIndex + 1;
  214. }
  215. }
  216. return minIndex;
  217. }
  218. function approximateFraction(x) {
  219. if (Math.floor(x) === x) {
  220. return [x, 1];
  221. }
  222. const xinv = 1 / x;
  223. const limit = 8;
  224. if (xinv > limit) {
  225. return [1, limit];
  226. } else if (Math.floor(xinv) === xinv) {
  227. return [1, xinv];
  228. }
  229. const x_ = x > 1 ? xinv : x;
  230. let a = 0,
  231. b = 1,
  232. c = 1,
  233. d = 1;
  234. while (true) {
  235. const p = a + c,
  236. q = b + d;
  237. if (q > limit) {
  238. break;
  239. }
  240. if (x_ <= p / q) {
  241. c = p;
  242. d = q;
  243. } else {
  244. a = p;
  245. b = q;
  246. }
  247. }
  248. let result;
  249. if (x_ - a / b < c / d - x_) {
  250. result = x_ === x ? [a, b] : [b, a];
  251. } else {
  252. result = x_ === x ? [c, d] : [d, c];
  253. }
  254. return result;
  255. }
  256. function floorToDivide(x, div) {
  257. return x - x % div;
  258. }
  259. function getPageSizeInches({
  260. view,
  261. userUnit,
  262. rotate
  263. }) {
  264. const [x1, y1, x2, y2] = view;
  265. const changeOrientation = rotate % 180 !== 0;
  266. const width = (x2 - x1) / 72 * userUnit;
  267. const height = (y2 - y1) / 72 * userUnit;
  268. return {
  269. width: changeOrientation ? height : width,
  270. height: changeOrientation ? width : height
  271. };
  272. }
  273. function backtrackBeforeAllVisibleElements(index, views, top) {
  274. if (index < 2) {
  275. return index;
  276. }
  277. let elt = views[index].div;
  278. let pageTop = elt.offsetTop + elt.clientTop;
  279. if (pageTop >= top) {
  280. elt = views[index - 1].div;
  281. pageTop = elt.offsetTop + elt.clientTop;
  282. }
  283. for (let i = index - 2; i >= 0; --i) {
  284. elt = views[i].div;
  285. if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) {
  286. break;
  287. }
  288. index = i;
  289. }
  290. return index;
  291. }
  292. function getVisibleElements({
  293. scrollEl,
  294. views,
  295. sortByVisibility = false,
  296. horizontal = false,
  297. rtl = false
  298. }) {
  299. const top = scrollEl.scrollTop,
  300. bottom = top + scrollEl.clientHeight;
  301. const left = scrollEl.scrollLeft,
  302. right = left + scrollEl.clientWidth;
  303. function isElementBottomAfterViewTop(view) {
  304. const element = view.div;
  305. const elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  306. return elementBottom > top;
  307. }
  308. function isElementNextAfterViewHorizontally(view) {
  309. const element = view.div;
  310. const elementLeft = element.offsetLeft + element.clientLeft;
  311. const elementRight = elementLeft + element.clientWidth;
  312. return rtl ? elementLeft < right : elementRight > left;
  313. }
  314. const visible = [],
  315. ids = new Set(),
  316. numViews = views.length;
  317. let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop);
  318. if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) {
  319. firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top);
  320. }
  321. let lastEdge = horizontal ? right : -1;
  322. for (let i = firstVisibleElementInd; i < numViews; i++) {
  323. const view = views[i],
  324. element = view.div;
  325. const currentWidth = element.offsetLeft + element.clientLeft;
  326. const currentHeight = element.offsetTop + element.clientTop;
  327. const viewWidth = element.clientWidth,
  328. viewHeight = element.clientHeight;
  329. const viewRight = currentWidth + viewWidth;
  330. const viewBottom = currentHeight + viewHeight;
  331. if (lastEdge === -1) {
  332. if (viewBottom >= bottom) {
  333. lastEdge = viewBottom;
  334. }
  335. } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) {
  336. break;
  337. }
  338. if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) {
  339. continue;
  340. }
  341. const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom);
  342. const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right);
  343. const fractionHeight = (viewHeight - hiddenHeight) / viewHeight,
  344. fractionWidth = (viewWidth - hiddenWidth) / viewWidth;
  345. const percent = fractionHeight * fractionWidth * 100 | 0;
  346. visible.push({
  347. id: view.id,
  348. x: currentWidth,
  349. y: currentHeight,
  350. view,
  351. percent,
  352. widthPercent: fractionWidth * 100 | 0
  353. });
  354. ids.add(view.id);
  355. }
  356. const first = visible[0],
  357. last = visible.at(-1);
  358. if (sortByVisibility) {
  359. visible.sort(function (a, b) {
  360. const pc = a.percent - b.percent;
  361. if (Math.abs(pc) > 0.001) {
  362. return -pc;
  363. }
  364. return a.id - b.id;
  365. });
  366. }
  367. return {
  368. first,
  369. last,
  370. views: visible,
  371. ids
  372. };
  373. }
  374. function normalizeWheelEventDirection(evt) {
  375. let delta = Math.hypot(evt.deltaX, evt.deltaY);
  376. const angle = Math.atan2(evt.deltaY, evt.deltaX);
  377. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  378. delta = -delta;
  379. }
  380. return delta;
  381. }
  382. function normalizeWheelEventDelta(evt) {
  383. const deltaMode = evt.deltaMode;
  384. let delta = normalizeWheelEventDirection(evt);
  385. const MOUSE_PIXELS_PER_LINE = 30;
  386. const MOUSE_LINES_PER_PAGE = 30;
  387. if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
  388. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  389. } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) {
  390. delta /= MOUSE_LINES_PER_PAGE;
  391. }
  392. return delta;
  393. }
  394. function isValidRotation(angle) {
  395. return Number.isInteger(angle) && angle % 90 === 0;
  396. }
  397. function isValidScrollMode(mode) {
  398. return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN;
  399. }
  400. function isValidSpreadMode(mode) {
  401. return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN;
  402. }
  403. function isPortraitOrientation(size) {
  404. return size.width <= size.height;
  405. }
  406. const animationStarted = new Promise(function (resolve) {
  407. window.requestAnimationFrame(resolve);
  408. });
  409. const docStyle = document.documentElement.style;
  410. function clamp(v, min, max) {
  411. return Math.min(Math.max(v, min), max);
  412. }
  413. class ProgressBar {
  414. #classList = null;
  415. #disableAutoFetchTimeout = null;
  416. #percent = 0;
  417. #style = null;
  418. #visible = true;
  419. constructor(bar) {
  420. this.#classList = bar.classList;
  421. this.#style = bar.style;
  422. }
  423. get percent() {
  424. return this.#percent;
  425. }
  426. set percent(val) {
  427. this.#percent = clamp(val, 0, 100);
  428. if (isNaN(val)) {
  429. this.#classList.add("indeterminate");
  430. return;
  431. }
  432. this.#classList.remove("indeterminate");
  433. this.#style.setProperty("--progressBar-percent", `${this.#percent}%`);
  434. }
  435. setWidth(viewer) {
  436. if (!viewer) {
  437. return;
  438. }
  439. const container = viewer.parentNode;
  440. const scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  441. if (scrollbarWidth > 0) {
  442. this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`);
  443. }
  444. }
  445. setDisableAutoFetch(delay = 5000) {
  446. if (this.#percent === 100 || isNaN(this.#percent)) {
  447. return;
  448. }
  449. if (this.#disableAutoFetchTimeout) {
  450. clearTimeout(this.#disableAutoFetchTimeout);
  451. }
  452. this.show();
  453. this.#disableAutoFetchTimeout = setTimeout(() => {
  454. this.#disableAutoFetchTimeout = null;
  455. this.hide();
  456. }, delay);
  457. }
  458. hide() {
  459. if (!this.#visible) {
  460. return;
  461. }
  462. this.#visible = false;
  463. this.#classList.add("hidden");
  464. }
  465. show() {
  466. if (this.#visible) {
  467. return;
  468. }
  469. this.#visible = true;
  470. this.#classList.remove("hidden");
  471. }
  472. }
  473. function getActiveOrFocusedElement() {
  474. let curRoot = document;
  475. let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus");
  476. while (curActiveOrFocused?.shadowRoot) {
  477. curRoot = curActiveOrFocused.shadowRoot;
  478. curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus");
  479. }
  480. return curActiveOrFocused;
  481. }
  482. function apiPageLayoutToViewerModes(layout) {
  483. let scrollMode = ScrollMode.VERTICAL,
  484. spreadMode = SpreadMode.NONE;
  485. switch (layout) {
  486. case "SinglePage":
  487. scrollMode = ScrollMode.PAGE;
  488. break;
  489. case "OneColumn":
  490. break;
  491. case "TwoPageLeft":
  492. scrollMode = ScrollMode.PAGE;
  493. case "TwoColumnLeft":
  494. spreadMode = SpreadMode.ODD;
  495. break;
  496. case "TwoPageRight":
  497. scrollMode = ScrollMode.PAGE;
  498. case "TwoColumnRight":
  499. spreadMode = SpreadMode.EVEN;
  500. break;
  501. }
  502. return {
  503. scrollMode,
  504. spreadMode
  505. };
  506. }
  507. function apiPageModeToSidebarView(mode) {
  508. switch (mode) {
  509. case "UseNone":
  510. return SidebarView.NONE;
  511. case "UseThumbs":
  512. return SidebarView.THUMBS;
  513. case "UseOutlines":
  514. return SidebarView.OUTLINE;
  515. case "UseAttachments":
  516. return SidebarView.ATTACHMENTS;
  517. case "UseOC":
  518. return SidebarView.LAYERS;
  519. }
  520. return SidebarView.NONE;
  521. }
  522. function toggleCheckedBtn(button, toggle, view = null) {
  523. button.classList.toggle("toggled", toggle);
  524. button.setAttribute("aria-checked", toggle);
  525. view?.classList.toggle("hidden", !toggle);
  526. }
  527. function toggleExpandedBtn(button, toggle, view = null) {
  528. button.classList.toggle("toggled", toggle);
  529. button.setAttribute("aria-expanded", toggle);
  530. view?.classList.toggle("hidden", !toggle);
  531. }
  532. ;// CONCATENATED MODULE: ./web/app_options.js
  533. {
  534. var compatParams = new Map();
  535. const userAgent = navigator.userAgent || "";
  536. const platform = navigator.platform || "";
  537. const maxTouchPoints = navigator.maxTouchPoints || 1;
  538. const isAndroid = /Android/.test(userAgent);
  539. const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1;
  540. (function () {
  541. if (isIOS || isAndroid) {
  542. compatParams.set("maxCanvasPixels", 5242880);
  543. }
  544. })();
  545. (function () {
  546. if (isAndroid) {
  547. compatParams.set("useSystemFonts", false);
  548. }
  549. })();
  550. }
  551. const OptionKind = {
  552. BROWSER: 0x01,
  553. VIEWER: 0x02,
  554. API: 0x04,
  555. WORKER: 0x08,
  556. EVENT_DISPATCH: 0x10,
  557. PREFERENCE: 0x80
  558. };
  559. const Type = {
  560. BOOLEAN: 0x01,
  561. NUMBER: 0x02,
  562. OBJECT: 0x04,
  563. STRING: 0x08,
  564. UNDEFINED: 0x10
  565. };
  566. const defaultOptions = {
  567. allowedGlobalEvents: {
  568. value: null,
  569. kind: OptionKind.BROWSER
  570. },
  571. canvasMaxAreaInBytes: {
  572. value: -1,
  573. kind: OptionKind.BROWSER + OptionKind.API
  574. },
  575. isInAutomation: {
  576. value: false,
  577. kind: OptionKind.BROWSER
  578. },
  579. localeProperties: {
  580. value: {
  581. lang: navigator.language || "en-US"
  582. },
  583. kind: OptionKind.BROWSER
  584. },
  585. nimbusDataStr: {
  586. value: "",
  587. kind: OptionKind.BROWSER
  588. },
  589. supportsCaretBrowsingMode: {
  590. value: false,
  591. kind: OptionKind.BROWSER
  592. },
  593. supportsDocumentFonts: {
  594. value: true,
  595. kind: OptionKind.BROWSER
  596. },
  597. supportsIntegratedFind: {
  598. value: false,
  599. kind: OptionKind.BROWSER
  600. },
  601. supportsMouseWheelZoomCtrlKey: {
  602. value: true,
  603. kind: OptionKind.BROWSER
  604. },
  605. supportsMouseWheelZoomMetaKey: {
  606. value: true,
  607. kind: OptionKind.BROWSER
  608. },
  609. supportsPinchToZoom: {
  610. value: true,
  611. kind: OptionKind.BROWSER
  612. },
  613. toolbarDensity: {
  614. value: 0,
  615. kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH
  616. },
  617. altTextLearnMoreUrl: {
  618. value: "",
  619. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  620. },
  621. annotationEditorMode: {
  622. value: 0,
  623. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  624. },
  625. annotationMode: {
  626. value: 2,
  627. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  628. },
  629. cursorToolOnLoad: {
  630. value: 0,
  631. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  632. },
  633. debuggerSrc: {
  634. value: "./debugger.mjs",
  635. kind: OptionKind.VIEWER
  636. },
  637. defaultZoomDelay: {
  638. value: 400,
  639. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  640. },
  641. defaultZoomValue: {
  642. value: "",
  643. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  644. },
  645. disableHistory: {
  646. value: false,
  647. kind: OptionKind.VIEWER
  648. },
  649. disablePageLabels: {
  650. value: false,
  651. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  652. },
  653. enableAltText: {
  654. value: false,
  655. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  656. },
  657. enableGuessAltText: {
  658. value: true,
  659. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  660. },
  661. enableHighlightEditor: {
  662. value: false,
  663. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  664. },
  665. enableHighlightFloatingButton: {
  666. value: false,
  667. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  668. },
  669. enablePermissions: {
  670. value: false,
  671. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  672. },
  673. enablePrintAutoRotate: {
  674. value: true,
  675. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  676. },
  677. enableScripting: {
  678. value: true,
  679. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  680. },
  681. enableUpdatedAddImage: {
  682. value: false,
  683. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  684. },
  685. externalLinkRel: {
  686. value: "noopener noreferrer nofollow",
  687. kind: OptionKind.VIEWER
  688. },
  689. externalLinkTarget: {
  690. value: 0,
  691. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  692. },
  693. highlightEditorColors: {
  694. value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F",
  695. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  696. },
  697. historyUpdateUrl: {
  698. value: false,
  699. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  700. },
  701. ignoreDestinationZoom: {
  702. value: false,
  703. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  704. },
  705. imageResourcesPath: {
  706. value: "./images/",
  707. kind: OptionKind.VIEWER
  708. },
  709. maxCanvasPixels: {
  710. value: 2 ** 25,
  711. kind: OptionKind.VIEWER
  712. },
  713. forcePageColors: {
  714. value: false,
  715. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  716. },
  717. pageColorsBackground: {
  718. value: "Canvas",
  719. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  720. },
  721. pageColorsForeground: {
  722. value: "CanvasText",
  723. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  724. },
  725. pdfBugEnabled: {
  726. value: false,
  727. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  728. },
  729. printResolution: {
  730. value: 150,
  731. kind: OptionKind.VIEWER
  732. },
  733. sidebarViewOnLoad: {
  734. value: -1,
  735. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  736. },
  737. scrollModeOnLoad: {
  738. value: -1,
  739. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  740. },
  741. spreadModeOnLoad: {
  742. value: -1,
  743. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  744. },
  745. textLayerMode: {
  746. value: 1,
  747. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  748. },
  749. viewOnLoad: {
  750. value: 0,
  751. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  752. },
  753. cMapPacked: {
  754. value: true,
  755. kind: OptionKind.API
  756. },
  757. cMapUrl: {
  758. value: "../web/cmaps/",
  759. kind: OptionKind.API
  760. },
  761. disableAutoFetch: {
  762. value: false,
  763. kind: OptionKind.API + OptionKind.PREFERENCE
  764. },
  765. disableFontFace: {
  766. value: false,
  767. kind: OptionKind.API + OptionKind.PREFERENCE
  768. },
  769. disableRange: {
  770. value: false,
  771. kind: OptionKind.API + OptionKind.PREFERENCE
  772. },
  773. disableStream: {
  774. value: false,
  775. kind: OptionKind.API + OptionKind.PREFERENCE
  776. },
  777. docBaseUrl: {
  778. value: "",
  779. kind: OptionKind.API
  780. },
  781. enableHWA: {
  782. value: true,
  783. kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE
  784. },
  785. enableXfa: {
  786. value: true,
  787. kind: OptionKind.API + OptionKind.PREFERENCE
  788. },
  789. fontExtraProperties: {
  790. value: false,
  791. kind: OptionKind.API
  792. },
  793. isEvalSupported: {
  794. value: true,
  795. kind: OptionKind.API
  796. },
  797. isOffscreenCanvasSupported: {
  798. value: true,
  799. kind: OptionKind.API
  800. },
  801. maxImageSize: {
  802. value: -1,
  803. kind: OptionKind.API
  804. },
  805. pdfBug: {
  806. value: false,
  807. kind: OptionKind.API
  808. },
  809. standardFontDataUrl: {
  810. value: "../web/standard_fonts/",
  811. kind: OptionKind.API
  812. },
  813. useSystemFonts: {
  814. value: undefined,
  815. kind: OptionKind.API,
  816. type: Type.BOOLEAN + Type.UNDEFINED
  817. },
  818. verbosity: {
  819. value: 1,
  820. kind: OptionKind.API
  821. },
  822. workerPort: {
  823. value: null,
  824. kind: OptionKind.WORKER
  825. },
  826. workerSrc: {
  827. value: "../build/pdf.worker.mjs",
  828. kind: OptionKind.WORKER
  829. }
  830. };
  831. {
  832. defaultOptions.defaultUrl = {
  833. value: "compressed.tracemonkey-pldi-09.pdf",
  834. kind: OptionKind.VIEWER
  835. };
  836. defaultOptions.sandboxBundleSrc = {
  837. value: "../build/pdf.sandbox.mjs",
  838. kind: OptionKind.VIEWER
  839. };
  840. defaultOptions.viewerCssTheme = {
  841. value: 1,
  842. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  843. };
  844. }
  845. {
  846. defaultOptions.disablePreferences = {
  847. value: false,
  848. kind: OptionKind.VIEWER
  849. };
  850. }
  851. const userOptions = new Map();
  852. {
  853. for (const [name, value] of compatParams) {
  854. userOptions.set(name, value);
  855. }
  856. }
  857. class AppOptions {
  858. static eventBus;
  859. constructor() {
  860. throw new Error("Cannot initialize AppOptions.");
  861. }
  862. static get(name) {
  863. return userOptions.has(name) ? userOptions.get(name) : defaultOptions[name]?.value;
  864. }
  865. static getAll(kind = null, defaultOnly = false) {
  866. const options = Object.create(null);
  867. for (const name in defaultOptions) {
  868. const defaultOpt = defaultOptions[name];
  869. if (kind && !(kind & defaultOpt.kind)) {
  870. continue;
  871. }
  872. options[name] = !defaultOnly && userOptions.has(name) ? userOptions.get(name) : defaultOpt.value;
  873. }
  874. return options;
  875. }
  876. static set(name, value) {
  877. this.setAll({
  878. [name]: value
  879. });
  880. }
  881. static setAll(options, prefs = false) {
  882. let events;
  883. for (const name in options) {
  884. const defaultOpt = defaultOptions[name],
  885. userOpt = options[name];
  886. if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) {
  887. continue;
  888. }
  889. const {
  890. kind
  891. } = defaultOpt;
  892. if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) {
  893. continue;
  894. }
  895. if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) {
  896. (events ||= new Map()).set(name, userOpt);
  897. }
  898. userOptions.set(name, userOpt);
  899. }
  900. if (events) {
  901. for (const [name, value] of events) {
  902. this.eventBus.dispatch(name.toLowerCase(), {
  903. source: this,
  904. value
  905. });
  906. }
  907. }
  908. }
  909. }
  910. {
  911. AppOptions._checkDisablePreferences = () => {
  912. if (AppOptions.get("disablePreferences")) {
  913. return true;
  914. }
  915. for (const [name] of userOptions) {
  916. if (compatParams.has(name)) {
  917. continue;
  918. }
  919. console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.');
  920. break;
  921. }
  922. return false;
  923. };
  924. }
  925. ;// CONCATENATED MODULE: ./web/pdf_link_service.js
  926. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  927. const LinkTarget = {
  928. NONE: 0,
  929. SELF: 1,
  930. BLANK: 2,
  931. PARENT: 3,
  932. TOP: 4
  933. };
  934. class PDFLinkService {
  935. externalLinkEnabled = true;
  936. constructor({
  937. eventBus,
  938. externalLinkTarget = null,
  939. externalLinkRel = null,
  940. ignoreDestinationZoom = false
  941. } = {}) {
  942. this.eventBus = eventBus;
  943. this.externalLinkTarget = externalLinkTarget;
  944. this.externalLinkRel = externalLinkRel;
  945. this._ignoreDestinationZoom = ignoreDestinationZoom;
  946. this.baseUrl = null;
  947. this.pdfDocument = null;
  948. this.pdfViewer = null;
  949. this.pdfHistory = null;
  950. }
  951. setDocument(pdfDocument, baseUrl = null) {
  952. this.baseUrl = baseUrl;
  953. this.pdfDocument = pdfDocument;
  954. }
  955. setViewer(pdfViewer) {
  956. this.pdfViewer = pdfViewer;
  957. }
  958. setHistory(pdfHistory) {
  959. this.pdfHistory = pdfHistory;
  960. }
  961. get pagesCount() {
  962. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  963. }
  964. get page() {
  965. return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1;
  966. }
  967. set page(value) {
  968. if (this.pdfDocument) {
  969. this.pdfViewer.currentPageNumber = value;
  970. }
  971. }
  972. get rotation() {
  973. return this.pdfDocument ? this.pdfViewer.pagesRotation : 0;
  974. }
  975. set rotation(value) {
  976. if (this.pdfDocument) {
  977. this.pdfViewer.pagesRotation = value;
  978. }
  979. }
  980. get isInPresentationMode() {
  981. return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false;
  982. }
  983. async goToDestination(dest) {
  984. if (!this.pdfDocument) {
  985. return;
  986. }
  987. let namedDest, explicitDest, pageNumber;
  988. if (typeof dest === "string") {
  989. namedDest = dest;
  990. explicitDest = await this.pdfDocument.getDestination(dest);
  991. } else {
  992. namedDest = null;
  993. explicitDest = await dest;
  994. }
  995. if (!Array.isArray(explicitDest)) {
  996. console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`);
  997. return;
  998. }
  999. const [destRef] = explicitDest;
  1000. if (destRef && typeof destRef === "object") {
  1001. pageNumber = this.pdfDocument.cachedPageNumber(destRef);
  1002. if (!pageNumber) {
  1003. try {
  1004. pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1;
  1005. } catch {
  1006. console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`);
  1007. return;
  1008. }
  1009. }
  1010. } else if (Number.isInteger(destRef)) {
  1011. pageNumber = destRef + 1;
  1012. }
  1013. if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
  1014. console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`);
  1015. return;
  1016. }
  1017. if (this.pdfHistory) {
  1018. this.pdfHistory.pushCurrentPosition();
  1019. this.pdfHistory.push({
  1020. namedDest,
  1021. explicitDest,
  1022. pageNumber
  1023. });
  1024. }
  1025. this.pdfViewer.scrollPageIntoView({
  1026. pageNumber,
  1027. destArray: explicitDest,
  1028. ignoreDestinationZoom: this._ignoreDestinationZoom
  1029. });
  1030. }
  1031. goToPage(val) {
  1032. if (!this.pdfDocument) {
  1033. return;
  1034. }
  1035. const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0;
  1036. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  1037. console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`);
  1038. return;
  1039. }
  1040. if (this.pdfHistory) {
  1041. this.pdfHistory.pushCurrentPosition();
  1042. this.pdfHistory.pushPage(pageNumber);
  1043. }
  1044. this.pdfViewer.scrollPageIntoView({
  1045. pageNumber
  1046. });
  1047. }
  1048. addLinkAttributes(link, url, newWindow = false) {
  1049. if (!url || typeof url !== "string") {
  1050. throw new Error('A valid "url" parameter must provided.');
  1051. }
  1052. const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget,
  1053. rel = this.externalLinkRel;
  1054. if (this.externalLinkEnabled) {
  1055. link.href = link.title = url;
  1056. } else {
  1057. link.href = "";
  1058. link.title = `Disabled: ${url}`;
  1059. link.onclick = () => false;
  1060. }
  1061. let targetStr = "";
  1062. switch (target) {
  1063. case LinkTarget.NONE:
  1064. break;
  1065. case LinkTarget.SELF:
  1066. targetStr = "_self";
  1067. break;
  1068. case LinkTarget.BLANK:
  1069. targetStr = "_blank";
  1070. break;
  1071. case LinkTarget.PARENT:
  1072. targetStr = "_parent";
  1073. break;
  1074. case LinkTarget.TOP:
  1075. targetStr = "_top";
  1076. break;
  1077. }
  1078. link.target = targetStr;
  1079. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  1080. }
  1081. getDestinationHash(dest) {
  1082. if (typeof dest === "string") {
  1083. if (dest.length > 0) {
  1084. return this.getAnchorUrl("#" + escape(dest));
  1085. }
  1086. } else if (Array.isArray(dest)) {
  1087. const str = JSON.stringify(dest);
  1088. if (str.length > 0) {
  1089. return this.getAnchorUrl("#" + escape(str));
  1090. }
  1091. }
  1092. return this.getAnchorUrl("");
  1093. }
  1094. getAnchorUrl(anchor) {
  1095. return this.baseUrl ? this.baseUrl + anchor : anchor;
  1096. }
  1097. setHash(hash) {
  1098. if (!this.pdfDocument) {
  1099. return;
  1100. }
  1101. let pageNumber, dest;
  1102. if (hash.includes("=")) {
  1103. const params = parseQueryString(hash);
  1104. if (params.has("search")) {
  1105. const query = params.get("search").replaceAll('"', ""),
  1106. phrase = params.get("phrase") === "true";
  1107. this.eventBus.dispatch("findfromurlhash", {
  1108. source: this,
  1109. query: phrase ? query : query.match(/\S+/g)
  1110. });
  1111. }
  1112. if (params.has("page")) {
  1113. pageNumber = params.get("page") | 0 || 1;
  1114. }
  1115. if (params.has("zoom")) {
  1116. const zoomArgs = params.get("zoom").split(",");
  1117. const zoomArg = zoomArgs[0];
  1118. const zoomArgNumber = parseFloat(zoomArg);
  1119. if (!zoomArg.includes("Fit")) {
  1120. dest = [null, {
  1121. name: "XYZ"
  1122. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg];
  1123. } else if (zoomArg === "Fit" || zoomArg === "FitB") {
  1124. dest = [null, {
  1125. name: zoomArg
  1126. }];
  1127. } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") {
  1128. dest = [null, {
  1129. name: zoomArg
  1130. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null];
  1131. } else if (zoomArg === "FitR") {
  1132. if (zoomArgs.length !== 5) {
  1133. console.error('PDFLinkService.setHash: Not enough parameters for "FitR".');
  1134. } else {
  1135. dest = [null, {
  1136. name: zoomArg
  1137. }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0];
  1138. }
  1139. } else {
  1140. console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`);
  1141. }
  1142. }
  1143. if (dest) {
  1144. this.pdfViewer.scrollPageIntoView({
  1145. pageNumber: pageNumber || this.page,
  1146. destArray: dest,
  1147. allowNegativeOffset: true
  1148. });
  1149. } else if (pageNumber) {
  1150. this.page = pageNumber;
  1151. }
  1152. if (params.has("pagemode")) {
  1153. this.eventBus.dispatch("pagemode", {
  1154. source: this,
  1155. mode: params.get("pagemode")
  1156. });
  1157. }
  1158. if (params.has("nameddest")) {
  1159. this.goToDestination(params.get("nameddest"));
  1160. }
  1161. return;
  1162. }
  1163. dest = unescape(hash);
  1164. try {
  1165. dest = JSON.parse(dest);
  1166. if (!Array.isArray(dest)) {
  1167. dest = dest.toString();
  1168. }
  1169. } catch {}
  1170. if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) {
  1171. this.goToDestination(dest);
  1172. return;
  1173. }
  1174. console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`);
  1175. }
  1176. executeNamedAction(action) {
  1177. if (!this.pdfDocument) {
  1178. return;
  1179. }
  1180. switch (action) {
  1181. case "GoBack":
  1182. this.pdfHistory?.back();
  1183. break;
  1184. case "GoForward":
  1185. this.pdfHistory?.forward();
  1186. break;
  1187. case "NextPage":
  1188. this.pdfViewer.nextPage();
  1189. break;
  1190. case "PrevPage":
  1191. this.pdfViewer.previousPage();
  1192. break;
  1193. case "LastPage":
  1194. this.page = this.pagesCount;
  1195. break;
  1196. case "FirstPage":
  1197. this.page = 1;
  1198. break;
  1199. default:
  1200. break;
  1201. }
  1202. this.eventBus.dispatch("namedaction", {
  1203. source: this,
  1204. action
  1205. });
  1206. }
  1207. async executeSetOCGState(action) {
  1208. if (!this.pdfDocument) {
  1209. return;
  1210. }
  1211. const pdfDocument = this.pdfDocument,
  1212. optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;
  1213. if (pdfDocument !== this.pdfDocument) {
  1214. return;
  1215. }
  1216. optionalContentConfig.setOCGState(action);
  1217. this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig);
  1218. }
  1219. static #isValidExplicitDest(dest) {
  1220. if (!Array.isArray(dest) || dest.length < 2) {
  1221. return false;
  1222. }
  1223. const [page, zoom, ...args] = dest;
  1224. if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) {
  1225. return false;
  1226. }
  1227. if (!(typeof zoom === "object" && typeof zoom?.name === "string")) {
  1228. return false;
  1229. }
  1230. const argsLen = args.length;
  1231. let allowNull = true;
  1232. switch (zoom.name) {
  1233. case "XYZ":
  1234. if (argsLen < 2 || argsLen > 3) {
  1235. return false;
  1236. }
  1237. break;
  1238. case "Fit":
  1239. case "FitB":
  1240. return argsLen === 0;
  1241. case "FitH":
  1242. case "FitBH":
  1243. case "FitV":
  1244. case "FitBV":
  1245. if (argsLen > 1) {
  1246. return false;
  1247. }
  1248. break;
  1249. case "FitR":
  1250. if (argsLen !== 4) {
  1251. return false;
  1252. }
  1253. allowNull = false;
  1254. break;
  1255. default:
  1256. return false;
  1257. }
  1258. for (const arg of args) {
  1259. if (!(typeof arg === "number" || allowNull && arg === null)) {
  1260. return false;
  1261. }
  1262. }
  1263. return true;
  1264. }
  1265. }
  1266. class SimpleLinkService extends PDFLinkService {
  1267. setDocument(pdfDocument, baseUrl = null) {}
  1268. }
  1269. ;// CONCATENATED MODULE: ./web/pdfjs.js
  1270. const {
  1271. AbortException,
  1272. AnnotationEditorLayer,
  1273. AnnotationEditorParamsType,
  1274. AnnotationEditorType,
  1275. AnnotationEditorUIManager,
  1276. AnnotationLayer,
  1277. AnnotationMode,
  1278. build,
  1279. CMapCompressionType,
  1280. ColorPicker,
  1281. createValidAbsoluteUrl,
  1282. DOMSVGFactory,
  1283. DrawLayer,
  1284. FeatureTest,
  1285. fetchData,
  1286. getDocument,
  1287. getFilenameFromUrl,
  1288. getPdfFilenameFromUrl: pdfjs_getPdfFilenameFromUrl,
  1289. getXfaPageViewport,
  1290. GlobalWorkerOptions,
  1291. ImageKind,
  1292. InvalidPDFException,
  1293. isDataScheme,
  1294. isPdfFile,
  1295. MissingPDFException,
  1296. noContextMenu,
  1297. normalizeUnicode,
  1298. OPS,
  1299. PasswordResponses,
  1300. PDFDataRangeTransport,
  1301. PDFDateString,
  1302. PDFWorker,
  1303. PermissionFlag,
  1304. PixelsPerInch,
  1305. RenderingCancelledException,
  1306. setLayerDimensions,
  1307. shadow,
  1308. TextLayer,
  1309. UnexpectedResponseException,
  1310. Util,
  1311. VerbosityLevel,
  1312. version,
  1313. XfaLayer
  1314. } = globalThis.pdfjsLib;
  1315. ;// CONCATENATED MODULE: ./web/event_utils.js
  1316. const WaitOnType = {
  1317. EVENT: "event",
  1318. TIMEOUT: "timeout"
  1319. };
  1320. async function waitOnEventOrTimeout({
  1321. target,
  1322. name,
  1323. delay = 0
  1324. }) {
  1325. if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) {
  1326. throw new Error("waitOnEventOrTimeout - invalid parameters.");
  1327. }
  1328. const {
  1329. promise,
  1330. resolve
  1331. } = Promise.withResolvers();
  1332. const ac = new AbortController();
  1333. function handler(type) {
  1334. ac.abort();
  1335. clearTimeout(timeout);
  1336. resolve(type);
  1337. }
  1338. const evtMethod = target instanceof EventBus ? "_on" : "addEventListener";
  1339. target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), {
  1340. signal: ac.signal
  1341. });
  1342. const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay);
  1343. return promise;
  1344. }
  1345. class EventBus {
  1346. #listeners = Object.create(null);
  1347. on(eventName, listener, options = null) {
  1348. this._on(eventName, listener, {
  1349. external: true,
  1350. once: options?.once,
  1351. signal: options?.signal
  1352. });
  1353. }
  1354. off(eventName, listener, options = null) {
  1355. this._off(eventName, listener);
  1356. }
  1357. dispatch(eventName, data) {
  1358. const eventListeners = this.#listeners[eventName];
  1359. if (!eventListeners || eventListeners.length === 0) {
  1360. return;
  1361. }
  1362. let externalListeners;
  1363. for (const {
  1364. listener,
  1365. external,
  1366. once
  1367. } of eventListeners.slice(0)) {
  1368. if (once) {
  1369. this._off(eventName, listener);
  1370. }
  1371. if (external) {
  1372. (externalListeners ||= []).push(listener);
  1373. continue;
  1374. }
  1375. listener(data);
  1376. }
  1377. if (externalListeners) {
  1378. for (const listener of externalListeners) {
  1379. listener(data);
  1380. }
  1381. externalListeners = null;
  1382. }
  1383. }
  1384. _on(eventName, listener, options = null) {
  1385. let rmAbort = null;
  1386. if (options?.signal instanceof AbortSignal) {
  1387. const {
  1388. signal
  1389. } = options;
  1390. if (signal.aborted) {
  1391. console.error("Cannot use an `aborted` signal.");
  1392. return;
  1393. }
  1394. const onAbort = () => this._off(eventName, listener);
  1395. rmAbort = () => signal.removeEventListener("abort", onAbort);
  1396. signal.addEventListener("abort", onAbort);
  1397. }
  1398. const eventListeners = this.#listeners[eventName] ||= [];
  1399. eventListeners.push({
  1400. listener,
  1401. external: options?.external === true,
  1402. once: options?.once === true,
  1403. rmAbort
  1404. });
  1405. }
  1406. _off(eventName, listener, options = null) {
  1407. const eventListeners = this.#listeners[eventName];
  1408. if (!eventListeners) {
  1409. return;
  1410. }
  1411. for (let i = 0, ii = eventListeners.length; i < ii; i++) {
  1412. const evt = eventListeners[i];
  1413. if (evt.listener === listener) {
  1414. evt.rmAbort?.();
  1415. eventListeners.splice(i, 1);
  1416. return;
  1417. }
  1418. }
  1419. }
  1420. }
  1421. class FirefoxEventBus extends EventBus {
  1422. #externalServices;
  1423. #globalEventNames;
  1424. #isInAutomation;
  1425. constructor(globalEventNames, externalServices, isInAutomation) {
  1426. super();
  1427. this.#globalEventNames = globalEventNames;
  1428. this.#externalServices = externalServices;
  1429. this.#isInAutomation = isInAutomation;
  1430. }
  1431. dispatch(eventName, data) {
  1432. throw new Error("Not implemented: FirefoxEventBus.dispatch");
  1433. }
  1434. }
  1435. ;// CONCATENATED MODULE: ./web/external_services.js
  1436. class BaseExternalServices {
  1437. constructor() {
  1438. if (this.constructor === BaseExternalServices) {
  1439. throw new Error("Cannot initialize BaseExternalServices.");
  1440. }
  1441. }
  1442. updateFindControlState(data) {}
  1443. updateFindMatchesCount(data) {}
  1444. initPassiveLoading() {}
  1445. reportTelemetry(data) {}
  1446. async createL10n() {
  1447. throw new Error("Not implemented: createL10n");
  1448. }
  1449. createScripting() {
  1450. throw new Error("Not implemented: createScripting");
  1451. }
  1452. updateEditorStates(data) {
  1453. throw new Error("Not implemented: updateEditorStates");
  1454. }
  1455. dispatchGlobalEvent(_event) {}
  1456. }
  1457. ;// CONCATENATED MODULE: ./web/preferences.js
  1458. class BasePreferences {
  1459. #defaults = Object.freeze({
  1460. altTextLearnMoreUrl: "",
  1461. annotationEditorMode: 0,
  1462. annotationMode: 2,
  1463. cursorToolOnLoad: 0,
  1464. defaultZoomDelay: 400,
  1465. defaultZoomValue: "",
  1466. disablePageLabels: false,
  1467. enableAltText: false,
  1468. enableGuessAltText: true,
  1469. enableHighlightEditor: false,
  1470. enableHighlightFloatingButton: false,
  1471. enablePermissions: false,
  1472. enablePrintAutoRotate: true,
  1473. enableScripting: true,
  1474. enableUpdatedAddImage: false,
  1475. externalLinkTarget: 0,
  1476. highlightEditorColors: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F",
  1477. historyUpdateUrl: false,
  1478. ignoreDestinationZoom: false,
  1479. forcePageColors: false,
  1480. pageColorsBackground: "Canvas",
  1481. pageColorsForeground: "CanvasText",
  1482. pdfBugEnabled: false,
  1483. sidebarViewOnLoad: -1,
  1484. scrollModeOnLoad: -1,
  1485. spreadModeOnLoad: -1,
  1486. textLayerMode: 1,
  1487. viewOnLoad: 0,
  1488. disableAutoFetch: false,
  1489. disableFontFace: false,
  1490. disableRange: false,
  1491. disableStream: false,
  1492. enableHWA: true,
  1493. enableXfa: true,
  1494. viewerCssTheme: 1
  1495. });
  1496. #initializedPromise = null;
  1497. constructor() {
  1498. if (this.constructor === BasePreferences) {
  1499. throw new Error("Cannot initialize BasePreferences.");
  1500. }
  1501. this.#initializedPromise = this._readFromStorage(this.#defaults).then(({
  1502. browserPrefs,
  1503. prefs
  1504. }) => {
  1505. if (AppOptions._checkDisablePreferences()) {
  1506. return;
  1507. }
  1508. AppOptions.setAll({
  1509. ...browserPrefs,
  1510. ...prefs
  1511. }, true);
  1512. });
  1513. }
  1514. async _writeToStorage(prefObj) {
  1515. throw new Error("Not implemented: _writeToStorage");
  1516. }
  1517. async _readFromStorage(prefObj) {
  1518. throw new Error("Not implemented: _readFromStorage");
  1519. }
  1520. async reset() {
  1521. await this.#initializedPromise;
  1522. AppOptions.setAll(this.#defaults, true);
  1523. await this._writeToStorage(this.#defaults);
  1524. }
  1525. async set(name, value) {
  1526. await this.#initializedPromise;
  1527. AppOptions.setAll({
  1528. [name]: value
  1529. }, true);
  1530. await this._writeToStorage(AppOptions.getAll(OptionKind.PREFERENCE));
  1531. }
  1532. async get(name) {
  1533. await this.#initializedPromise;
  1534. return AppOptions.get(name);
  1535. }
  1536. get initializedPromise() {
  1537. return this.#initializedPromise;
  1538. }
  1539. }
  1540. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/types.js
  1541. class FluentType {
  1542. constructor(value) {
  1543. this.value = value;
  1544. }
  1545. valueOf() {
  1546. return this.value;
  1547. }
  1548. }
  1549. class FluentNone extends FluentType {
  1550. constructor(value = "???") {
  1551. super(value);
  1552. }
  1553. toString(scope) {
  1554. return `{${this.value}}`;
  1555. }
  1556. }
  1557. class FluentNumber extends FluentType {
  1558. constructor(value, opts = {}) {
  1559. super(value);
  1560. this.opts = opts;
  1561. }
  1562. toString(scope) {
  1563. try {
  1564. const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts);
  1565. return nf.format(this.value);
  1566. } catch (err) {
  1567. scope.reportError(err);
  1568. return this.value.toString(10);
  1569. }
  1570. }
  1571. }
  1572. class FluentDateTime extends FluentType {
  1573. constructor(value, opts = {}) {
  1574. super(value);
  1575. this.opts = opts;
  1576. }
  1577. toString(scope) {
  1578. try {
  1579. const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts);
  1580. return dtf.format(this.value);
  1581. } catch (err) {
  1582. scope.reportError(err);
  1583. return new Date(this.value).toISOString();
  1584. }
  1585. }
  1586. }
  1587. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/resolver.js
  1588. const MAX_PLACEABLES = 100;
  1589. const FSI = "\u2068";
  1590. const PDI = "\u2069";
  1591. function match(scope, selector, key) {
  1592. if (key === selector) {
  1593. return true;
  1594. }
  1595. if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) {
  1596. return true;
  1597. }
  1598. if (selector instanceof FluentNumber && typeof key === "string") {
  1599. let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value);
  1600. if (key === category) {
  1601. return true;
  1602. }
  1603. }
  1604. return false;
  1605. }
  1606. function getDefault(scope, variants, star) {
  1607. if (variants[star]) {
  1608. return resolvePattern(scope, variants[star].value);
  1609. }
  1610. scope.reportError(new RangeError("No default"));
  1611. return new FluentNone();
  1612. }
  1613. function getArguments(scope, args) {
  1614. const positional = [];
  1615. const named = Object.create(null);
  1616. for (const arg of args) {
  1617. if (arg.type === "narg") {
  1618. named[arg.name] = resolveExpression(scope, arg.value);
  1619. } else {
  1620. positional.push(resolveExpression(scope, arg));
  1621. }
  1622. }
  1623. return {
  1624. positional,
  1625. named
  1626. };
  1627. }
  1628. function resolveExpression(scope, expr) {
  1629. switch (expr.type) {
  1630. case "str":
  1631. return expr.value;
  1632. case "num":
  1633. return new FluentNumber(expr.value, {
  1634. minimumFractionDigits: expr.precision
  1635. });
  1636. case "var":
  1637. return resolveVariableReference(scope, expr);
  1638. case "mesg":
  1639. return resolveMessageReference(scope, expr);
  1640. case "term":
  1641. return resolveTermReference(scope, expr);
  1642. case "func":
  1643. return resolveFunctionReference(scope, expr);
  1644. case "select":
  1645. return resolveSelectExpression(scope, expr);
  1646. default:
  1647. return new FluentNone();
  1648. }
  1649. }
  1650. function resolveVariableReference(scope, {
  1651. name
  1652. }) {
  1653. let arg;
  1654. if (scope.params) {
  1655. if (Object.prototype.hasOwnProperty.call(scope.params, name)) {
  1656. arg = scope.params[name];
  1657. } else {
  1658. return new FluentNone(`$${name}`);
  1659. }
  1660. } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) {
  1661. arg = scope.args[name];
  1662. } else {
  1663. scope.reportError(new ReferenceError(`Unknown variable: $${name}`));
  1664. return new FluentNone(`$${name}`);
  1665. }
  1666. if (arg instanceof FluentType) {
  1667. return arg;
  1668. }
  1669. switch (typeof arg) {
  1670. case "string":
  1671. return arg;
  1672. case "number":
  1673. return new FluentNumber(arg);
  1674. case "object":
  1675. if (arg instanceof Date) {
  1676. return new FluentDateTime(arg.getTime());
  1677. }
  1678. default:
  1679. scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`));
  1680. return new FluentNone(`$${name}`);
  1681. }
  1682. }
  1683. function resolveMessageReference(scope, {
  1684. name,
  1685. attr
  1686. }) {
  1687. const message = scope.bundle._messages.get(name);
  1688. if (!message) {
  1689. scope.reportError(new ReferenceError(`Unknown message: ${name}`));
  1690. return new FluentNone(name);
  1691. }
  1692. if (attr) {
  1693. const attribute = message.attributes[attr];
  1694. if (attribute) {
  1695. return resolvePattern(scope, attribute);
  1696. }
  1697. scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
  1698. return new FluentNone(`${name}.${attr}`);
  1699. }
  1700. if (message.value) {
  1701. return resolvePattern(scope, message.value);
  1702. }
  1703. scope.reportError(new ReferenceError(`No value: ${name}`));
  1704. return new FluentNone(name);
  1705. }
  1706. function resolveTermReference(scope, {
  1707. name,
  1708. attr,
  1709. args
  1710. }) {
  1711. const id = `-${name}`;
  1712. const term = scope.bundle._terms.get(id);
  1713. if (!term) {
  1714. scope.reportError(new ReferenceError(`Unknown term: ${id}`));
  1715. return new FluentNone(id);
  1716. }
  1717. if (attr) {
  1718. const attribute = term.attributes[attr];
  1719. if (attribute) {
  1720. scope.params = getArguments(scope, args).named;
  1721. const resolved = resolvePattern(scope, attribute);
  1722. scope.params = null;
  1723. return resolved;
  1724. }
  1725. scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
  1726. return new FluentNone(`${id}.${attr}`);
  1727. }
  1728. scope.params = getArguments(scope, args).named;
  1729. const resolved = resolvePattern(scope, term.value);
  1730. scope.params = null;
  1731. return resolved;
  1732. }
  1733. function resolveFunctionReference(scope, {
  1734. name,
  1735. args
  1736. }) {
  1737. let func = scope.bundle._functions[name];
  1738. if (!func) {
  1739. scope.reportError(new ReferenceError(`Unknown function: ${name}()`));
  1740. return new FluentNone(`${name}()`);
  1741. }
  1742. if (typeof func !== "function") {
  1743. scope.reportError(new TypeError(`Function ${name}() is not callable`));
  1744. return new FluentNone(`${name}()`);
  1745. }
  1746. try {
  1747. let resolved = getArguments(scope, args);
  1748. return func(resolved.positional, resolved.named);
  1749. } catch (err) {
  1750. scope.reportError(err);
  1751. return new FluentNone(`${name}()`);
  1752. }
  1753. }
  1754. function resolveSelectExpression(scope, {
  1755. selector,
  1756. variants,
  1757. star
  1758. }) {
  1759. let sel = resolveExpression(scope, selector);
  1760. if (sel instanceof FluentNone) {
  1761. return getDefault(scope, variants, star);
  1762. }
  1763. for (const variant of variants) {
  1764. const key = resolveExpression(scope, variant.key);
  1765. if (match(scope, sel, key)) {
  1766. return resolvePattern(scope, variant.value);
  1767. }
  1768. }
  1769. return getDefault(scope, variants, star);
  1770. }
  1771. function resolveComplexPattern(scope, ptn) {
  1772. if (scope.dirty.has(ptn)) {
  1773. scope.reportError(new RangeError("Cyclic reference"));
  1774. return new FluentNone();
  1775. }
  1776. scope.dirty.add(ptn);
  1777. const result = [];
  1778. const useIsolating = scope.bundle._useIsolating && ptn.length > 1;
  1779. for (const elem of ptn) {
  1780. if (typeof elem === "string") {
  1781. result.push(scope.bundle._transform(elem));
  1782. continue;
  1783. }
  1784. scope.placeables++;
  1785. if (scope.placeables > MAX_PLACEABLES) {
  1786. scope.dirty.delete(ptn);
  1787. throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`);
  1788. }
  1789. if (useIsolating) {
  1790. result.push(FSI);
  1791. }
  1792. result.push(resolveExpression(scope, elem).toString(scope));
  1793. if (useIsolating) {
  1794. result.push(PDI);
  1795. }
  1796. }
  1797. scope.dirty.delete(ptn);
  1798. return result.join("");
  1799. }
  1800. function resolvePattern(scope, value) {
  1801. if (typeof value === "string") {
  1802. return scope.bundle._transform(value);
  1803. }
  1804. return resolveComplexPattern(scope, value);
  1805. }
  1806. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/scope.js
  1807. class Scope {
  1808. constructor(bundle, errors, args) {
  1809. this.dirty = new WeakSet();
  1810. this.params = null;
  1811. this.placeables = 0;
  1812. this.bundle = bundle;
  1813. this.errors = errors;
  1814. this.args = args;
  1815. }
  1816. reportError(error) {
  1817. if (!this.errors || !(error instanceof Error)) {
  1818. throw error;
  1819. }
  1820. this.errors.push(error);
  1821. }
  1822. memoizeIntlObject(ctor, opts) {
  1823. let cache = this.bundle._intls.get(ctor);
  1824. if (!cache) {
  1825. cache = {};
  1826. this.bundle._intls.set(ctor, cache);
  1827. }
  1828. let id = JSON.stringify(opts);
  1829. if (!cache[id]) {
  1830. cache[id] = new ctor(this.bundle.locales, opts);
  1831. }
  1832. return cache[id];
  1833. }
  1834. }
  1835. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/builtins.js
  1836. function values(opts, allowed) {
  1837. const unwrapped = Object.create(null);
  1838. for (const [name, opt] of Object.entries(opts)) {
  1839. if (allowed.includes(name)) {
  1840. unwrapped[name] = opt.valueOf();
  1841. }
  1842. }
  1843. return unwrapped;
  1844. }
  1845. const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"];
  1846. function NUMBER(args, opts) {
  1847. let arg = args[0];
  1848. if (arg instanceof FluentNone) {
  1849. return new FluentNone(`NUMBER(${arg.valueOf()})`);
  1850. }
  1851. if (arg instanceof FluentNumber) {
  1852. return new FluentNumber(arg.valueOf(), {
  1853. ...arg.opts,
  1854. ...values(opts, NUMBER_ALLOWED)
  1855. });
  1856. }
  1857. if (arg instanceof FluentDateTime) {
  1858. return new FluentNumber(arg.valueOf(), {
  1859. ...values(opts, NUMBER_ALLOWED)
  1860. });
  1861. }
  1862. throw new TypeError("Invalid argument to NUMBER");
  1863. }
  1864. const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"];
  1865. function DATETIME(args, opts) {
  1866. let arg = args[0];
  1867. if (arg instanceof FluentNone) {
  1868. return new FluentNone(`DATETIME(${arg.valueOf()})`);
  1869. }
  1870. if (arg instanceof FluentDateTime) {
  1871. return new FluentDateTime(arg.valueOf(), {
  1872. ...arg.opts,
  1873. ...values(opts, DATETIME_ALLOWED)
  1874. });
  1875. }
  1876. if (arg instanceof FluentNumber) {
  1877. return new FluentDateTime(arg.valueOf(), {
  1878. ...values(opts, DATETIME_ALLOWED)
  1879. });
  1880. }
  1881. throw new TypeError("Invalid argument to DATETIME");
  1882. }
  1883. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/memoizer.js
  1884. const cache = new Map();
  1885. function getMemoizerForLocale(locales) {
  1886. const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales;
  1887. let memoizer = cache.get(stringLocale);
  1888. if (memoizer === undefined) {
  1889. memoizer = new Map();
  1890. cache.set(stringLocale, memoizer);
  1891. }
  1892. return memoizer;
  1893. }
  1894. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/bundle.js
  1895. class FluentBundle {
  1896. constructor(locales, {
  1897. functions,
  1898. useIsolating = true,
  1899. transform = v => v
  1900. } = {}) {
  1901. this._terms = new Map();
  1902. this._messages = new Map();
  1903. this.locales = Array.isArray(locales) ? locales : [locales];
  1904. this._functions = {
  1905. NUMBER: NUMBER,
  1906. DATETIME: DATETIME,
  1907. ...functions
  1908. };
  1909. this._useIsolating = useIsolating;
  1910. this._transform = transform;
  1911. this._intls = getMemoizerForLocale(locales);
  1912. }
  1913. hasMessage(id) {
  1914. return this._messages.has(id);
  1915. }
  1916. getMessage(id) {
  1917. return this._messages.get(id);
  1918. }
  1919. addResource(res, {
  1920. allowOverrides = false
  1921. } = {}) {
  1922. const errors = [];
  1923. for (let i = 0; i < res.body.length; i++) {
  1924. let entry = res.body[i];
  1925. if (entry.id.startsWith("-")) {
  1926. if (allowOverrides === false && this._terms.has(entry.id)) {
  1927. errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`));
  1928. continue;
  1929. }
  1930. this._terms.set(entry.id, entry);
  1931. } else {
  1932. if (allowOverrides === false && this._messages.has(entry.id)) {
  1933. errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`));
  1934. continue;
  1935. }
  1936. this._messages.set(entry.id, entry);
  1937. }
  1938. }
  1939. return errors;
  1940. }
  1941. formatPattern(pattern, args = null, errors = null) {
  1942. if (typeof pattern === "string") {
  1943. return this._transform(pattern);
  1944. }
  1945. let scope = new Scope(this, errors, args);
  1946. try {
  1947. let value = resolveComplexPattern(scope, pattern);
  1948. return value.toString(scope);
  1949. } catch (err) {
  1950. if (scope.errors && err instanceof Error) {
  1951. scope.errors.push(err);
  1952. return new FluentNone().toString(scope);
  1953. }
  1954. throw err;
  1955. }
  1956. }
  1957. }
  1958. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/resource.js
  1959. const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm;
  1960. const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y;
  1961. const RE_VARIANT_START = /\*?\[/y;
  1962. const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y;
  1963. const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y;
  1964. const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y;
  1965. const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/;
  1966. const RE_TEXT_RUN = /([^{}\n\r]+)/y;
  1967. const RE_STRING_RUN = /([^\\"\n\r]*)/y;
  1968. const RE_STRING_ESCAPE = /\\([\\"])/y;
  1969. const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y;
  1970. const RE_LEADING_NEWLINES = /^\n+/;
  1971. const RE_TRAILING_SPACES = / +$/;
  1972. const RE_BLANK_LINES = / *\r?\n/g;
  1973. const RE_INDENT = /( *)$/;
  1974. const TOKEN_BRACE_OPEN = /{\s*/y;
  1975. const TOKEN_BRACE_CLOSE = /\s*}/y;
  1976. const TOKEN_BRACKET_OPEN = /\[\s*/y;
  1977. const TOKEN_BRACKET_CLOSE = /\s*] */y;
  1978. const TOKEN_PAREN_OPEN = /\s*\(\s*/y;
  1979. const TOKEN_ARROW = /\s*->\s*/y;
  1980. const TOKEN_COLON = /\s*:\s*/y;
  1981. const TOKEN_COMMA = /\s*,?\s*/y;
  1982. const TOKEN_BLANK = /\s+/y;
  1983. class FluentResource {
  1984. constructor(source) {
  1985. this.body = [];
  1986. RE_MESSAGE_START.lastIndex = 0;
  1987. let cursor = 0;
  1988. while (true) {
  1989. let next = RE_MESSAGE_START.exec(source);
  1990. if (next === null) {
  1991. break;
  1992. }
  1993. cursor = RE_MESSAGE_START.lastIndex;
  1994. try {
  1995. this.body.push(parseMessage(next[1]));
  1996. } catch (err) {
  1997. if (err instanceof SyntaxError) {
  1998. continue;
  1999. }
  2000. throw err;
  2001. }
  2002. }
  2003. function test(re) {
  2004. re.lastIndex = cursor;
  2005. return re.test(source);
  2006. }
  2007. function consumeChar(char, errorClass) {
  2008. if (source[cursor] === char) {
  2009. cursor++;
  2010. return true;
  2011. }
  2012. if (errorClass) {
  2013. throw new errorClass(`Expected ${char}`);
  2014. }
  2015. return false;
  2016. }
  2017. function consumeToken(re, errorClass) {
  2018. if (test(re)) {
  2019. cursor = re.lastIndex;
  2020. return true;
  2021. }
  2022. if (errorClass) {
  2023. throw new errorClass(`Expected ${re.toString()}`);
  2024. }
  2025. return false;
  2026. }
  2027. function match(re) {
  2028. re.lastIndex = cursor;
  2029. let result = re.exec(source);
  2030. if (result === null) {
  2031. throw new SyntaxError(`Expected ${re.toString()}`);
  2032. }
  2033. cursor = re.lastIndex;
  2034. return result;
  2035. }
  2036. function match1(re) {
  2037. return match(re)[1];
  2038. }
  2039. function parseMessage(id) {
  2040. let value = parsePattern();
  2041. let attributes = parseAttributes();
  2042. if (value === null && Object.keys(attributes).length === 0) {
  2043. throw new SyntaxError("Expected message value or attributes");
  2044. }
  2045. return {
  2046. id,
  2047. value,
  2048. attributes
  2049. };
  2050. }
  2051. function parseAttributes() {
  2052. let attrs = Object.create(null);
  2053. while (test(RE_ATTRIBUTE_START)) {
  2054. let name = match1(RE_ATTRIBUTE_START);
  2055. let value = parsePattern();
  2056. if (value === null) {
  2057. throw new SyntaxError("Expected attribute value");
  2058. }
  2059. attrs[name] = value;
  2060. }
  2061. return attrs;
  2062. }
  2063. function parsePattern() {
  2064. let first;
  2065. if (test(RE_TEXT_RUN)) {
  2066. first = match1(RE_TEXT_RUN);
  2067. }
  2068. if (source[cursor] === "{" || source[cursor] === "}") {
  2069. return parsePatternElements(first ? [first] : [], Infinity);
  2070. }
  2071. let indent = parseIndent();
  2072. if (indent) {
  2073. if (first) {
  2074. return parsePatternElements([first, indent], indent.length);
  2075. }
  2076. indent.value = trim(indent.value, RE_LEADING_NEWLINES);
  2077. return parsePatternElements([indent], indent.length);
  2078. }
  2079. if (first) {
  2080. return trim(first, RE_TRAILING_SPACES);
  2081. }
  2082. return null;
  2083. }
  2084. function parsePatternElements(elements = [], commonIndent) {
  2085. while (true) {
  2086. if (test(RE_TEXT_RUN)) {
  2087. elements.push(match1(RE_TEXT_RUN));
  2088. continue;
  2089. }
  2090. if (source[cursor] === "{") {
  2091. elements.push(parsePlaceable());
  2092. continue;
  2093. }
  2094. if (source[cursor] === "}") {
  2095. throw new SyntaxError("Unbalanced closing brace");
  2096. }
  2097. let indent = parseIndent();
  2098. if (indent) {
  2099. elements.push(indent);
  2100. commonIndent = Math.min(commonIndent, indent.length);
  2101. continue;
  2102. }
  2103. break;
  2104. }
  2105. let lastIndex = elements.length - 1;
  2106. let lastElement = elements[lastIndex];
  2107. if (typeof lastElement === "string") {
  2108. elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES);
  2109. }
  2110. let baked = [];
  2111. for (let element of elements) {
  2112. if (element instanceof Indent) {
  2113. element = element.value.slice(0, element.value.length - commonIndent);
  2114. }
  2115. if (element) {
  2116. baked.push(element);
  2117. }
  2118. }
  2119. return baked;
  2120. }
  2121. function parsePlaceable() {
  2122. consumeToken(TOKEN_BRACE_OPEN, SyntaxError);
  2123. let selector = parseInlineExpression();
  2124. if (consumeToken(TOKEN_BRACE_CLOSE)) {
  2125. return selector;
  2126. }
  2127. if (consumeToken(TOKEN_ARROW)) {
  2128. let variants = parseVariants();
  2129. consumeToken(TOKEN_BRACE_CLOSE, SyntaxError);
  2130. return {
  2131. type: "select",
  2132. selector,
  2133. ...variants
  2134. };
  2135. }
  2136. throw new SyntaxError("Unclosed placeable");
  2137. }
  2138. function parseInlineExpression() {
  2139. if (source[cursor] === "{") {
  2140. return parsePlaceable();
  2141. }
  2142. if (test(RE_REFERENCE)) {
  2143. let [, sigil, name, attr = null] = match(RE_REFERENCE);
  2144. if (sigil === "$") {
  2145. return {
  2146. type: "var",
  2147. name
  2148. };
  2149. }
  2150. if (consumeToken(TOKEN_PAREN_OPEN)) {
  2151. let args = parseArguments();
  2152. if (sigil === "-") {
  2153. return {
  2154. type: "term",
  2155. name,
  2156. attr,
  2157. args
  2158. };
  2159. }
  2160. if (RE_FUNCTION_NAME.test(name)) {
  2161. return {
  2162. type: "func",
  2163. name,
  2164. args
  2165. };
  2166. }
  2167. throw new SyntaxError("Function names must be all upper-case");
  2168. }
  2169. if (sigil === "-") {
  2170. return {
  2171. type: "term",
  2172. name,
  2173. attr,
  2174. args: []
  2175. };
  2176. }
  2177. return {
  2178. type: "mesg",
  2179. name,
  2180. attr
  2181. };
  2182. }
  2183. return parseLiteral();
  2184. }
  2185. function parseArguments() {
  2186. let args = [];
  2187. while (true) {
  2188. switch (source[cursor]) {
  2189. case ")":
  2190. cursor++;
  2191. return args;
  2192. case undefined:
  2193. throw new SyntaxError("Unclosed argument list");
  2194. }
  2195. args.push(parseArgument());
  2196. consumeToken(TOKEN_COMMA);
  2197. }
  2198. }
  2199. function parseArgument() {
  2200. let expr = parseInlineExpression();
  2201. if (expr.type !== "mesg") {
  2202. return expr;
  2203. }
  2204. if (consumeToken(TOKEN_COLON)) {
  2205. return {
  2206. type: "narg",
  2207. name: expr.name,
  2208. value: parseLiteral()
  2209. };
  2210. }
  2211. return expr;
  2212. }
  2213. function parseVariants() {
  2214. let variants = [];
  2215. let count = 0;
  2216. let star;
  2217. while (test(RE_VARIANT_START)) {
  2218. if (consumeChar("*")) {
  2219. star = count;
  2220. }
  2221. let key = parseVariantKey();
  2222. let value = parsePattern();
  2223. if (value === null) {
  2224. throw new SyntaxError("Expected variant value");
  2225. }
  2226. variants[count++] = {
  2227. key,
  2228. value
  2229. };
  2230. }
  2231. if (count === 0) {
  2232. return null;
  2233. }
  2234. if (star === undefined) {
  2235. throw new SyntaxError("Expected default variant");
  2236. }
  2237. return {
  2238. variants,
  2239. star
  2240. };
  2241. }
  2242. function parseVariantKey() {
  2243. consumeToken(TOKEN_BRACKET_OPEN, SyntaxError);
  2244. let key;
  2245. if (test(RE_NUMBER_LITERAL)) {
  2246. key = parseNumberLiteral();
  2247. } else {
  2248. key = {
  2249. type: "str",
  2250. value: match1(RE_IDENTIFIER)
  2251. };
  2252. }
  2253. consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError);
  2254. return key;
  2255. }
  2256. function parseLiteral() {
  2257. if (test(RE_NUMBER_LITERAL)) {
  2258. return parseNumberLiteral();
  2259. }
  2260. if (source[cursor] === '"') {
  2261. return parseStringLiteral();
  2262. }
  2263. throw new SyntaxError("Invalid expression");
  2264. }
  2265. function parseNumberLiteral() {
  2266. let [, value, fraction = ""] = match(RE_NUMBER_LITERAL);
  2267. let precision = fraction.length;
  2268. return {
  2269. type: "num",
  2270. value: parseFloat(value),
  2271. precision
  2272. };
  2273. }
  2274. function parseStringLiteral() {
  2275. consumeChar('"', SyntaxError);
  2276. let value = "";
  2277. while (true) {
  2278. value += match1(RE_STRING_RUN);
  2279. if (source[cursor] === "\\") {
  2280. value += parseEscapeSequence();
  2281. continue;
  2282. }
  2283. if (consumeChar('"')) {
  2284. return {
  2285. type: "str",
  2286. value
  2287. };
  2288. }
  2289. throw new SyntaxError("Unclosed string literal");
  2290. }
  2291. }
  2292. function parseEscapeSequence() {
  2293. if (test(RE_STRING_ESCAPE)) {
  2294. return match1(RE_STRING_ESCAPE);
  2295. }
  2296. if (test(RE_UNICODE_ESCAPE)) {
  2297. let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE);
  2298. let codepoint = parseInt(codepoint4 || codepoint6, 16);
  2299. return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�";
  2300. }
  2301. throw new SyntaxError("Unknown escape sequence");
  2302. }
  2303. function parseIndent() {
  2304. let start = cursor;
  2305. consumeToken(TOKEN_BLANK);
  2306. switch (source[cursor]) {
  2307. case ".":
  2308. case "[":
  2309. case "*":
  2310. case "}":
  2311. case undefined:
  2312. return false;
  2313. case "{":
  2314. return makeIndent(source.slice(start, cursor));
  2315. }
  2316. if (source[cursor - 1] === " ") {
  2317. return makeIndent(source.slice(start, cursor));
  2318. }
  2319. return false;
  2320. }
  2321. function trim(text, re) {
  2322. return text.replace(re, "");
  2323. }
  2324. function makeIndent(blank) {
  2325. let value = blank.replace(RE_BLANK_LINES, "\n");
  2326. let length = RE_INDENT.exec(blank)[1].length;
  2327. return new Indent(value, length);
  2328. }
  2329. }
  2330. }
  2331. class Indent {
  2332. constructor(value, length) {
  2333. this.value = value;
  2334. this.length = length;
  2335. }
  2336. }
  2337. ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/index.js
  2338. ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/overlay.js
  2339. const reOverlay = /<|&#?\w+;/;
  2340. const TEXT_LEVEL_ELEMENTS = {
  2341. "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"]
  2342. };
  2343. const LOCALIZABLE_ATTRIBUTES = {
  2344. "http://www.w3.org/1999/xhtml": {
  2345. global: ["title", "aria-label", "aria-valuetext"],
  2346. a: ["download"],
  2347. area: ["download", "alt"],
  2348. input: ["alt", "placeholder"],
  2349. menuitem: ["label"],
  2350. menu: ["label"],
  2351. optgroup: ["label"],
  2352. option: ["label"],
  2353. track: ["label"],
  2354. img: ["alt"],
  2355. textarea: ["placeholder"],
  2356. th: ["abbr"]
  2357. },
  2358. "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": {
  2359. global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"],
  2360. description: ["value"],
  2361. key: ["key", "keycode"],
  2362. label: ["value"],
  2363. textbox: ["placeholder", "value"]
  2364. }
  2365. };
  2366. function translateElement(element, translation) {
  2367. const {
  2368. value
  2369. } = translation;
  2370. if (typeof value === "string") {
  2371. if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") {
  2372. element.textContent = value;
  2373. } else if (!reOverlay.test(value)) {
  2374. element.textContent = value;
  2375. } else {
  2376. const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template");
  2377. templateElement.innerHTML = value;
  2378. overlayChildNodes(templateElement.content, element);
  2379. }
  2380. }
  2381. overlayAttributes(translation, element);
  2382. }
  2383. function overlayChildNodes(fromFragment, toElement) {
  2384. for (const childNode of fromFragment.childNodes) {
  2385. if (childNode.nodeType === childNode.TEXT_NODE) {
  2386. continue;
  2387. }
  2388. if (childNode.hasAttribute("data-l10n-name")) {
  2389. const sanitized = getNodeForNamedElement(toElement, childNode);
  2390. fromFragment.replaceChild(sanitized, childNode);
  2391. continue;
  2392. }
  2393. if (isElementAllowed(childNode)) {
  2394. const sanitized = createSanitizedElement(childNode);
  2395. fromFragment.replaceChild(sanitized, childNode);
  2396. continue;
  2397. }
  2398. console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed.");
  2399. fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode);
  2400. }
  2401. toElement.textContent = "";
  2402. toElement.appendChild(fromFragment);
  2403. }
  2404. function hasAttribute(attributes, name) {
  2405. if (!attributes) {
  2406. return false;
  2407. }
  2408. for (let attr of attributes) {
  2409. if (attr.name === name) {
  2410. return true;
  2411. }
  2412. }
  2413. return false;
  2414. }
  2415. function overlayAttributes(fromElement, toElement) {
  2416. const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null;
  2417. for (const attr of Array.from(toElement.attributes)) {
  2418. if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) {
  2419. toElement.removeAttribute(attr.name);
  2420. }
  2421. }
  2422. if (!fromElement.attributes) {
  2423. return;
  2424. }
  2425. for (const attr of Array.from(fromElement.attributes)) {
  2426. if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) {
  2427. toElement.setAttribute(attr.name, attr.value);
  2428. }
  2429. }
  2430. }
  2431. function getNodeForNamedElement(sourceElement, translatedChild) {
  2432. const childName = translatedChild.getAttribute("data-l10n-name");
  2433. const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`);
  2434. if (!sourceChild) {
  2435. console.warn(`An element named "${childName}" wasn't found in the source.`);
  2436. return createTextNodeFromTextContent(translatedChild);
  2437. }
  2438. if (sourceChild.localName !== translatedChild.localName) {
  2439. console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`);
  2440. return createTextNodeFromTextContent(translatedChild);
  2441. }
  2442. sourceElement.removeChild(sourceChild);
  2443. const clone = sourceChild.cloneNode(false);
  2444. return shallowPopulateUsing(translatedChild, clone);
  2445. }
  2446. function createSanitizedElement(element) {
  2447. const clone = element.ownerDocument.createElement(element.localName);
  2448. return shallowPopulateUsing(element, clone);
  2449. }
  2450. function createTextNodeFromTextContent(element) {
  2451. return element.ownerDocument.createTextNode(element.textContent);
  2452. }
  2453. function isElementAllowed(element) {
  2454. const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI];
  2455. return allowed && allowed.includes(element.localName);
  2456. }
  2457. function isAttrNameLocalizable(name, element, explicitlyAllowed = null) {
  2458. if (explicitlyAllowed && explicitlyAllowed.includes(name)) {
  2459. return true;
  2460. }
  2461. const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI];
  2462. if (!allowed) {
  2463. return false;
  2464. }
  2465. const attrName = name.toLowerCase();
  2466. const elemName = element.localName;
  2467. if (allowed.global.includes(attrName)) {
  2468. return true;
  2469. }
  2470. if (!allowed[elemName]) {
  2471. return false;
  2472. }
  2473. if (allowed[elemName].includes(attrName)) {
  2474. return true;
  2475. }
  2476. if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") {
  2477. const type = element.type.toLowerCase();
  2478. if (type === "submit" || type === "button" || type === "reset") {
  2479. return true;
  2480. }
  2481. }
  2482. return false;
  2483. }
  2484. function shallowPopulateUsing(fromElement, toElement) {
  2485. toElement.textContent = fromElement.textContent;
  2486. overlayAttributes(fromElement, toElement);
  2487. return toElement;
  2488. }
  2489. ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_iterable.mjs
  2490. class CachedIterable extends Array {
  2491. static from(iterable) {
  2492. if (iterable instanceof this) {
  2493. return iterable;
  2494. }
  2495. return new this(iterable);
  2496. }
  2497. }
  2498. ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_sync_iterable.mjs
  2499. class CachedSyncIterable extends CachedIterable {
  2500. constructor(iterable) {
  2501. super();
  2502. if (Symbol.iterator in Object(iterable)) {
  2503. this.iterator = iterable[Symbol.iterator]();
  2504. } else {
  2505. throw new TypeError("Argument must implement the iteration protocol.");
  2506. }
  2507. }
  2508. [Symbol.iterator]() {
  2509. const cached = this;
  2510. let cur = 0;
  2511. return {
  2512. next() {
  2513. if (cached.length <= cur) {
  2514. cached.push(cached.iterator.next());
  2515. }
  2516. return cached[cur++];
  2517. }
  2518. };
  2519. }
  2520. touchNext(count = 1) {
  2521. let idx = 0;
  2522. while (idx++ < count) {
  2523. const last = this[this.length - 1];
  2524. if (last && last.done) {
  2525. break;
  2526. }
  2527. this.push(this.iterator.next());
  2528. }
  2529. return this[this.length - 1];
  2530. }
  2531. }
  2532. ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_async_iterable.mjs
  2533. class CachedAsyncIterable extends CachedIterable {
  2534. constructor(iterable) {
  2535. super();
  2536. if (Symbol.asyncIterator in Object(iterable)) {
  2537. this.iterator = iterable[Symbol.asyncIterator]();
  2538. } else if (Symbol.iterator in Object(iterable)) {
  2539. this.iterator = iterable[Symbol.iterator]();
  2540. } else {
  2541. throw new TypeError("Argument must implement the iteration protocol.");
  2542. }
  2543. }
  2544. [Symbol.asyncIterator]() {
  2545. const cached = this;
  2546. let cur = 0;
  2547. return {
  2548. async next() {
  2549. if (cached.length <= cur) {
  2550. cached.push(cached.iterator.next());
  2551. }
  2552. return cached[cur++];
  2553. }
  2554. };
  2555. }
  2556. async touchNext(count = 1) {
  2557. let idx = 0;
  2558. while (idx++ < count) {
  2559. const last = this[this.length - 1];
  2560. if (last && (await last).done) {
  2561. break;
  2562. }
  2563. this.push(this.iterator.next());
  2564. }
  2565. return this[this.length - 1];
  2566. }
  2567. }
  2568. ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/index.mjs
  2569. ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/localization.js
  2570. class Localization {
  2571. constructor(resourceIds = [], generateBundles) {
  2572. this.resourceIds = resourceIds;
  2573. this.generateBundles = generateBundles;
  2574. this.onChange(true);
  2575. }
  2576. addResourceIds(resourceIds, eager = false) {
  2577. this.resourceIds.push(...resourceIds);
  2578. this.onChange(eager);
  2579. return this.resourceIds.length;
  2580. }
  2581. removeResourceIds(resourceIds) {
  2582. this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r));
  2583. this.onChange();
  2584. return this.resourceIds.length;
  2585. }
  2586. async formatWithFallback(keys, method) {
  2587. const translations = [];
  2588. let hasAtLeastOneBundle = false;
  2589. for await (const bundle of this.bundles) {
  2590. hasAtLeastOneBundle = true;
  2591. const missingIds = keysFromBundle(method, bundle, keys, translations);
  2592. if (missingIds.size === 0) {
  2593. break;
  2594. }
  2595. if (typeof console !== "undefined") {
  2596. const locale = bundle.locales[0];
  2597. const ids = Array.from(missingIds).join(", ");
  2598. console.warn(`[fluent] Missing translations in ${locale}: ${ids}`);
  2599. }
  2600. }
  2601. if (!hasAtLeastOneBundle && typeof console !== "undefined") {
  2602. console.warn(`[fluent] Request for keys failed because no resource bundles got generated.
  2603. keys: ${JSON.stringify(keys)}.
  2604. resourceIds: ${JSON.stringify(this.resourceIds)}.`);
  2605. }
  2606. return translations;
  2607. }
  2608. formatMessages(keys) {
  2609. return this.formatWithFallback(keys, messageFromBundle);
  2610. }
  2611. formatValues(keys) {
  2612. return this.formatWithFallback(keys, valueFromBundle);
  2613. }
  2614. async formatValue(id, args) {
  2615. const [val] = await this.formatValues([{
  2616. id,
  2617. args
  2618. }]);
  2619. return val;
  2620. }
  2621. handleEvent() {
  2622. this.onChange();
  2623. }
  2624. onChange(eager = false) {
  2625. this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds));
  2626. if (eager) {
  2627. this.bundles.touchNext(2);
  2628. }
  2629. }
  2630. }
  2631. function valueFromBundle(bundle, errors, message, args) {
  2632. if (message.value) {
  2633. return bundle.formatPattern(message.value, args, errors);
  2634. }
  2635. return null;
  2636. }
  2637. function messageFromBundle(bundle, errors, message, args) {
  2638. const formatted = {
  2639. value: null,
  2640. attributes: null
  2641. };
  2642. if (message.value) {
  2643. formatted.value = bundle.formatPattern(message.value, args, errors);
  2644. }
  2645. let attrNames = Object.keys(message.attributes);
  2646. if (attrNames.length > 0) {
  2647. formatted.attributes = new Array(attrNames.length);
  2648. for (let [i, name] of attrNames.entries()) {
  2649. let value = bundle.formatPattern(message.attributes[name], args, errors);
  2650. formatted.attributes[i] = {
  2651. name,
  2652. value
  2653. };
  2654. }
  2655. }
  2656. return formatted;
  2657. }
  2658. function keysFromBundle(method, bundle, keys, translations) {
  2659. const messageErrors = [];
  2660. const missingIds = new Set();
  2661. keys.forEach(({
  2662. id,
  2663. args
  2664. }, i) => {
  2665. if (translations[i] !== undefined) {
  2666. return;
  2667. }
  2668. let message = bundle.getMessage(id);
  2669. if (message) {
  2670. messageErrors.length = 0;
  2671. translations[i] = method(bundle, messageErrors, message, args);
  2672. if (messageErrors.length > 0 && typeof console !== "undefined") {
  2673. const locale = bundle.locales[0];
  2674. const errors = messageErrors.join(", ");
  2675. console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`);
  2676. }
  2677. } else {
  2678. missingIds.add(id);
  2679. }
  2680. });
  2681. return missingIds;
  2682. }
  2683. ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/dom_localization.js
  2684. const L10NID_ATTR_NAME = "data-l10n-id";
  2685. const L10NARGS_ATTR_NAME = "data-l10n-args";
  2686. const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`;
  2687. class DOMLocalization extends Localization {
  2688. constructor(resourceIds, generateBundles) {
  2689. super(resourceIds, generateBundles);
  2690. this.roots = new Set();
  2691. this.pendingrAF = null;
  2692. this.pendingElements = new Set();
  2693. this.windowElement = null;
  2694. this.mutationObserver = null;
  2695. this.observerConfig = {
  2696. attributes: true,
  2697. characterData: false,
  2698. childList: true,
  2699. subtree: true,
  2700. attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME]
  2701. };
  2702. }
  2703. onChange(eager = false) {
  2704. super.onChange(eager);
  2705. if (this.roots) {
  2706. this.translateRoots();
  2707. }
  2708. }
  2709. setAttributes(element, id, args) {
  2710. element.setAttribute(L10NID_ATTR_NAME, id);
  2711. if (args) {
  2712. element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args));
  2713. } else {
  2714. element.removeAttribute(L10NARGS_ATTR_NAME);
  2715. }
  2716. return element;
  2717. }
  2718. getAttributes(element) {
  2719. return {
  2720. id: element.getAttribute(L10NID_ATTR_NAME),
  2721. args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null)
  2722. };
  2723. }
  2724. connectRoot(newRoot) {
  2725. for (const root of this.roots) {
  2726. if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) {
  2727. throw new Error("Cannot add a root that overlaps with existing root.");
  2728. }
  2729. }
  2730. if (this.windowElement) {
  2731. if (this.windowElement !== newRoot.ownerDocument.defaultView) {
  2732. throw new Error(`Cannot connect a root:
  2733. DOMLocalization already has a root from a different window.`);
  2734. }
  2735. } else {
  2736. this.windowElement = newRoot.ownerDocument.defaultView;
  2737. this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations));
  2738. }
  2739. this.roots.add(newRoot);
  2740. this.mutationObserver.observe(newRoot, this.observerConfig);
  2741. }
  2742. disconnectRoot(root) {
  2743. this.roots.delete(root);
  2744. this.pauseObserving();
  2745. if (this.roots.size === 0) {
  2746. this.mutationObserver = null;
  2747. if (this.windowElement && this.pendingrAF) {
  2748. this.windowElement.cancelAnimationFrame(this.pendingrAF);
  2749. }
  2750. this.windowElement = null;
  2751. this.pendingrAF = null;
  2752. this.pendingElements.clear();
  2753. return true;
  2754. }
  2755. this.resumeObserving();
  2756. return false;
  2757. }
  2758. translateRoots() {
  2759. const roots = Array.from(this.roots);
  2760. return Promise.all(roots.map(root => this.translateFragment(root)));
  2761. }
  2762. pauseObserving() {
  2763. if (!this.mutationObserver) {
  2764. return;
  2765. }
  2766. this.translateMutations(this.mutationObserver.takeRecords());
  2767. this.mutationObserver.disconnect();
  2768. }
  2769. resumeObserving() {
  2770. if (!this.mutationObserver) {
  2771. return;
  2772. }
  2773. for (const root of this.roots) {
  2774. this.mutationObserver.observe(root, this.observerConfig);
  2775. }
  2776. }
  2777. translateMutations(mutations) {
  2778. for (const mutation of mutations) {
  2779. switch (mutation.type) {
  2780. case "attributes":
  2781. if (mutation.target.hasAttribute("data-l10n-id")) {
  2782. this.pendingElements.add(mutation.target);
  2783. }
  2784. break;
  2785. case "childList":
  2786. for (const addedNode of mutation.addedNodes) {
  2787. if (addedNode.nodeType === addedNode.ELEMENT_NODE) {
  2788. if (addedNode.childElementCount) {
  2789. for (const element of this.getTranslatables(addedNode)) {
  2790. this.pendingElements.add(element);
  2791. }
  2792. } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) {
  2793. this.pendingElements.add(addedNode);
  2794. }
  2795. }
  2796. }
  2797. break;
  2798. }
  2799. }
  2800. if (this.pendingElements.size > 0) {
  2801. if (this.pendingrAF === null) {
  2802. this.pendingrAF = this.windowElement.requestAnimationFrame(() => {
  2803. this.translateElements(Array.from(this.pendingElements));
  2804. this.pendingElements.clear();
  2805. this.pendingrAF = null;
  2806. });
  2807. }
  2808. }
  2809. }
  2810. translateFragment(frag) {
  2811. return this.translateElements(this.getTranslatables(frag));
  2812. }
  2813. async translateElements(elements) {
  2814. if (!elements.length) {
  2815. return undefined;
  2816. }
  2817. const keys = elements.map(this.getKeysForElement);
  2818. const translations = await this.formatMessages(keys);
  2819. return this.applyTranslations(elements, translations);
  2820. }
  2821. applyTranslations(elements, translations) {
  2822. this.pauseObserving();
  2823. for (let i = 0; i < elements.length; i++) {
  2824. if (translations[i] !== undefined) {
  2825. translateElement(elements[i], translations[i]);
  2826. }
  2827. }
  2828. this.resumeObserving();
  2829. }
  2830. getTranslatables(element) {
  2831. const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY));
  2832. if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) {
  2833. nodes.push(element);
  2834. }
  2835. return nodes;
  2836. }
  2837. getKeysForElement(element) {
  2838. return {
  2839. id: element.getAttribute(L10NID_ATTR_NAME),
  2840. args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null)
  2841. };
  2842. }
  2843. }
  2844. ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/index.js
  2845. ;// CONCATENATED MODULE: ./web/l10n.js
  2846. class L10n {
  2847. #dir;
  2848. #elements = new Set();
  2849. #lang;
  2850. #l10n;
  2851. constructor({
  2852. lang,
  2853. isRTL
  2854. }, l10n = null) {
  2855. this.#lang = L10n.#fixupLangCode(lang);
  2856. this.#l10n = l10n;
  2857. this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr";
  2858. }
  2859. _setL10n(l10n) {
  2860. this.#l10n = l10n;
  2861. }
  2862. getLanguage() {
  2863. return this.#lang;
  2864. }
  2865. getDirection() {
  2866. return this.#dir;
  2867. }
  2868. async get(ids, args = null, fallback) {
  2869. if (Array.isArray(ids)) {
  2870. ids = ids.map(id => ({
  2871. id
  2872. }));
  2873. const messages = await this.#l10n.formatMessages(ids);
  2874. return messages.map(message => message.value);
  2875. }
  2876. const messages = await this.#l10n.formatMessages([{
  2877. id: ids,
  2878. args
  2879. }]);
  2880. return messages?.[0].value || fallback;
  2881. }
  2882. async translate(element) {
  2883. this.#elements.add(element);
  2884. try {
  2885. this.#l10n.connectRoot(element);
  2886. await this.#l10n.translateRoots();
  2887. } catch {}
  2888. }
  2889. async destroy() {
  2890. for (const element of this.#elements) {
  2891. this.#l10n.disconnectRoot(element);
  2892. }
  2893. this.#elements.clear();
  2894. this.#l10n.pauseObserving();
  2895. }
  2896. pause() {
  2897. this.#l10n.pauseObserving();
  2898. }
  2899. resume() {
  2900. this.#l10n.resumeObserving();
  2901. }
  2902. static #fixupLangCode(langCode) {
  2903. langCode = langCode?.toLowerCase() || "en-us";
  2904. const PARTIAL_LANG_CODES = {
  2905. en: "en-us",
  2906. es: "es-es",
  2907. fy: "fy-nl",
  2908. ga: "ga-ie",
  2909. gu: "gu-in",
  2910. hi: "hi-in",
  2911. hy: "hy-am",
  2912. nb: "nb-no",
  2913. ne: "ne-np",
  2914. nn: "nn-no",
  2915. pa: "pa-in",
  2916. pt: "pt-pt",
  2917. sv: "sv-se",
  2918. zh: "zh-cn"
  2919. };
  2920. return PARTIAL_LANG_CODES[langCode] || langCode;
  2921. }
  2922. static #isRTL(lang) {
  2923. const shortCode = lang.split("-", 1)[0];
  2924. return ["ar", "he", "fa", "ps", "ur"].includes(shortCode);
  2925. }
  2926. }
  2927. const GenericL10n = null;
  2928. ;// CONCATENATED MODULE: ./web/genericl10n.js
  2929. function createBundle(lang, text) {
  2930. const resource = new FluentResource(text);
  2931. const bundle = new FluentBundle(lang);
  2932. const errors = bundle.addResource(resource);
  2933. if (errors.length) {
  2934. console.error("L10n errors", errors);
  2935. }
  2936. return bundle;
  2937. }
  2938. class genericl10n_GenericL10n extends L10n {
  2939. constructor(lang) {
  2940. super({
  2941. lang
  2942. });
  2943. const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage());
  2944. this._setL10n(new DOMLocalization([], generateBundles));
  2945. }
  2946. static async *#generateBundles(defaultLang, baseLang) {
  2947. const {
  2948. baseURL,
  2949. paths
  2950. } = await this.#getPaths();
  2951. const langs = [baseLang];
  2952. if (defaultLang !== baseLang) {
  2953. const shortLang = baseLang.split("-", 1)[0];
  2954. if (shortLang !== baseLang) {
  2955. langs.push(shortLang);
  2956. }
  2957. langs.push(defaultLang);
  2958. }
  2959. for (const lang of langs) {
  2960. const bundle = await this.#createBundle(lang, baseURL, paths);
  2961. if (bundle) {
  2962. yield bundle;
  2963. } else if (lang === "en-us") {
  2964. yield this.#createBundleFallback(lang);
  2965. }
  2966. }
  2967. }
  2968. static async #createBundle(lang, baseURL, paths) {
  2969. const path = paths[lang];
  2970. if (!path) {
  2971. return null;
  2972. }
  2973. const url = new URL(path, baseURL);
  2974. const text = await fetchData(url, "text");
  2975. return createBundle(lang, text);
  2976. }
  2977. static async #getPaths() {
  2978. try {
  2979. const {
  2980. href
  2981. } = document.querySelector(`link[type="application/l10n"]`);
  2982. const paths = await fetchData(href, "json");
  2983. return {
  2984. baseURL: href.replace(/[^/]*$/, "") || "./",
  2985. paths
  2986. };
  2987. } catch {}
  2988. return {
  2989. baseURL: "./",
  2990. paths: Object.create(null)
  2991. };
  2992. }
  2993. static async *#generateBundlesFallback(lang) {
  2994. yield this.#createBundleFallback(lang);
  2995. }
  2996. static async #createBundleFallback(lang) {
  2997. const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-kb = { $size_kb } KB ({ $size_b } bytes)\npdfjs-document-properties-mb = { $size_mb } MB ({ $size_b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-string = { $date }, { $time }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-string = { $date }, { $time }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text =\n .aria-label = Text Editor\npdfjs-free-text-default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-label-top-left = Top left corner \u2014 resize\npdfjs-editor-resizer-label-top-middle = Top middle \u2014 resize\npdfjs-editor-resizer-label-top-right = Top right corner \u2014 resize\npdfjs-editor-resizer-label-middle-right = Middle right \u2014 resize\npdfjs-editor-resizer-label-bottom-right = Bottom right corner \u2014 resize\npdfjs-editor-resizer-label-bottom-middle = Bottom middle \u2014 resize\npdfjs-editor-resizer-label-bottom-left = Bottom left corner \u2014 resize\npdfjs-editor-resizer-label-middle-left = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all";
  2998. return createBundle(lang, text);
  2999. }
  3000. }
  3001. ;// CONCATENATED MODULE: ./web/generic_scripting.js
  3002. async function docProperties(pdfDocument) {
  3003. const url = "",
  3004. baseUrl = url.split("#", 1)[0];
  3005. let {
  3006. info,
  3007. metadata,
  3008. contentDispositionFilename,
  3009. contentLength
  3010. } = await pdfDocument.getMetadata();
  3011. if (!contentLength) {
  3012. const {
  3013. length
  3014. } = await pdfDocument.getDownloadInfo();
  3015. contentLength = length;
  3016. }
  3017. return {
  3018. ...info,
  3019. baseURL: baseUrl,
  3020. filesize: contentLength,
  3021. filename: contentDispositionFilename || getPdfFilenameFromUrl(url),
  3022. metadata: metadata?.getRaw(),
  3023. authors: metadata?.get("dc:creator"),
  3024. numPages: pdfDocument.numPages,
  3025. URL: url
  3026. };
  3027. }
  3028. class GenericScripting {
  3029. constructor(sandboxBundleSrc) {
  3030. this._ready = new Promise((resolve, reject) => {
  3031. const sandbox = import( /*webpackIgnore: true*/sandboxBundleSrc);
  3032. sandbox.then(pdfjsSandbox => {
  3033. resolve(pdfjsSandbox.QuickJSSandbox());
  3034. }).catch(reject);
  3035. });
  3036. }
  3037. async createSandbox(data) {
  3038. const sandbox = await this._ready;
  3039. sandbox.create(data);
  3040. }
  3041. async dispatchEventInSandbox(event) {
  3042. const sandbox = await this._ready;
  3043. setTimeout(() => sandbox.dispatchEvent(event), 0);
  3044. }
  3045. async destroySandbox() {
  3046. const sandbox = await this._ready;
  3047. sandbox.nukeSandbox();
  3048. }
  3049. }
  3050. ;// CONCATENATED MODULE: ./web/genericcom.js
  3051. function initCom(app) {}
  3052. class Preferences extends BasePreferences {
  3053. async _writeToStorage(prefObj) {
  3054. localStorage.setItem("pdfjs.preferences", JSON.stringify(prefObj));
  3055. }
  3056. async _readFromStorage(prefObj) {
  3057. return {
  3058. prefs: JSON.parse(localStorage.getItem("pdfjs.preferences"))
  3059. };
  3060. }
  3061. }
  3062. class ExternalServices extends BaseExternalServices {
  3063. async createL10n() {
  3064. return new genericl10n_GenericL10n(AppOptions.get("localeProperties")?.lang);
  3065. }
  3066. createScripting() {
  3067. return new GenericScripting(AppOptions.get("sandboxBundleSrc"));
  3068. }
  3069. }
  3070. class MLManager {
  3071. async isEnabledFor(_name) {
  3072. return false;
  3073. }
  3074. async deleteModel(_service) {
  3075. return null;
  3076. }
  3077. async guess() {
  3078. return null;
  3079. }
  3080. }
  3081. ;// CONCATENATED MODULE: ./web/alt_text_manager.js
  3082. class AltTextManager {
  3083. #boundUpdateUIState = this.#updateUIState.bind(this);
  3084. #boundSetPosition = this.#setPosition.bind(this);
  3085. #boundOnClick = this.#onClick.bind(this);
  3086. #currentEditor = null;
  3087. #cancelButton;
  3088. #dialog;
  3089. #eventBus;
  3090. #hasUsedPointer = false;
  3091. #optionDescription;
  3092. #optionDecorative;
  3093. #overlayManager;
  3094. #saveButton;
  3095. #textarea;
  3096. #uiManager;
  3097. #previousAltText = null;
  3098. #svgElement = null;
  3099. #rectElement = null;
  3100. #container;
  3101. #telemetryData = null;
  3102. constructor({
  3103. dialog,
  3104. optionDescription,
  3105. optionDecorative,
  3106. textarea,
  3107. cancelButton,
  3108. saveButton
  3109. }, container, overlayManager, eventBus) {
  3110. this.#dialog = dialog;
  3111. this.#optionDescription = optionDescription;
  3112. this.#optionDecorative = optionDecorative;
  3113. this.#textarea = textarea;
  3114. this.#cancelButton = cancelButton;
  3115. this.#saveButton = saveButton;
  3116. this.#overlayManager = overlayManager;
  3117. this.#eventBus = eventBus;
  3118. this.#container = container;
  3119. dialog.addEventListener("close", this.#close.bind(this));
  3120. dialog.addEventListener("contextmenu", event => {
  3121. if (event.target !== this.#textarea) {
  3122. event.preventDefault();
  3123. }
  3124. });
  3125. cancelButton.addEventListener("click", this.#finish.bind(this));
  3126. saveButton.addEventListener("click", this.#save.bind(this));
  3127. optionDescription.addEventListener("change", this.#boundUpdateUIState);
  3128. optionDecorative.addEventListener("change", this.#boundUpdateUIState);
  3129. this.#overlayManager.register(dialog);
  3130. }
  3131. get _elements() {
  3132. return shadow(this, "_elements", [this.#optionDescription, this.#optionDecorative, this.#textarea, this.#saveButton, this.#cancelButton]);
  3133. }
  3134. #createSVGElement() {
  3135. if (this.#svgElement) {
  3136. return;
  3137. }
  3138. const svgFactory = new DOMSVGFactory();
  3139. const svg = this.#svgElement = svgFactory.createElement("svg");
  3140. svg.setAttribute("width", "0");
  3141. svg.setAttribute("height", "0");
  3142. const defs = svgFactory.createElement("defs");
  3143. svg.append(defs);
  3144. const mask = svgFactory.createElement("mask");
  3145. defs.append(mask);
  3146. mask.setAttribute("id", "alttext-manager-mask");
  3147. mask.setAttribute("maskContentUnits", "objectBoundingBox");
  3148. let rect = svgFactory.createElement("rect");
  3149. mask.append(rect);
  3150. rect.setAttribute("fill", "white");
  3151. rect.setAttribute("width", "1");
  3152. rect.setAttribute("height", "1");
  3153. rect.setAttribute("x", "0");
  3154. rect.setAttribute("y", "0");
  3155. rect = this.#rectElement = svgFactory.createElement("rect");
  3156. mask.append(rect);
  3157. rect.setAttribute("fill", "black");
  3158. this.#dialog.append(svg);
  3159. }
  3160. async editAltText(uiManager, editor) {
  3161. if (this.#currentEditor || !editor) {
  3162. return;
  3163. }
  3164. this.#createSVGElement();
  3165. this.#hasUsedPointer = false;
  3166. for (const element of this._elements) {
  3167. element.addEventListener("click", this.#boundOnClick);
  3168. }
  3169. const {
  3170. altText,
  3171. decorative
  3172. } = editor.altTextData;
  3173. if (decorative === true) {
  3174. this.#optionDecorative.checked = true;
  3175. this.#optionDescription.checked = false;
  3176. } else {
  3177. this.#optionDecorative.checked = false;
  3178. this.#optionDescription.checked = true;
  3179. }
  3180. this.#previousAltText = this.#textarea.value = altText?.trim() || "";
  3181. this.#updateUIState();
  3182. this.#currentEditor = editor;
  3183. this.#uiManager = uiManager;
  3184. this.#uiManager.removeEditListeners();
  3185. this.#eventBus._on("resize", this.#boundSetPosition);
  3186. try {
  3187. await this.#overlayManager.open(this.#dialog);
  3188. this.#setPosition();
  3189. } catch (ex) {
  3190. this.#close();
  3191. throw ex;
  3192. }
  3193. }
  3194. #setPosition() {
  3195. if (!this.#currentEditor) {
  3196. return;
  3197. }
  3198. const dialog = this.#dialog;
  3199. const {
  3200. style
  3201. } = dialog;
  3202. const {
  3203. x: containerX,
  3204. y: containerY,
  3205. width: containerW,
  3206. height: containerH
  3207. } = this.#container.getBoundingClientRect();
  3208. const {
  3209. innerWidth: windowW,
  3210. innerHeight: windowH
  3211. } = window;
  3212. const {
  3213. width: dialogW,
  3214. height: dialogH
  3215. } = dialog.getBoundingClientRect();
  3216. const {
  3217. x,
  3218. y,
  3219. width,
  3220. height
  3221. } = this.#currentEditor.getClientDimensions();
  3222. const MARGIN = 10;
  3223. const isLTR = this.#uiManager.direction === "ltr";
  3224. const xs = Math.max(x, containerX);
  3225. const xe = Math.min(x + width, containerX + containerW);
  3226. const ys = Math.max(y, containerY);
  3227. const ye = Math.min(y + height, containerY + containerH);
  3228. this.#rectElement.setAttribute("width", `${(xe - xs) / windowW}`);
  3229. this.#rectElement.setAttribute("height", `${(ye - ys) / windowH}`);
  3230. this.#rectElement.setAttribute("x", `${xs / windowW}`);
  3231. this.#rectElement.setAttribute("y", `${ys / windowH}`);
  3232. let left = null;
  3233. let top = Math.max(y, 0);
  3234. top += Math.min(windowH - (top + dialogH), 0);
  3235. if (isLTR) {
  3236. if (x + width + MARGIN + dialogW < windowW) {
  3237. left = x + width + MARGIN;
  3238. } else if (x > dialogW + MARGIN) {
  3239. left = x - dialogW - MARGIN;
  3240. }
  3241. } else if (x > dialogW + MARGIN) {
  3242. left = x - dialogW - MARGIN;
  3243. } else if (x + width + MARGIN + dialogW < windowW) {
  3244. left = x + width + MARGIN;
  3245. }
  3246. if (left === null) {
  3247. top = null;
  3248. left = Math.max(x, 0);
  3249. left += Math.min(windowW - (left + dialogW), 0);
  3250. if (y > dialogH + MARGIN) {
  3251. top = y - dialogH - MARGIN;
  3252. } else if (y + height + MARGIN + dialogH < windowH) {
  3253. top = y + height + MARGIN;
  3254. }
  3255. }
  3256. if (top !== null) {
  3257. dialog.classList.add("positioned");
  3258. if (isLTR) {
  3259. style.left = `${left}px`;
  3260. } else {
  3261. style.right = `${windowW - left - dialogW}px`;
  3262. }
  3263. style.top = `${top}px`;
  3264. } else {
  3265. dialog.classList.remove("positioned");
  3266. style.left = "";
  3267. style.top = "";
  3268. }
  3269. }
  3270. #finish() {
  3271. if (this.#overlayManager.active === this.#dialog) {
  3272. this.#overlayManager.close(this.#dialog);
  3273. }
  3274. }
  3275. #close() {
  3276. this.#currentEditor._reportTelemetry(this.#telemetryData || {
  3277. action: "alt_text_cancel",
  3278. alt_text_keyboard: !this.#hasUsedPointer
  3279. });
  3280. this.#telemetryData = null;
  3281. this.#removeOnClickListeners();
  3282. this.#uiManager?.addEditListeners();
  3283. this.#eventBus._off("resize", this.#boundSetPosition);
  3284. this.#currentEditor.altTextFinish();
  3285. this.#currentEditor = null;
  3286. this.#uiManager = null;
  3287. }
  3288. #updateUIState() {
  3289. this.#textarea.disabled = this.#optionDecorative.checked;
  3290. }
  3291. #save() {
  3292. const altText = this.#textarea.value.trim();
  3293. const decorative = this.#optionDecorative.checked;
  3294. this.#currentEditor.altTextData = {
  3295. altText,
  3296. decorative
  3297. };
  3298. this.#telemetryData = {
  3299. action: "alt_text_save",
  3300. alt_text_description: !!altText,
  3301. alt_text_edit: !!this.#previousAltText && this.#previousAltText !== altText,
  3302. alt_text_decorative: decorative,
  3303. alt_text_keyboard: !this.#hasUsedPointer
  3304. };
  3305. this.#finish();
  3306. }
  3307. #onClick(evt) {
  3308. if (evt.detail === 0) {
  3309. return;
  3310. }
  3311. this.#hasUsedPointer = true;
  3312. this.#removeOnClickListeners();
  3313. }
  3314. #removeOnClickListeners() {
  3315. for (const element of this._elements) {
  3316. element.removeEventListener("click", this.#boundOnClick);
  3317. }
  3318. }
  3319. destroy() {
  3320. this.#uiManager = null;
  3321. this.#finish();
  3322. this.#svgElement?.remove();
  3323. this.#svgElement = this.#rectElement = null;
  3324. }
  3325. }
  3326. ;// CONCATENATED MODULE: ./web/annotation_editor_params.js
  3327. class AnnotationEditorParams {
  3328. constructor(options, eventBus) {
  3329. this.eventBus = eventBus;
  3330. this.#bindListeners(options);
  3331. }
  3332. #bindListeners({
  3333. editorFreeTextFontSize,
  3334. editorFreeTextColor,
  3335. editorInkColor,
  3336. editorInkThickness,
  3337. editorInkOpacity,
  3338. editorStampAddImage,
  3339. editorFreeHighlightThickness,
  3340. editorHighlightShowAll
  3341. }) {
  3342. const dispatchEvent = (typeStr, value) => {
  3343. this.eventBus.dispatch("switchannotationeditorparams", {
  3344. source: this,
  3345. type: AnnotationEditorParamsType[typeStr],
  3346. value
  3347. });
  3348. };
  3349. editorFreeTextFontSize.addEventListener("input", function () {
  3350. dispatchEvent("FREETEXT_SIZE", this.valueAsNumber);
  3351. });
  3352. editorFreeTextColor.addEventListener("input", function () {
  3353. dispatchEvent("FREETEXT_COLOR", this.value);
  3354. });
  3355. editorInkColor.addEventListener("input", function () {
  3356. dispatchEvent("INK_COLOR", this.value);
  3357. });
  3358. editorInkThickness.addEventListener("input", function () {
  3359. dispatchEvent("INK_THICKNESS", this.valueAsNumber);
  3360. });
  3361. editorInkOpacity.addEventListener("input", function () {
  3362. dispatchEvent("INK_OPACITY", this.valueAsNumber);
  3363. });
  3364. editorStampAddImage.addEventListener("click", () => {
  3365. dispatchEvent("CREATE");
  3366. });
  3367. editorFreeHighlightThickness.addEventListener("input", function () {
  3368. dispatchEvent("HIGHLIGHT_THICKNESS", this.valueAsNumber);
  3369. });
  3370. editorHighlightShowAll.addEventListener("click", function () {
  3371. const checked = this.getAttribute("aria-pressed") === "true";
  3372. this.setAttribute("aria-pressed", !checked);
  3373. dispatchEvent("HIGHLIGHT_SHOW_ALL", !checked);
  3374. });
  3375. this.eventBus._on("annotationeditorparamschanged", evt => {
  3376. for (const [type, value] of evt.details) {
  3377. switch (type) {
  3378. case AnnotationEditorParamsType.FREETEXT_SIZE:
  3379. editorFreeTextFontSize.value = value;
  3380. break;
  3381. case AnnotationEditorParamsType.FREETEXT_COLOR:
  3382. editorFreeTextColor.value = value;
  3383. break;
  3384. case AnnotationEditorParamsType.INK_COLOR:
  3385. editorInkColor.value = value;
  3386. break;
  3387. case AnnotationEditorParamsType.INK_THICKNESS:
  3388. editorInkThickness.value = value;
  3389. break;
  3390. case AnnotationEditorParamsType.INK_OPACITY:
  3391. editorInkOpacity.value = value;
  3392. break;
  3393. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  3394. editorFreeHighlightThickness.value = value;
  3395. break;
  3396. case AnnotationEditorParamsType.HIGHLIGHT_FREE:
  3397. editorFreeHighlightThickness.disabled = !value;
  3398. break;
  3399. case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
  3400. editorHighlightShowAll.setAttribute("aria-pressed", value);
  3401. break;
  3402. }
  3403. }
  3404. });
  3405. }
  3406. }
  3407. ;// CONCATENATED MODULE: ./web/caret_browsing.js
  3408. const PRECISION = 1e-1;
  3409. class CaretBrowsingMode {
  3410. #mainContainer;
  3411. #toolBarHeight;
  3412. #viewerContainer;
  3413. constructor(mainContainer, viewerContainer, toolbarContainer) {
  3414. this.#mainContainer = mainContainer;
  3415. this.#viewerContainer = viewerContainer;
  3416. this.#toolBarHeight = toolbarContainer?.getBoundingClientRect().height ?? 0;
  3417. }
  3418. #isOnSameLine(rect1, rect2) {
  3419. const top1 = rect1.y;
  3420. const bot1 = rect1.bottom;
  3421. const mid1 = rect1.y + rect1.height / 2;
  3422. const top2 = rect2.y;
  3423. const bot2 = rect2.bottom;
  3424. const mid2 = rect2.y + rect2.height / 2;
  3425. return top1 <= mid2 && mid2 <= bot1 || top2 <= mid1 && mid1 <= bot2;
  3426. }
  3427. #isUnderOver(rect, x, y, isUp) {
  3428. const midY = rect.y + rect.height / 2;
  3429. return (isUp ? y >= midY : y <= midY) && rect.x - PRECISION <= x && x <= rect.right + PRECISION;
  3430. }
  3431. #isVisible(rect) {
  3432. return rect.top >= this.#toolBarHeight && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth);
  3433. }
  3434. #getCaretPosition(selection, isUp) {
  3435. const {
  3436. focusNode,
  3437. focusOffset
  3438. } = selection;
  3439. const range = document.createRange();
  3440. range.setStart(focusNode, focusOffset);
  3441. range.setEnd(focusNode, focusOffset);
  3442. const rect = range.getBoundingClientRect();
  3443. return [rect.x, isUp ? rect.top : rect.bottom];
  3444. }
  3445. static #caretPositionFromPoint(x, y) {
  3446. if (!document.caretPositionFromPoint) {
  3447. const {
  3448. startContainer: offsetNode,
  3449. startOffset: offset
  3450. } = document.caretRangeFromPoint(x, y);
  3451. return {
  3452. offsetNode,
  3453. offset
  3454. };
  3455. }
  3456. return document.caretPositionFromPoint(x, y);
  3457. }
  3458. #setCaretPositionHelper(selection, caretX, select, element, rect) {
  3459. rect ||= element.getBoundingClientRect();
  3460. if (caretX <= rect.x + PRECISION) {
  3461. if (select) {
  3462. selection.extend(element.firstChild, 0);
  3463. } else {
  3464. selection.setPosition(element.firstChild, 0);
  3465. }
  3466. return;
  3467. }
  3468. if (rect.right - PRECISION <= caretX) {
  3469. const {
  3470. lastChild
  3471. } = element;
  3472. if (select) {
  3473. selection.extend(lastChild, lastChild.length);
  3474. } else {
  3475. selection.setPosition(lastChild, lastChild.length);
  3476. }
  3477. return;
  3478. }
  3479. const midY = rect.y + rect.height / 2;
  3480. let caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);
  3481. let parentElement = caretPosition.offsetNode?.parentElement;
  3482. if (parentElement && parentElement !== element) {
  3483. const elementsAtPoint = document.elementsFromPoint(caretX, midY);
  3484. const savedVisibilities = [];
  3485. for (const el of elementsAtPoint) {
  3486. if (el === element) {
  3487. break;
  3488. }
  3489. const {
  3490. style
  3491. } = el;
  3492. savedVisibilities.push([el, style.visibility]);
  3493. style.visibility = "hidden";
  3494. }
  3495. caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);
  3496. parentElement = caretPosition.offsetNode?.parentElement;
  3497. for (const [el, visibility] of savedVisibilities) {
  3498. el.style.visibility = visibility;
  3499. }
  3500. }
  3501. if (parentElement !== element) {
  3502. if (select) {
  3503. selection.extend(element.firstChild, 0);
  3504. } else {
  3505. selection.setPosition(element.firstChild, 0);
  3506. }
  3507. return;
  3508. }
  3509. if (select) {
  3510. selection.extend(caretPosition.offsetNode, caretPosition.offset);
  3511. } else {
  3512. selection.setPosition(caretPosition.offsetNode, caretPosition.offset);
  3513. }
  3514. }
  3515. #setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX) {
  3516. if (this.#isVisible(newLineElementRect)) {
  3517. this.#setCaretPositionHelper(selection, caretX, select, newLineElement, newLineElementRect);
  3518. return;
  3519. }
  3520. this.#mainContainer.addEventListener("scrollend", this.#setCaretPositionHelper.bind(this, selection, caretX, select, newLineElement, null), {
  3521. once: true
  3522. });
  3523. newLineElement.scrollIntoView();
  3524. }
  3525. #getNodeOnNextPage(textLayer, isUp) {
  3526. while (true) {
  3527. const page = textLayer.closest(".page");
  3528. const pageNumber = parseInt(page.getAttribute("data-page-number"));
  3529. const nextPage = isUp ? pageNumber - 1 : pageNumber + 1;
  3530. textLayer = this.#viewerContainer.querySelector(`.page[data-page-number="${nextPage}"] .textLayer`);
  3531. if (!textLayer) {
  3532. return null;
  3533. }
  3534. const walker = document.createTreeWalker(textLayer, NodeFilter.SHOW_TEXT);
  3535. const node = isUp ? walker.lastChild() : walker.firstChild();
  3536. if (node) {
  3537. return node;
  3538. }
  3539. }
  3540. }
  3541. moveCaret(isUp, select) {
  3542. const selection = document.getSelection();
  3543. if (selection.rangeCount === 0) {
  3544. return;
  3545. }
  3546. const {
  3547. focusNode
  3548. } = selection;
  3549. const focusElement = focusNode.nodeType !== Node.ELEMENT_NODE ? focusNode.parentElement : focusNode;
  3550. const root = focusElement.closest(".textLayer");
  3551. if (!root) {
  3552. return;
  3553. }
  3554. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  3555. walker.currentNode = focusNode;
  3556. const focusRect = focusElement.getBoundingClientRect();
  3557. let newLineElement = null;
  3558. const nodeIterator = (isUp ? walker.previousSibling : walker.nextSibling).bind(walker);
  3559. while (nodeIterator()) {
  3560. const element = walker.currentNode.parentElement;
  3561. if (!this.#isOnSameLine(focusRect, element.getBoundingClientRect())) {
  3562. newLineElement = element;
  3563. break;
  3564. }
  3565. }
  3566. if (!newLineElement) {
  3567. const node = this.#getNodeOnNextPage(root, isUp);
  3568. if (!node) {
  3569. return;
  3570. }
  3571. if (select) {
  3572. const lastNode = (isUp ? walker.firstChild() : walker.lastChild()) || focusNode;
  3573. selection.extend(lastNode, isUp ? 0 : lastNode.length);
  3574. const range = document.createRange();
  3575. range.setStart(node, isUp ? node.length : 0);
  3576. range.setEnd(node, isUp ? node.length : 0);
  3577. selection.addRange(range);
  3578. return;
  3579. }
  3580. const [caretX] = this.#getCaretPosition(selection, isUp);
  3581. const {
  3582. parentElement
  3583. } = node;
  3584. this.#setCaretPosition(select, selection, parentElement, parentElement.getBoundingClientRect(), caretX);
  3585. return;
  3586. }
  3587. const [caretX, caretY] = this.#getCaretPosition(selection, isUp);
  3588. const newLineElementRect = newLineElement.getBoundingClientRect();
  3589. if (this.#isUnderOver(newLineElementRect, caretX, caretY, isUp)) {
  3590. this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX);
  3591. return;
  3592. }
  3593. while (nodeIterator()) {
  3594. const element = walker.currentNode.parentElement;
  3595. const elementRect = element.getBoundingClientRect();
  3596. if (!this.#isOnSameLine(newLineElementRect, elementRect)) {
  3597. break;
  3598. }
  3599. if (this.#isUnderOver(elementRect, caretX, caretY, isUp)) {
  3600. this.#setCaretPosition(select, selection, element, elementRect, caretX);
  3601. return;
  3602. }
  3603. }
  3604. this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX);
  3605. }
  3606. }
  3607. ;// CONCATENATED MODULE: ./web/download_manager.js
  3608. function download(blobUrl, filename) {
  3609. const a = document.createElement("a");
  3610. if (!a.click) {
  3611. throw new Error('DownloadManager: "a.click()" is not supported.');
  3612. }
  3613. a.href = blobUrl;
  3614. a.target = "_parent";
  3615. if ("download" in a) {
  3616. a.download = filename;
  3617. }
  3618. (document.body || document.documentElement).append(a);
  3619. a.click();
  3620. a.remove();
  3621. }
  3622. class DownloadManager {
  3623. #openBlobUrls = new WeakMap();
  3624. downloadData(data, filename, contentType) {
  3625. const blobUrl = URL.createObjectURL(new Blob([data], {
  3626. type: contentType
  3627. }));
  3628. download(blobUrl, filename);
  3629. }
  3630. openOrDownloadData(data, filename, dest = null) {
  3631. const isPdfData = isPdfFile(filename);
  3632. const contentType = isPdfData ? "application/pdf" : "";
  3633. if (isPdfData) {
  3634. let blobUrl = this.#openBlobUrls.get(data);
  3635. if (!blobUrl) {
  3636. blobUrl = URL.createObjectURL(new Blob([data], {
  3637. type: contentType
  3638. }));
  3639. this.#openBlobUrls.set(data, blobUrl);
  3640. }
  3641. let viewerUrl;
  3642. debugger
  3643. viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename);
  3644. if (dest) {
  3645. viewerUrl += `#${escape(dest)}`;
  3646. }
  3647. try {
  3648. window.open(viewerUrl);
  3649. return true;
  3650. } catch (ex) {
  3651. console.error(`openOrDownloadData: ${ex}`);
  3652. URL.revokeObjectURL(blobUrl);
  3653. this.#openBlobUrls.delete(data);
  3654. }
  3655. }
  3656. this.downloadData(data, filename, contentType);
  3657. return false;
  3658. }
  3659. download(data, url, filename, _options) {
  3660. let blobUrl;
  3661. if (data) {
  3662. blobUrl = URL.createObjectURL(new Blob([data], {
  3663. type: "application/pdf"
  3664. }));
  3665. } else {
  3666. if (!createValidAbsoluteUrl(url, "http://example.com")) {
  3667. console.error(`download - not a valid URL: ${url}`);
  3668. return;
  3669. }
  3670. blobUrl = url + "#pdfjs.action=download";
  3671. }
  3672. download(blobUrl, filename);
  3673. }
  3674. }
  3675. ;// CONCATENATED MODULE: ./web/overlay_manager.js
  3676. class OverlayManager {
  3677. #overlays = new WeakMap();
  3678. #active = null;
  3679. get active() {
  3680. return this.#active;
  3681. }
  3682. async register(dialog, canForceClose = false) {
  3683. if (typeof dialog !== "object") {
  3684. throw new Error("Not enough parameters.");
  3685. } else if (this.#overlays.has(dialog)) {
  3686. throw new Error("The overlay is already registered.");
  3687. }
  3688. this.#overlays.set(dialog, {
  3689. canForceClose
  3690. });
  3691. dialog.addEventListener("cancel", evt => {
  3692. this.#active = null;
  3693. });
  3694. }
  3695. async open(dialog) {
  3696. if (!this.#overlays.has(dialog)) {
  3697. throw new Error("The overlay does not exist.");
  3698. } else if (this.#active) {
  3699. if (this.#active === dialog) {
  3700. throw new Error("The overlay is already active.");
  3701. } else if (this.#overlays.get(dialog).canForceClose) {
  3702. await this.close();
  3703. } else {
  3704. throw new Error("Another overlay is currently active.");
  3705. }
  3706. }
  3707. this.#active = dialog;
  3708. dialog.showModal();
  3709. }
  3710. async close(dialog = this.#active) {
  3711. if (!this.#overlays.has(dialog)) {
  3712. throw new Error("The overlay does not exist.");
  3713. } else if (!this.#active) {
  3714. throw new Error("The overlay is currently not active.");
  3715. } else if (this.#active !== dialog) {
  3716. throw new Error("Another overlay is currently active.");
  3717. }
  3718. dialog.close();
  3719. this.#active = null;
  3720. }
  3721. }
  3722. ;// CONCATENATED MODULE: ./web/password_prompt.js
  3723. class PasswordPrompt {
  3724. #activeCapability = null;
  3725. #updateCallback = null;
  3726. #reason = null;
  3727. constructor(options, overlayManager, isViewerEmbedded = false) {
  3728. this.dialog = options.dialog;
  3729. this.label = options.label;
  3730. this.input = options.input;
  3731. this.submitButton = options.submitButton;
  3732. this.cancelButton = options.cancelButton;
  3733. this.overlayManager = overlayManager;
  3734. this._isViewerEmbedded = isViewerEmbedded;
  3735. this.submitButton.addEventListener("click", this.#verify.bind(this));
  3736. this.cancelButton.addEventListener("click", this.close.bind(this));
  3737. this.input.addEventListener("keydown", e => {
  3738. if (e.keyCode === 13) {
  3739. this.#verify();
  3740. }
  3741. });
  3742. this.overlayManager.register(this.dialog, true);
  3743. this.dialog.addEventListener("close", this.#cancel.bind(this));
  3744. }
  3745. async open() {
  3746. await this.#activeCapability?.promise;
  3747. this.#activeCapability = Promise.withResolvers();
  3748. try {
  3749. await this.overlayManager.open(this.dialog);
  3750. } catch (ex) {
  3751. this.#activeCapability.resolve();
  3752. throw ex;
  3753. }
  3754. const passwordIncorrect = this.#reason === PasswordResponses.INCORRECT_PASSWORD;
  3755. if (!this._isViewerEmbedded || passwordIncorrect) {
  3756. this.input.focus();
  3757. }
  3758. this.label.setAttribute("data-l10n-id", `pdfjs-password-${passwordIncorrect ? "invalid" : "label"}`);
  3759. }
  3760. async close() {
  3761. if (this.overlayManager.active === this.dialog) {
  3762. this.overlayManager.close(this.dialog);
  3763. }
  3764. }
  3765. #verify() {
  3766. const password = this.input.value;
  3767. if (password?.length > 0) {
  3768. this.#invokeCallback(password);
  3769. }
  3770. }
  3771. #cancel() {
  3772. this.#invokeCallback(new Error("PasswordPrompt cancelled."));
  3773. this.#activeCapability.resolve();
  3774. }
  3775. #invokeCallback(password) {
  3776. if (!this.#updateCallback) {
  3777. return;
  3778. }
  3779. this.close();
  3780. this.input.value = "";
  3781. this.#updateCallback(password);
  3782. this.#updateCallback = null;
  3783. }
  3784. async setUpdateCallback(updateCallback, reason) {
  3785. if (this.#activeCapability) {
  3786. await this.#activeCapability.promise;
  3787. }
  3788. this.#updateCallback = updateCallback;
  3789. this.#reason = reason;
  3790. }
  3791. }
  3792. ;// CONCATENATED MODULE: ./web/base_tree_viewer.js
  3793. const TREEITEM_OFFSET_TOP = -100;
  3794. const TREEITEM_SELECTED_CLASS = "selected";
  3795. class BaseTreeViewer {
  3796. constructor(options) {
  3797. if (this.constructor === BaseTreeViewer) {
  3798. throw new Error("Cannot initialize BaseTreeViewer.");
  3799. }
  3800. this.container = options.container;
  3801. this.eventBus = options.eventBus;
  3802. this._l10n = options.l10n;
  3803. this.reset();
  3804. }
  3805. reset() {
  3806. this._pdfDocument = null;
  3807. this._lastToggleIsShow = true;
  3808. this._currentTreeItem = null;
  3809. this.container.textContent = "";
  3810. this.container.classList.remove("treeWithDeepNesting");
  3811. }
  3812. _dispatchEvent(count) {
  3813. throw new Error("Not implemented: _dispatchEvent");
  3814. }
  3815. _bindLink(element, params) {
  3816. throw new Error("Not implemented: _bindLink");
  3817. }
  3818. _normalizeTextContent(str) {
  3819. return removeNullCharacters(str, true) || "\u2013";
  3820. }
  3821. _addToggleButton(div, hidden = false) {
  3822. const toggler = document.createElement("div");
  3823. toggler.className = "treeItemToggler";
  3824. if (hidden) {
  3825. toggler.classList.add("treeItemsHidden");
  3826. }
  3827. toggler.onclick = evt => {
  3828. evt.stopPropagation();
  3829. toggler.classList.toggle("treeItemsHidden");
  3830. if (evt.shiftKey) {
  3831. const shouldShowAll = !toggler.classList.contains("treeItemsHidden");
  3832. this._toggleTreeItem(div, shouldShowAll);
  3833. }
  3834. };
  3835. div.prepend(toggler);
  3836. }
  3837. _toggleTreeItem(root, show = false) {
  3838. this._l10n.pause();
  3839. this._lastToggleIsShow = show;
  3840. for (const toggler of root.querySelectorAll(".treeItemToggler")) {
  3841. toggler.classList.toggle("treeItemsHidden", !show);
  3842. }
  3843. this._l10n.resume();
  3844. }
  3845. _toggleAllTreeItems() {
  3846. this._toggleTreeItem(this.container, !this._lastToggleIsShow);
  3847. }
  3848. _finishRendering(fragment, count, hasAnyNesting = false) {
  3849. if (hasAnyNesting) {
  3850. this.container.classList.add("treeWithDeepNesting");
  3851. this._lastToggleIsShow = !fragment.querySelector(".treeItemsHidden");
  3852. }
  3853. this._l10n.pause();
  3854. this.container.append(fragment);
  3855. this._l10n.resume();
  3856. this._dispatchEvent(count);
  3857. }
  3858. render(params) {
  3859. throw new Error("Not implemented: render");
  3860. }
  3861. _updateCurrentTreeItem(treeItem = null) {
  3862. if (this._currentTreeItem) {
  3863. this._currentTreeItem.classList.remove(TREEITEM_SELECTED_CLASS);
  3864. this._currentTreeItem = null;
  3865. }
  3866. if (treeItem) {
  3867. treeItem.classList.add(TREEITEM_SELECTED_CLASS);
  3868. this._currentTreeItem = treeItem;
  3869. }
  3870. }
  3871. _scrollToCurrentTreeItem(treeItem) {
  3872. if (!treeItem) {
  3873. return;
  3874. }
  3875. this._l10n.pause();
  3876. let currentNode = treeItem.parentNode;
  3877. while (currentNode && currentNode !== this.container) {
  3878. if (currentNode.classList.contains("treeItem")) {
  3879. const toggler = currentNode.firstElementChild;
  3880. toggler?.classList.remove("treeItemsHidden");
  3881. }
  3882. currentNode = currentNode.parentNode;
  3883. }
  3884. this._l10n.resume();
  3885. this._updateCurrentTreeItem(treeItem);
  3886. this.container.scrollTo(treeItem.offsetLeft, treeItem.offsetTop + TREEITEM_OFFSET_TOP);
  3887. }
  3888. }
  3889. ;// CONCATENATED MODULE: ./web/pdf_attachment_viewer.js
  3890. class PDFAttachmentViewer extends BaseTreeViewer {
  3891. constructor(options) {
  3892. super(options);
  3893. this.downloadManager = options.downloadManager;
  3894. this.eventBus._on("fileattachmentannotation", this.#appendAttachment.bind(this));
  3895. }
  3896. reset(keepRenderedCapability = false) {
  3897. super.reset();
  3898. this._attachments = null;
  3899. if (!keepRenderedCapability) {
  3900. this._renderedCapability = Promise.withResolvers();
  3901. }
  3902. this._pendingDispatchEvent = false;
  3903. }
  3904. async _dispatchEvent(attachmentsCount) {
  3905. this._renderedCapability.resolve();
  3906. if (attachmentsCount === 0 && !this._pendingDispatchEvent) {
  3907. this._pendingDispatchEvent = true;
  3908. await waitOnEventOrTimeout({
  3909. target: this.eventBus,
  3910. name: "annotationlayerrendered",
  3911. delay: 1000
  3912. });
  3913. if (!this._pendingDispatchEvent) {
  3914. return;
  3915. }
  3916. }
  3917. this._pendingDispatchEvent = false;
  3918. this.eventBus.dispatch("attachmentsloaded", {
  3919. source: this,
  3920. attachmentsCount
  3921. });
  3922. }
  3923. _bindLink(element, {
  3924. content,
  3925. description,
  3926. filename
  3927. }) {
  3928. if (description) {
  3929. element.title = description;
  3930. }
  3931. element.onclick = () => {
  3932. this.downloadManager.openOrDownloadData(content, filename);
  3933. return false;
  3934. };
  3935. }
  3936. render({
  3937. attachments,
  3938. keepRenderedCapability = false
  3939. }) {
  3940. if (this._attachments) {
  3941. this.reset(keepRenderedCapability);
  3942. }
  3943. this._attachments = attachments || null;
  3944. if (!attachments) {
  3945. this._dispatchEvent(0);
  3946. return;
  3947. }
  3948. const fragment = document.createDocumentFragment();
  3949. let attachmentsCount = 0;
  3950. for (const name in attachments) {
  3951. const item = attachments[name];
  3952. const div = document.createElement("div");
  3953. div.className = "treeItem";
  3954. const element = document.createElement("a");
  3955. this._bindLink(element, item);
  3956. element.textContent = this._normalizeTextContent(item.filename);
  3957. div.append(element);
  3958. fragment.append(div);
  3959. attachmentsCount++;
  3960. }
  3961. this._finishRendering(fragment, attachmentsCount);
  3962. }
  3963. #appendAttachment(item) {
  3964. const renderedPromise = this._renderedCapability.promise;
  3965. renderedPromise.then(() => {
  3966. if (renderedPromise !== this._renderedCapability.promise) {
  3967. return;
  3968. }
  3969. const attachments = this._attachments || Object.create(null);
  3970. for (const name in attachments) {
  3971. if (item.filename === name) {
  3972. return;
  3973. }
  3974. }
  3975. attachments[item.filename] = item;
  3976. this.render({
  3977. attachments,
  3978. keepRenderedCapability: true
  3979. });
  3980. });
  3981. }
  3982. }
  3983. ;// CONCATENATED MODULE: ./web/grab_to_pan.js
  3984. const CSS_CLASS_GRAB = "grab-to-pan-grab";
  3985. class GrabToPan {
  3986. constructor({
  3987. element
  3988. }) {
  3989. this.element = element;
  3990. this.document = element.ownerDocument;
  3991. this.activate = this.activate.bind(this);
  3992. this.deactivate = this.deactivate.bind(this);
  3993. this.toggle = this.toggle.bind(this);
  3994. this._onMouseDown = this.#onMouseDown.bind(this);
  3995. this._onMouseMove = this.#onMouseMove.bind(this);
  3996. this._endPan = this.#endPan.bind(this);
  3997. const overlay = this.overlay = document.createElement("div");
  3998. overlay.className = "grab-to-pan-grabbing";
  3999. }
  4000. activate() {
  4001. if (!this.active) {
  4002. this.active = true;
  4003. this.element.addEventListener("mousedown", this._onMouseDown, true);
  4004. this.element.classList.add(CSS_CLASS_GRAB);
  4005. }
  4006. }
  4007. deactivate() {
  4008. if (this.active) {
  4009. this.active = false;
  4010. this.element.removeEventListener("mousedown", this._onMouseDown, true);
  4011. this._endPan();
  4012. this.element.classList.remove(CSS_CLASS_GRAB);
  4013. }
  4014. }
  4015. toggle() {
  4016. if (this.active) {
  4017. this.deactivate();
  4018. } else {
  4019. this.activate();
  4020. }
  4021. }
  4022. ignoreTarget(node) {
  4023. return node.matches("a[href], a[href] *, input, textarea, button, button *, select, option");
  4024. }
  4025. #onMouseDown(event) {
  4026. if (event.button !== 0 || this.ignoreTarget(event.target)) {
  4027. return;
  4028. }
  4029. if (event.originalTarget) {
  4030. try {
  4031. event.originalTarget.tagName;
  4032. } catch {
  4033. return;
  4034. }
  4035. }
  4036. this.scrollLeftStart = this.element.scrollLeft;
  4037. this.scrollTopStart = this.element.scrollTop;
  4038. this.clientXStart = event.clientX;
  4039. this.clientYStart = event.clientY;
  4040. this.document.addEventListener("mousemove", this._onMouseMove, true);
  4041. this.document.addEventListener("mouseup", this._endPan, true);
  4042. this.element.addEventListener("scroll", this._endPan, true);
  4043. event.preventDefault();
  4044. event.stopPropagation();
  4045. const focusedElement = document.activeElement;
  4046. if (focusedElement && !focusedElement.contains(event.target)) {
  4047. focusedElement.blur();
  4048. }
  4049. }
  4050. #onMouseMove(event) {
  4051. this.element.removeEventListener("scroll", this._endPan, true);
  4052. if (!(event.buttons & 1)) {
  4053. this._endPan();
  4054. return;
  4055. }
  4056. const xDiff = event.clientX - this.clientXStart;
  4057. const yDiff = event.clientY - this.clientYStart;
  4058. this.element.scrollTo({
  4059. top: this.scrollTopStart - yDiff,
  4060. left: this.scrollLeftStart - xDiff,
  4061. behavior: "instant"
  4062. });
  4063. if (!this.overlay.parentNode) {
  4064. document.body.append(this.overlay);
  4065. }
  4066. }
  4067. #endPan() {
  4068. this.element.removeEventListener("scroll", this._endPan, true);
  4069. this.document.removeEventListener("mousemove", this._onMouseMove, true);
  4070. this.document.removeEventListener("mouseup", this._endPan, true);
  4071. this.overlay.remove();
  4072. }
  4073. }
  4074. ;// CONCATENATED MODULE: ./web/pdf_cursor_tools.js
  4075. class PDFCursorTools {
  4076. #active = CursorTool.SELECT;
  4077. #prevActive = null;
  4078. constructor({
  4079. container,
  4080. eventBus,
  4081. cursorToolOnLoad = CursorTool.SELECT
  4082. }) {
  4083. this.container = container;
  4084. this.eventBus = eventBus;
  4085. this.#addEventListeners();
  4086. Promise.resolve().then(() => {
  4087. this.switchTool(cursorToolOnLoad);
  4088. });
  4089. }
  4090. get activeTool() {
  4091. return this.#active;
  4092. }
  4093. switchTool(tool) {
  4094. if (this.#prevActive !== null) {
  4095. return;
  4096. }
  4097. if (tool === this.#active) {
  4098. return;
  4099. }
  4100. const disableActiveTool = () => {
  4101. switch (this.#active) {
  4102. case CursorTool.SELECT:
  4103. break;
  4104. case CursorTool.HAND:
  4105. this._handTool.deactivate();
  4106. break;
  4107. case CursorTool.ZOOM:
  4108. }
  4109. };
  4110. switch (tool) {
  4111. case CursorTool.SELECT:
  4112. disableActiveTool();
  4113. break;
  4114. case CursorTool.HAND:
  4115. disableActiveTool();
  4116. this._handTool.activate();
  4117. break;
  4118. case CursorTool.ZOOM:
  4119. default:
  4120. console.error(`switchTool: "${tool}" is an unsupported value.`);
  4121. return;
  4122. }
  4123. this.#active = tool;
  4124. this.eventBus.dispatch("cursortoolchanged", {
  4125. source: this,
  4126. tool
  4127. });
  4128. }
  4129. #addEventListeners() {
  4130. this.eventBus._on("switchcursortool", evt => {
  4131. if (!evt.reset) {
  4132. this.switchTool(evt.tool);
  4133. } else if (this.#prevActive !== null) {
  4134. annotationEditorMode = AnnotationEditorType.NONE;
  4135. presentationModeState = PresentationModeState.NORMAL;
  4136. enableActive();
  4137. }
  4138. });
  4139. let annotationEditorMode = AnnotationEditorType.NONE,
  4140. presentationModeState = PresentationModeState.NORMAL;
  4141. const disableActive = () => {
  4142. const prevActive = this.#active;
  4143. this.switchTool(CursorTool.SELECT);
  4144. this.#prevActive ??= prevActive;
  4145. };
  4146. const enableActive = () => {
  4147. const prevActive = this.#prevActive;
  4148. if (prevActive !== null && annotationEditorMode === AnnotationEditorType.NONE && presentationModeState === PresentationModeState.NORMAL) {
  4149. this.#prevActive = null;
  4150. this.switchTool(prevActive);
  4151. }
  4152. };
  4153. this.eventBus._on("annotationeditormodechanged", ({
  4154. mode
  4155. }) => {
  4156. annotationEditorMode = mode;
  4157. if (mode === AnnotationEditorType.NONE) {
  4158. enableActive();
  4159. } else {
  4160. disableActive();
  4161. }
  4162. });
  4163. this.eventBus._on("presentationmodechanged", ({
  4164. state
  4165. }) => {
  4166. presentationModeState = state;
  4167. if (state === PresentationModeState.NORMAL) {
  4168. enableActive();
  4169. } else if (state === PresentationModeState.FULLSCREEN) {
  4170. disableActive();
  4171. }
  4172. });
  4173. }
  4174. get _handTool() {
  4175. return shadow(this, "_handTool", new GrabToPan({
  4176. element: this.container
  4177. }));
  4178. }
  4179. }
  4180. ;// CONCATENATED MODULE: ./web/pdf_document_properties.js
  4181. const DEFAULT_FIELD_CONTENT = "-";
  4182. const NON_METRIC_LOCALES = ["en-us", "en-lr", "my"];
  4183. const US_PAGE_NAMES = {
  4184. "8.5x11": "letter",
  4185. "8.5x14": "legal"
  4186. };
  4187. const METRIC_PAGE_NAMES = {
  4188. "297x420": "a-three",
  4189. "210x297": "a-four"
  4190. };
  4191. function getPageName(size, isPortrait, pageNames) {
  4192. const width = isPortrait ? size.width : size.height;
  4193. const height = isPortrait ? size.height : size.width;
  4194. return pageNames[`${width}x${height}`];
  4195. }
  4196. class PDFDocumentProperties {
  4197. #fieldData = null;
  4198. constructor({
  4199. dialog,
  4200. fields,
  4201. closeButton
  4202. }, overlayManager, eventBus, l10n, fileNameLookup) {
  4203. this.dialog = dialog;
  4204. this.fields = fields;
  4205. this.overlayManager = overlayManager;
  4206. this.l10n = l10n;
  4207. this._fileNameLookup = fileNameLookup;
  4208. this.#reset();
  4209. closeButton.addEventListener("click", this.close.bind(this));
  4210. this.overlayManager.register(this.dialog);
  4211. eventBus._on("pagechanging", evt => {
  4212. this._currentPageNumber = evt.pageNumber;
  4213. });
  4214. eventBus._on("rotationchanging", evt => {
  4215. this._pagesRotation = evt.pagesRotation;
  4216. });
  4217. this._isNonMetricLocale = NON_METRIC_LOCALES.includes(l10n.getLanguage());
  4218. }
  4219. async open() {
  4220. await Promise.all([this.overlayManager.open(this.dialog), this._dataAvailableCapability.promise]);
  4221. const currentPageNumber = this._currentPageNumber;
  4222. const pagesRotation = this._pagesRotation;
  4223. if (this.#fieldData && currentPageNumber === this.#fieldData._currentPageNumber && pagesRotation === this.#fieldData._pagesRotation) {
  4224. this.#updateUI();
  4225. return;
  4226. }
  4227. const {
  4228. info,
  4229. contentLength
  4230. } = await this.pdfDocument.getMetadata();
  4231. const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([this._fileNameLookup(), this.#parseFileSize(contentLength), this.#parseDate(info.CreationDate), this.#parseDate(info.ModDate), this.pdfDocument.getPage(currentPageNumber).then(pdfPage => {
  4232. return this.#parsePageSize(getPageSizeInches(pdfPage), pagesRotation);
  4233. }), this.#parseLinearization(info.IsLinearized)]);
  4234. this.#fieldData = Object.freeze({
  4235. fileName,
  4236. fileSize,
  4237. title: info.Title,
  4238. author: info.Author,
  4239. subject: info.Subject,
  4240. keywords: info.Keywords,
  4241. creationDate,
  4242. modificationDate,
  4243. creator: info.Creator,
  4244. producer: info.Producer,
  4245. version: info.PDFFormatVersion,
  4246. pageCount: this.pdfDocument.numPages,
  4247. pageSize,
  4248. linearized: isLinearized,
  4249. _currentPageNumber: currentPageNumber,
  4250. _pagesRotation: pagesRotation
  4251. });
  4252. this.#updateUI();
  4253. const {
  4254. length
  4255. } = await this.pdfDocument.getDownloadInfo();
  4256. if (contentLength === length) {
  4257. return;
  4258. }
  4259. const data = Object.assign(Object.create(null), this.#fieldData);
  4260. data.fileSize = await this.#parseFileSize(length);
  4261. this.#fieldData = Object.freeze(data);
  4262. this.#updateUI();
  4263. }
  4264. async close() {
  4265. this.overlayManager.close(this.dialog);
  4266. }
  4267. setDocument(pdfDocument) {
  4268. if (this.pdfDocument) {
  4269. this.#reset();
  4270. this.#updateUI(true);
  4271. }
  4272. if (!pdfDocument) {
  4273. return;
  4274. }
  4275. this.pdfDocument = pdfDocument;
  4276. this._dataAvailableCapability.resolve();
  4277. }
  4278. #reset() {
  4279. this.pdfDocument = null;
  4280. this.#fieldData = null;
  4281. this._dataAvailableCapability = Promise.withResolvers();
  4282. this._currentPageNumber = 1;
  4283. this._pagesRotation = 0;
  4284. }
  4285. #updateUI(reset = false) {
  4286. if (reset || !this.#fieldData) {
  4287. for (const id in this.fields) {
  4288. this.fields[id].textContent = DEFAULT_FIELD_CONTENT;
  4289. }
  4290. return;
  4291. }
  4292. if (this.overlayManager.active !== this.dialog) {
  4293. return;
  4294. }
  4295. for (const id in this.fields) {
  4296. const content = this.#fieldData[id];
  4297. this.fields[id].textContent = content || content === 0 ? content : DEFAULT_FIELD_CONTENT;
  4298. }
  4299. }
  4300. async #parseFileSize(fileSize = 0) {
  4301. const kb = fileSize / 1024,
  4302. mb = kb / 1024;
  4303. if (!kb) {
  4304. return undefined;
  4305. }
  4306. return this.l10n.get(`pdfjs-document-properties-${mb >= 1 ? "mb" : "kb"}`, {
  4307. size_mb: mb >= 1 && (+mb.toPrecision(3)).toLocaleString(),
  4308. size_kb: mb < 1 && (+kb.toPrecision(3)).toLocaleString(),
  4309. size_b: fileSize.toLocaleString()
  4310. });
  4311. }
  4312. async #parsePageSize(pageSizeInches, pagesRotation) {
  4313. if (!pageSizeInches) {
  4314. return undefined;
  4315. }
  4316. if (pagesRotation % 180 !== 0) {
  4317. pageSizeInches = {
  4318. width: pageSizeInches.height,
  4319. height: pageSizeInches.width
  4320. };
  4321. }
  4322. const isPortrait = isPortraitOrientation(pageSizeInches);
  4323. let sizeInches = {
  4324. width: Math.round(pageSizeInches.width * 100) / 100,
  4325. height: Math.round(pageSizeInches.height * 100) / 100
  4326. };
  4327. let sizeMillimeters = {
  4328. width: Math.round(pageSizeInches.width * 25.4 * 10) / 10,
  4329. height: Math.round(pageSizeInches.height * 25.4 * 10) / 10
  4330. };
  4331. let rawName = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES);
  4332. if (!rawName && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) {
  4333. const exactMillimeters = {
  4334. width: pageSizeInches.width * 25.4,
  4335. height: pageSizeInches.height * 25.4
  4336. };
  4337. const intMillimeters = {
  4338. width: Math.round(sizeMillimeters.width),
  4339. height: Math.round(sizeMillimeters.height)
  4340. };
  4341. if (Math.abs(exactMillimeters.width - intMillimeters.width) < 0.1 && Math.abs(exactMillimeters.height - intMillimeters.height) < 0.1) {
  4342. rawName = getPageName(intMillimeters, isPortrait, METRIC_PAGE_NAMES);
  4343. if (rawName) {
  4344. sizeInches = {
  4345. width: Math.round(intMillimeters.width / 25.4 * 100) / 100,
  4346. height: Math.round(intMillimeters.height / 25.4 * 100) / 100
  4347. };
  4348. sizeMillimeters = intMillimeters;
  4349. }
  4350. }
  4351. }
  4352. const [{
  4353. width,
  4354. height
  4355. }, unit, name, orientation] = await Promise.all([this._isNonMetricLocale ? sizeInches : sizeMillimeters, this.l10n.get(`pdfjs-document-properties-page-size-unit-${this._isNonMetricLocale ? "inches" : "millimeters"}`), rawName && this.l10n.get(`pdfjs-document-properties-page-size-name-${rawName}`), this.l10n.get(`pdfjs-document-properties-page-size-orientation-${isPortrait ? "portrait" : "landscape"}`)]);
  4356. return this.l10n.get(`pdfjs-document-properties-page-size-dimension-${name ? "name-" : ""}string`, {
  4357. width: width.toLocaleString(),
  4358. height: height.toLocaleString(),
  4359. unit,
  4360. name,
  4361. orientation
  4362. });
  4363. }
  4364. async #parseDate(inputDate) {
  4365. const dateObject = PDFDateString.toDateObject(inputDate);
  4366. if (!dateObject) {
  4367. return undefined;
  4368. }
  4369. return this.l10n.get("pdfjs-document-properties-date-string", {
  4370. date: dateObject.toLocaleDateString(),
  4371. time: dateObject.toLocaleTimeString()
  4372. });
  4373. }
  4374. #parseLinearization(isLinearized) {
  4375. return this.l10n.get(`pdfjs-document-properties-linearized-${isLinearized ? "yes" : "no"}`);
  4376. }
  4377. }
  4378. ;// CONCATENATED MODULE: ./web/pdf_find_utils.js
  4379. const CharacterType = {
  4380. SPACE: 0,
  4381. ALPHA_LETTER: 1,
  4382. PUNCT: 2,
  4383. HAN_LETTER: 3,
  4384. KATAKANA_LETTER: 4,
  4385. HIRAGANA_LETTER: 5,
  4386. HALFWIDTH_KATAKANA_LETTER: 6,
  4387. THAI_LETTER: 7
  4388. };
  4389. function isAlphabeticalScript(charCode) {
  4390. return charCode < 0x2e80;
  4391. }
  4392. function isAscii(charCode) {
  4393. return (charCode & 0xff80) === 0;
  4394. }
  4395. function isAsciiAlpha(charCode) {
  4396. return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a;
  4397. }
  4398. function isAsciiDigit(charCode) {
  4399. return charCode >= 0x30 && charCode <= 0x39;
  4400. }
  4401. function isAsciiSpace(charCode) {
  4402. return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a;
  4403. }
  4404. function isHan(charCode) {
  4405. return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff;
  4406. }
  4407. function isKatakana(charCode) {
  4408. return charCode >= 0x30a0 && charCode <= 0x30ff;
  4409. }
  4410. function isHiragana(charCode) {
  4411. return charCode >= 0x3040 && charCode <= 0x309f;
  4412. }
  4413. function isHalfwidthKatakana(charCode) {
  4414. return charCode >= 0xff60 && charCode <= 0xff9f;
  4415. }
  4416. function isThai(charCode) {
  4417. return (charCode & 0xff80) === 0x0e00;
  4418. }
  4419. function getCharacterType(charCode) {
  4420. if (isAlphabeticalScript(charCode)) {
  4421. if (isAscii(charCode)) {
  4422. if (isAsciiSpace(charCode)) {
  4423. return CharacterType.SPACE;
  4424. } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) {
  4425. return CharacterType.ALPHA_LETTER;
  4426. }
  4427. return CharacterType.PUNCT;
  4428. } else if (isThai(charCode)) {
  4429. return CharacterType.THAI_LETTER;
  4430. } else if (charCode === 0xa0) {
  4431. return CharacterType.SPACE;
  4432. }
  4433. return CharacterType.ALPHA_LETTER;
  4434. }
  4435. if (isHan(charCode)) {
  4436. return CharacterType.HAN_LETTER;
  4437. } else if (isKatakana(charCode)) {
  4438. return CharacterType.KATAKANA_LETTER;
  4439. } else if (isHiragana(charCode)) {
  4440. return CharacterType.HIRAGANA_LETTER;
  4441. } else if (isHalfwidthKatakana(charCode)) {
  4442. return CharacterType.HALFWIDTH_KATAKANA_LETTER;
  4443. }
  4444. return CharacterType.ALPHA_LETTER;
  4445. }
  4446. let NormalizeWithNFKC;
  4447. function getNormalizeWithNFKC() {
  4448. NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`;
  4449. return NormalizeWithNFKC;
  4450. }
  4451. ;// CONCATENATED MODULE: ./web/pdf_find_controller.js
  4452. const FindState = {
  4453. FOUND: 0,
  4454. NOT_FOUND: 1,
  4455. WRAPPED: 2,
  4456. PENDING: 3
  4457. };
  4458. const FIND_TIMEOUT = 250;
  4459. const MATCH_SCROLL_OFFSET_TOP = -50;
  4460. const MATCH_SCROLL_OFFSET_LEFT = -400;
  4461. const CHARACTERS_TO_NORMALIZE = {
  4462. "\u2010": "-",
  4463. "\u2018": "'",
  4464. "\u2019": "'",
  4465. "\u201A": "'",
  4466. "\u201B": "'",
  4467. "\u201C": '"',
  4468. "\u201D": '"',
  4469. "\u201E": '"',
  4470. "\u201F": '"',
  4471. "\u00BC": "1/4",
  4472. "\u00BD": "1/2",
  4473. "\u00BE": "3/4"
  4474. };
  4475. const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]);
  4476. let DIACRITICS_EXCEPTION_STR;
  4477. const DIACRITICS_REG_EXP = /\p{M}+/gu;
  4478. const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu;
  4479. const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u;
  4480. const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u;
  4481. const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g;
  4482. const SYLLABLES_LENGTHS = new Map();
  4483. const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]";
  4484. const NFKC_CHARS_TO_NORMALIZE = new Map();
  4485. let noSyllablesRegExp = null;
  4486. let withSyllablesRegExp = null;
  4487. function normalize(text) {
  4488. const syllablePositions = [];
  4489. let m;
  4490. while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) {
  4491. let {
  4492. index
  4493. } = m;
  4494. for (const char of m[0]) {
  4495. let len = SYLLABLES_LENGTHS.get(char);
  4496. if (!len) {
  4497. len = char.normalize("NFD").length;
  4498. SYLLABLES_LENGTHS.set(char, len);
  4499. }
  4500. syllablePositions.push([len, index++]);
  4501. }
  4502. }
  4503. let normalizationRegex;
  4504. if (syllablePositions.length === 0 && noSyllablesRegExp) {
  4505. normalizationRegex = noSyllablesRegExp;
  4506. } else if (syllablePositions.length > 0 && withSyllablesRegExp) {
  4507. normalizationRegex = withSyllablesRegExp;
  4508. } else {
  4509. const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join("");
  4510. const toNormalizeWithNFKC = getNormalizeWithNFKC();
  4511. const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])";
  4512. const HKDiacritics = "(?:\u3099|\u309A)";
  4513. const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(\\S-\\n)|(${CJK}\\n)|(\\n)`;
  4514. if (syllablePositions.length === 0) {
  4515. normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum");
  4516. } else {
  4517. normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum");
  4518. }
  4519. }
  4520. const rawDiacriticsPositions = [];
  4521. while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) {
  4522. rawDiacriticsPositions.push([m[0].length, m.index]);
  4523. }
  4524. let normalized = text.normalize("NFD");
  4525. const positions = [[0, 0]];
  4526. let rawDiacriticsIndex = 0;
  4527. let syllableIndex = 0;
  4528. let shift = 0;
  4529. let shiftOrigin = 0;
  4530. let eol = 0;
  4531. let hasDiacritics = false;
  4532. normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, i) => {
  4533. i -= shiftOrigin;
  4534. if (p1) {
  4535. const replacement = CHARACTERS_TO_NORMALIZE[p1];
  4536. const jj = replacement.length;
  4537. for (let j = 1; j < jj; j++) {
  4538. positions.push([i - shift + j, shift - j]);
  4539. }
  4540. shift -= jj - 1;
  4541. return replacement;
  4542. }
  4543. if (p2) {
  4544. let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2);
  4545. if (!replacement) {
  4546. replacement = p2.normalize("NFKC");
  4547. NFKC_CHARS_TO_NORMALIZE.set(p2, replacement);
  4548. }
  4549. const jj = replacement.length;
  4550. for (let j = 1; j < jj; j++) {
  4551. positions.push([i - shift + j, shift - j]);
  4552. }
  4553. shift -= jj - 1;
  4554. return replacement;
  4555. }
  4556. if (p3) {
  4557. hasDiacritics = true;
  4558. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  4559. ++rawDiacriticsIndex;
  4560. } else {
  4561. positions.push([i - 1 - shift + 1, shift - 1]);
  4562. shift -= 1;
  4563. shiftOrigin += 1;
  4564. }
  4565. positions.push([i - shift + 1, shift]);
  4566. shiftOrigin += 1;
  4567. eol += 1;
  4568. return p3.charAt(0);
  4569. }
  4570. if (p4) {
  4571. const hasTrailingDashEOL = p4.endsWith("\n");
  4572. const len = hasTrailingDashEOL ? p4.length - 2 : p4.length;
  4573. hasDiacritics = true;
  4574. let jj = len;
  4575. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  4576. jj -= rawDiacriticsPositions[rawDiacriticsIndex][0];
  4577. ++rawDiacriticsIndex;
  4578. }
  4579. for (let j = 1; j <= jj; j++) {
  4580. positions.push([i - 1 - shift + j, shift - j]);
  4581. }
  4582. shift -= jj;
  4583. shiftOrigin += jj;
  4584. if (hasTrailingDashEOL) {
  4585. i += len - 1;
  4586. positions.push([i - shift + 1, 1 + shift]);
  4587. shift += 1;
  4588. shiftOrigin += 1;
  4589. eol += 1;
  4590. return p4.slice(0, len);
  4591. }
  4592. return p4;
  4593. }
  4594. if (p5) {
  4595. const len = p5.length - 2;
  4596. positions.push([i - shift + len, 1 + shift]);
  4597. shift += 1;
  4598. shiftOrigin += 1;
  4599. eol += 1;
  4600. return p5.slice(0, -2);
  4601. }
  4602. if (p6) {
  4603. const len = p6.length - 1;
  4604. positions.push([i - shift + len, shift]);
  4605. shiftOrigin += 1;
  4606. eol += 1;
  4607. return p6.slice(0, -1);
  4608. }
  4609. if (p7) {
  4610. positions.push([i - shift + 1, shift - 1]);
  4611. shift -= 1;
  4612. shiftOrigin += 1;
  4613. eol += 1;
  4614. return " ";
  4615. }
  4616. if (i + eol === syllablePositions[syllableIndex]?.[1]) {
  4617. const newCharLen = syllablePositions[syllableIndex][0] - 1;
  4618. ++syllableIndex;
  4619. for (let j = 1; j <= newCharLen; j++) {
  4620. positions.push([i - (shift - j), shift - j]);
  4621. }
  4622. shift -= newCharLen;
  4623. shiftOrigin += newCharLen;
  4624. }
  4625. return p8;
  4626. });
  4627. positions.push([normalized.length, shift]);
  4628. return [normalized, positions, hasDiacritics];
  4629. }
  4630. function getOriginalIndex(diffs, pos, len) {
  4631. if (!diffs) {
  4632. return [pos, len];
  4633. }
  4634. const start = pos;
  4635. const end = pos + len - 1;
  4636. let i = binarySearchFirstItem(diffs, x => x[0] >= start);
  4637. if (diffs[i][0] > start) {
  4638. --i;
  4639. }
  4640. let j = binarySearchFirstItem(diffs, x => x[0] >= end, i);
  4641. if (diffs[j][0] > end) {
  4642. --j;
  4643. }
  4644. const oldStart = start + diffs[i][1];
  4645. const oldEnd = end + diffs[j][1];
  4646. const oldLen = oldEnd + 1 - oldStart;
  4647. return [oldStart, oldLen];
  4648. }
  4649. class PDFFindController {
  4650. #state = null;
  4651. #updateMatchesCountOnProgress = true;
  4652. #visitedPagesCount = 0;
  4653. constructor({
  4654. linkService,
  4655. eventBus,
  4656. updateMatchesCountOnProgress = true
  4657. }) {
  4658. this._linkService = linkService;
  4659. this._eventBus = eventBus;
  4660. this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress;
  4661. this.onIsPageVisible = null;
  4662. this.#reset();
  4663. eventBus._on("find", this.#onFind.bind(this));
  4664. eventBus._on("findbarclose", this.#onFindBarClose.bind(this));
  4665. }
  4666. get highlightMatches() {
  4667. return this._highlightMatches;
  4668. }
  4669. get pageMatches() {
  4670. return this._pageMatches;
  4671. }
  4672. get pageMatchesLength() {
  4673. return this._pageMatchesLength;
  4674. }
  4675. get selected() {
  4676. return this._selected;
  4677. }
  4678. get state() {
  4679. return this.#state;
  4680. }
  4681. setDocument(pdfDocument) {
  4682. if (this._pdfDocument) {
  4683. this.#reset();
  4684. }
  4685. if (!pdfDocument) {
  4686. return;
  4687. }
  4688. this._pdfDocument = pdfDocument;
  4689. this._firstPageCapability.resolve();
  4690. }
  4691. #onFind(state) {
  4692. if (!state) {
  4693. return;
  4694. }
  4695. const pdfDocument = this._pdfDocument;
  4696. const {
  4697. type
  4698. } = state;
  4699. if (this.#state === null || this.#shouldDirtyMatch(state)) {
  4700. this._dirtyMatch = true;
  4701. }
  4702. this.#state = state;
  4703. if (type !== "highlightallchange") {
  4704. this.#updateUIState(FindState.PENDING);
  4705. }
  4706. this._firstPageCapability.promise.then(() => {
  4707. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  4708. return;
  4709. }
  4710. this.#extractText();
  4711. const findbarClosed = !this._highlightMatches;
  4712. const pendingTimeout = !!this._findTimeout;
  4713. if (this._findTimeout) {
  4714. clearTimeout(this._findTimeout);
  4715. this._findTimeout = null;
  4716. }
  4717. if (!type) {
  4718. this._findTimeout = setTimeout(() => {
  4719. this.#nextMatch();
  4720. this._findTimeout = null;
  4721. }, FIND_TIMEOUT);
  4722. } else if (this._dirtyMatch) {
  4723. this.#nextMatch();
  4724. } else if (type === "again") {
  4725. this.#nextMatch();
  4726. if (findbarClosed && this.#state.highlightAll) {
  4727. this.#updateAllPages();
  4728. }
  4729. } else if (type === "highlightallchange") {
  4730. if (pendingTimeout) {
  4731. this.#nextMatch();
  4732. } else {
  4733. this._highlightMatches = true;
  4734. }
  4735. this.#updateAllPages();
  4736. } else {
  4737. this.#nextMatch();
  4738. }
  4739. });
  4740. }
  4741. scrollMatchIntoView({
  4742. element = null,
  4743. selectedLeft = 0,
  4744. pageIndex = -1,
  4745. matchIndex = -1
  4746. }) {
  4747. if (!this._scrollMatches || !element) {
  4748. return;
  4749. } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) {
  4750. return;
  4751. } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) {
  4752. return;
  4753. }
  4754. this._scrollMatches = false;
  4755. const spot = {
  4756. top: MATCH_SCROLL_OFFSET_TOP,
  4757. left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT
  4758. };
  4759. scrollIntoView(element, spot, true);
  4760. }
  4761. #reset() {
  4762. this._highlightMatches = false;
  4763. this._scrollMatches = false;
  4764. this._pdfDocument = null;
  4765. this._pageMatches = [];
  4766. this._pageMatchesLength = [];
  4767. this.#visitedPagesCount = 0;
  4768. this.#state = null;
  4769. this._selected = {
  4770. pageIdx: -1,
  4771. matchIdx: -1
  4772. };
  4773. this._offset = {
  4774. pageIdx: null,
  4775. matchIdx: null,
  4776. wrapped: false
  4777. };
  4778. this._extractTextPromises = [];
  4779. this._pageContents = [];
  4780. this._pageDiffs = [];
  4781. this._hasDiacritics = [];
  4782. this._matchesCountTotal = 0;
  4783. this._pagesToSearch = null;
  4784. this._pendingFindMatches = new Set();
  4785. this._resumePageIdx = null;
  4786. this._dirtyMatch = false;
  4787. clearTimeout(this._findTimeout);
  4788. this._findTimeout = null;
  4789. this._firstPageCapability = Promise.withResolvers();
  4790. }
  4791. get #query() {
  4792. const {
  4793. query
  4794. } = this.#state;
  4795. if (typeof query === "string") {
  4796. if (query !== this._rawQuery) {
  4797. this._rawQuery = query;
  4798. [this._normalizedQuery] = normalize(query);
  4799. }
  4800. return this._normalizedQuery;
  4801. }
  4802. return (query || []).filter(q => !!q).map(q => normalize(q)[0]);
  4803. }
  4804. #shouldDirtyMatch(state) {
  4805. const newQuery = state.query,
  4806. prevQuery = this.#state.query;
  4807. const newType = typeof newQuery,
  4808. prevType = typeof prevQuery;
  4809. if (newType !== prevType) {
  4810. return true;
  4811. }
  4812. if (newType === "string") {
  4813. if (newQuery !== prevQuery) {
  4814. return true;
  4815. }
  4816. } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) {
  4817. return true;
  4818. }
  4819. switch (state.type) {
  4820. case "again":
  4821. const pageNumber = this._selected.pageIdx + 1;
  4822. const linkService = this._linkService;
  4823. return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true);
  4824. case "highlightallchange":
  4825. return false;
  4826. }
  4827. return true;
  4828. }
  4829. #isEntireWord(content, startIdx, length) {
  4830. let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP);
  4831. if (match) {
  4832. const first = content.charCodeAt(startIdx);
  4833. const limit = match[1].charCodeAt(0);
  4834. if (getCharacterType(first) === getCharacterType(limit)) {
  4835. return false;
  4836. }
  4837. }
  4838. match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP);
  4839. if (match) {
  4840. const last = content.charCodeAt(startIdx + length - 1);
  4841. const limit = match[1].charCodeAt(0);
  4842. if (getCharacterType(last) === getCharacterType(limit)) {
  4843. return false;
  4844. }
  4845. }
  4846. return true;
  4847. }
  4848. #calculateRegExpMatch(query, entireWord, pageIndex, pageContent) {
  4849. const matches = this._pageMatches[pageIndex] = [];
  4850. const matchesLength = this._pageMatchesLength[pageIndex] = [];
  4851. if (!query) {
  4852. return;
  4853. }
  4854. const diffs = this._pageDiffs[pageIndex];
  4855. let match;
  4856. while ((match = query.exec(pageContent)) !== null) {
  4857. if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) {
  4858. continue;
  4859. }
  4860. const [matchPos, matchLen] = getOriginalIndex(diffs, match.index, match[0].length);
  4861. if (matchLen) {
  4862. matches.push(matchPos);
  4863. matchesLength.push(matchLen);
  4864. }
  4865. }
  4866. }
  4867. #convertToRegExpString(query, hasDiacritics) {
  4868. const {
  4869. matchDiacritics
  4870. } = this.#state;
  4871. let isUnicode = false;
  4872. query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => {
  4873. if (p1) {
  4874. return `[ ]*\\${p1}[ ]*`;
  4875. }
  4876. if (p2) {
  4877. return `[ ]*${p2}[ ]*`;
  4878. }
  4879. if (p3) {
  4880. return "[ ]+";
  4881. }
  4882. if (matchDiacritics) {
  4883. return p4 || p5;
  4884. }
  4885. if (p4) {
  4886. return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : "";
  4887. }
  4888. if (hasDiacritics) {
  4889. isUnicode = true;
  4890. return `${p5}\\p{M}*`;
  4891. }
  4892. return p5;
  4893. });
  4894. const trailingSpaces = "[ ]*";
  4895. if (query.endsWith(trailingSpaces)) {
  4896. query = query.slice(0, query.length - trailingSpaces.length);
  4897. }
  4898. if (matchDiacritics) {
  4899. if (hasDiacritics) {
  4900. DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION);
  4901. isUnicode = true;
  4902. query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`;
  4903. }
  4904. }
  4905. return [isUnicode, query];
  4906. }
  4907. #calculateMatch(pageIndex) {
  4908. let query = this.#query;
  4909. if (query.length === 0) {
  4910. return;
  4911. }
  4912. const {
  4913. caseSensitive,
  4914. entireWord
  4915. } = this.#state;
  4916. const pageContent = this._pageContents[pageIndex];
  4917. const hasDiacritics = this._hasDiacritics[pageIndex];
  4918. let isUnicode = false;
  4919. if (typeof query === "string") {
  4920. [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics);
  4921. } else {
  4922. query = query.sort().reverse().map(q => {
  4923. const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics);
  4924. isUnicode ||= isUnicodePart;
  4925. return `(${queryPart})`;
  4926. }).join("|");
  4927. }
  4928. const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`;
  4929. query = query ? new RegExp(query, flags) : null;
  4930. this.#calculateRegExpMatch(query, entireWord, pageIndex, pageContent);
  4931. if (this.#state.highlightAll) {
  4932. this.#updatePage(pageIndex);
  4933. }
  4934. if (this._resumePageIdx === pageIndex) {
  4935. this._resumePageIdx = null;
  4936. this.#nextPageMatch();
  4937. }
  4938. const pageMatchesCount = this._pageMatches[pageIndex].length;
  4939. this._matchesCountTotal += pageMatchesCount;
  4940. if (this.#updateMatchesCountOnProgress) {
  4941. if (pageMatchesCount > 0) {
  4942. this.#updateUIResultsCount();
  4943. }
  4944. } else if (++this.#visitedPagesCount === this._linkService.pagesCount) {
  4945. this.#updateUIResultsCount();
  4946. }
  4947. }
  4948. #extractText() {
  4949. if (this._extractTextPromises.length > 0) {
  4950. return;
  4951. }
  4952. let deferred = Promise.resolve();
  4953. const textOptions = {
  4954. disableNormalization: true
  4955. };
  4956. for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) {
  4957. const {
  4958. promise,
  4959. resolve
  4960. } = Promise.withResolvers();
  4961. this._extractTextPromises[i] = promise;
  4962. deferred = deferred.then(() => {
  4963. return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => {
  4964. const strBuf = [];
  4965. for (const textItem of textContent.items) {
  4966. strBuf.push(textItem.str);
  4967. if (textItem.hasEOL) {
  4968. strBuf.push("\n");
  4969. }
  4970. }
  4971. [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join(""));
  4972. resolve();
  4973. }, reason => {
  4974. console.error(`Unable to get text content for page ${i + 1}`, reason);
  4975. this._pageContents[i] = "";
  4976. this._pageDiffs[i] = null;
  4977. this._hasDiacritics[i] = false;
  4978. resolve();
  4979. });
  4980. });
  4981. }
  4982. }
  4983. #updatePage(index) {
  4984. if (this._scrollMatches && this._selected.pageIdx === index) {
  4985. this._linkService.page = index + 1;
  4986. }
  4987. this._eventBus.dispatch("updatetextlayermatches", {
  4988. source: this,
  4989. pageIndex: index
  4990. });
  4991. }
  4992. #updateAllPages() {
  4993. this._eventBus.dispatch("updatetextlayermatches", {
  4994. source: this,
  4995. pageIndex: -1
  4996. });
  4997. }
  4998. #nextMatch() {
  4999. const previous = this.#state.findPrevious;
  5000. const currentPageIndex = this._linkService.page - 1;
  5001. const numPages = this._linkService.pagesCount;
  5002. this._highlightMatches = true;
  5003. if (this._dirtyMatch) {
  5004. this._dirtyMatch = false;
  5005. this._selected.pageIdx = this._selected.matchIdx = -1;
  5006. this._offset.pageIdx = currentPageIndex;
  5007. this._offset.matchIdx = null;
  5008. this._offset.wrapped = false;
  5009. this._resumePageIdx = null;
  5010. this._pageMatches.length = 0;
  5011. this._pageMatchesLength.length = 0;
  5012. this.#visitedPagesCount = 0;
  5013. this._matchesCountTotal = 0;
  5014. this.#updateAllPages();
  5015. for (let i = 0; i < numPages; i++) {
  5016. if (this._pendingFindMatches.has(i)) {
  5017. continue;
  5018. }
  5019. this._pendingFindMatches.add(i);
  5020. this._extractTextPromises[i].then(() => {
  5021. this._pendingFindMatches.delete(i);
  5022. this.#calculateMatch(i);
  5023. });
  5024. }
  5025. }
  5026. const query = this.#query;
  5027. if (query.length === 0) {
  5028. this.#updateUIState(FindState.FOUND);
  5029. return;
  5030. }
  5031. if (this._resumePageIdx) {
  5032. return;
  5033. }
  5034. const offset = this._offset;
  5035. this._pagesToSearch = numPages;
  5036. if (offset.matchIdx !== null) {
  5037. const numPageMatches = this._pageMatches[offset.pageIdx].length;
  5038. if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
  5039. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  5040. this.#updateMatch(true);
  5041. return;
  5042. }
  5043. this.#advanceOffsetPage(previous);
  5044. }
  5045. this.#nextPageMatch();
  5046. }
  5047. #matchesReady(matches) {
  5048. const offset = this._offset;
  5049. const numMatches = matches.length;
  5050. const previous = this.#state.findPrevious;
  5051. if (numMatches) {
  5052. offset.matchIdx = previous ? numMatches - 1 : 0;
  5053. this.#updateMatch(true);
  5054. return true;
  5055. }
  5056. this.#advanceOffsetPage(previous);
  5057. if (offset.wrapped) {
  5058. offset.matchIdx = null;
  5059. if (this._pagesToSearch < 0) {
  5060. this.#updateMatch(false);
  5061. return true;
  5062. }
  5063. }
  5064. return false;
  5065. }
  5066. #nextPageMatch() {
  5067. if (this._resumePageIdx !== null) {
  5068. console.error("There can only be one pending page.");
  5069. }
  5070. let matches = null;
  5071. do {
  5072. const pageIdx = this._offset.pageIdx;
  5073. matches = this._pageMatches[pageIdx];
  5074. if (!matches) {
  5075. this._resumePageIdx = pageIdx;
  5076. break;
  5077. }
  5078. } while (!this.#matchesReady(matches));
  5079. }
  5080. #advanceOffsetPage(previous) {
  5081. const offset = this._offset;
  5082. const numPages = this._linkService.pagesCount;
  5083. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  5084. offset.matchIdx = null;
  5085. this._pagesToSearch--;
  5086. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  5087. offset.pageIdx = previous ? numPages - 1 : 0;
  5088. offset.wrapped = true;
  5089. }
  5090. }
  5091. #updateMatch(found = false) {
  5092. let state = FindState.NOT_FOUND;
  5093. const wrapped = this._offset.wrapped;
  5094. this._offset.wrapped = false;
  5095. if (found) {
  5096. const previousPage = this._selected.pageIdx;
  5097. this._selected.pageIdx = this._offset.pageIdx;
  5098. this._selected.matchIdx = this._offset.matchIdx;
  5099. state = wrapped ? FindState.WRAPPED : FindState.FOUND;
  5100. if (previousPage !== -1 && previousPage !== this._selected.pageIdx) {
  5101. this.#updatePage(previousPage);
  5102. }
  5103. }
  5104. this.#updateUIState(state, this.#state.findPrevious);
  5105. if (this._selected.pageIdx !== -1) {
  5106. this._scrollMatches = true;
  5107. this.#updatePage(this._selected.pageIdx);
  5108. }
  5109. }
  5110. #onFindBarClose(evt) {
  5111. const pdfDocument = this._pdfDocument;
  5112. this._firstPageCapability.promise.then(() => {
  5113. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  5114. return;
  5115. }
  5116. if (this._findTimeout) {
  5117. clearTimeout(this._findTimeout);
  5118. this._findTimeout = null;
  5119. }
  5120. if (this._resumePageIdx) {
  5121. this._resumePageIdx = null;
  5122. this._dirtyMatch = true;
  5123. }
  5124. this.#updateUIState(FindState.FOUND);
  5125. this._highlightMatches = false;
  5126. this.#updateAllPages();
  5127. });
  5128. }
  5129. #requestMatchesCount() {
  5130. const {
  5131. pageIdx,
  5132. matchIdx
  5133. } = this._selected;
  5134. let current = 0,
  5135. total = this._matchesCountTotal;
  5136. if (matchIdx !== -1) {
  5137. for (let i = 0; i < pageIdx; i++) {
  5138. current += this._pageMatches[i]?.length || 0;
  5139. }
  5140. current += matchIdx + 1;
  5141. }
  5142. if (current < 1 || current > total) {
  5143. current = total = 0;
  5144. }
  5145. return {
  5146. current,
  5147. total
  5148. };
  5149. }
  5150. #updateUIResultsCount() {
  5151. this._eventBus.dispatch("updatefindmatchescount", {
  5152. source: this,
  5153. matchesCount: this.#requestMatchesCount()
  5154. });
  5155. }
  5156. #updateUIState(state, previous = false) {
  5157. if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) {
  5158. return;
  5159. }
  5160. this._eventBus.dispatch("updatefindcontrolstate", {
  5161. source: this,
  5162. state,
  5163. previous,
  5164. entireWord: this.#state?.entireWord ?? null,
  5165. matchesCount: this.#requestMatchesCount(),
  5166. rawQuery: this.#state?.query ?? null
  5167. });
  5168. }
  5169. }
  5170. ;// CONCATENATED MODULE: ./web/pdf_find_bar.js
  5171. const MATCHES_COUNT_LIMIT = 1000;
  5172. class PDFFindBar {
  5173. #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this));
  5174. constructor(options, eventBus) {
  5175. this.opened = false;
  5176. this.bar = options.bar;
  5177. this.toggleButton = options.toggleButton;
  5178. this.findField = options.findField;
  5179. this.highlightAll = options.highlightAllCheckbox;
  5180. this.caseSensitive = options.caseSensitiveCheckbox;
  5181. this.matchDiacritics = options.matchDiacriticsCheckbox;
  5182. this.entireWord = options.entireWordCheckbox;
  5183. this.findMsg = options.findMsg;
  5184. this.findResultsCount = options.findResultsCount;
  5185. this.findPreviousButton = options.findPreviousButton;
  5186. this.findNextButton = options.findNextButton;
  5187. this.eventBus = eventBus;
  5188. this.toggleButton.addEventListener("click", () => {
  5189. this.toggle();
  5190. });
  5191. this.findField.addEventListener("input", () => {
  5192. this.dispatchEvent("");
  5193. });
  5194. this.bar.addEventListener("keydown", e => {
  5195. switch (e.keyCode) {
  5196. case 13:
  5197. if (e.target === this.findField) {
  5198. this.dispatchEvent("again", e.shiftKey);
  5199. }
  5200. break;
  5201. case 27:
  5202. this.close();
  5203. break;
  5204. }
  5205. });
  5206. this.findPreviousButton.addEventListener("click", () => {
  5207. this.dispatchEvent("again", true);
  5208. });
  5209. this.findNextButton.addEventListener("click", () => {
  5210. this.dispatchEvent("again", false);
  5211. });
  5212. this.highlightAll.addEventListener("click", () => {
  5213. this.dispatchEvent("highlightallchange");
  5214. });
  5215. this.caseSensitive.addEventListener("click", () => {
  5216. this.dispatchEvent("casesensitivitychange");
  5217. });
  5218. this.entireWord.addEventListener("click", () => {
  5219. this.dispatchEvent("entirewordchange");
  5220. });
  5221. this.matchDiacritics.addEventListener("click", () => {
  5222. this.dispatchEvent("diacriticmatchingchange");
  5223. });
  5224. }
  5225. reset() {
  5226. this.updateUIState();
  5227. }
  5228. dispatchEvent(type, findPrev = false) {
  5229. this.eventBus.dispatch("find", {
  5230. source: this,
  5231. type,
  5232. query: this.findField.value,
  5233. caseSensitive: this.caseSensitive.checked,
  5234. entireWord: this.entireWord.checked,
  5235. highlightAll: this.highlightAll.checked,
  5236. findPrevious: findPrev,
  5237. matchDiacritics: this.matchDiacritics.checked
  5238. });
  5239. }
  5240. updateUIState(state, previous, matchesCount) {
  5241. const {
  5242. findField,
  5243. findMsg
  5244. } = this;
  5245. let findMsgId = "",
  5246. status = "";
  5247. switch (state) {
  5248. case FindState.FOUND:
  5249. break;
  5250. case FindState.PENDING:
  5251. status = "pending";
  5252. break;
  5253. case FindState.NOT_FOUND:
  5254. findMsgId = "pdfjs-find-not-found";
  5255. status = "notFound";
  5256. break;
  5257. case FindState.WRAPPED:
  5258. findMsgId = `pdfjs-find-reached-${previous ? "top" : "bottom"}`;
  5259. break;
  5260. }
  5261. findField.setAttribute("data-status", status);
  5262. findField.setAttribute("aria-invalid", state === FindState.NOT_FOUND);
  5263. findMsg.setAttribute("data-status", status);
  5264. if (findMsgId) {
  5265. findMsg.setAttribute("data-l10n-id", findMsgId);
  5266. } else {
  5267. findMsg.removeAttribute("data-l10n-id");
  5268. findMsg.textContent = "";
  5269. }
  5270. this.updateResultsCount(matchesCount);
  5271. }
  5272. updateResultsCount({
  5273. current = 0,
  5274. total = 0
  5275. } = {}) {
  5276. const {
  5277. findResultsCount
  5278. } = this;
  5279. if (total > 0) {
  5280. const limit = MATCHES_COUNT_LIMIT;
  5281. findResultsCount.setAttribute("data-l10n-id", `pdfjs-find-match-count${total > limit ? "-limit" : ""}`);
  5282. findResultsCount.setAttribute("data-l10n-args", JSON.stringify({
  5283. limit,
  5284. current,
  5285. total
  5286. }));
  5287. } else {
  5288. findResultsCount.removeAttribute("data-l10n-id");
  5289. findResultsCount.textContent = "";
  5290. }
  5291. }
  5292. open() {
  5293. if (!this.opened) {
  5294. this.#resizeObserver.observe(this.bar.parentNode);
  5295. this.#resizeObserver.observe(this.bar);
  5296. this.opened = true;
  5297. toggleExpandedBtn(this.toggleButton, true, this.bar);
  5298. }
  5299. this.findField.select();
  5300. this.findField.focus();
  5301. }
  5302. close() {
  5303. if (!this.opened) {
  5304. return;
  5305. }
  5306. this.#resizeObserver.disconnect();
  5307. this.opened = false;
  5308. toggleExpandedBtn(this.toggleButton, false, this.bar);
  5309. this.eventBus.dispatch("findbarclose", {
  5310. source: this
  5311. });
  5312. }
  5313. toggle() {
  5314. if (this.opened) {
  5315. this.close();
  5316. } else {
  5317. this.open();
  5318. }
  5319. }
  5320. #resizeObserverCallback(entries) {
  5321. const {
  5322. bar
  5323. } = this;
  5324. bar.classList.remove("wrapContainers");
  5325. const findbarHeight = bar.clientHeight;
  5326. const inputContainerHeight = bar.firstElementChild.clientHeight;
  5327. if (findbarHeight > inputContainerHeight) {
  5328. bar.classList.add("wrapContainers");
  5329. }
  5330. }
  5331. }
  5332. ;// CONCATENATED MODULE: ./web/pdf_history.js
  5333. const HASH_CHANGE_TIMEOUT = 1000;
  5334. const POSITION_UPDATED_THRESHOLD = 50;
  5335. const UPDATE_VIEWAREA_TIMEOUT = 1000;
  5336. function getCurrentHash() {
  5337. return document.location.hash;
  5338. }
  5339. class PDFHistory {
  5340. #eventAbortController = null;
  5341. constructor({
  5342. linkService,
  5343. eventBus
  5344. }) {
  5345. this.linkService = linkService;
  5346. this.eventBus = eventBus;
  5347. this._initialized = false;
  5348. this._fingerprint = "";
  5349. this.reset();
  5350. this.eventBus._on("pagesinit", () => {
  5351. this._isPagesLoaded = false;
  5352. this.eventBus._on("pagesloaded", evt => {
  5353. this._isPagesLoaded = !!evt.pagesCount;
  5354. }, {
  5355. once: true
  5356. });
  5357. });
  5358. }
  5359. initialize({
  5360. fingerprint,
  5361. resetHistory = false,
  5362. updateUrl = false
  5363. }) {
  5364. if (!fingerprint || typeof fingerprint !== "string") {
  5365. console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');
  5366. return;
  5367. }
  5368. if (this._initialized) {
  5369. this.reset();
  5370. }
  5371. const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint;
  5372. this._fingerprint = fingerprint;
  5373. this._updateUrl = updateUrl === true;
  5374. this._initialized = true;
  5375. this.#bindEvents();
  5376. const state = window.history.state;
  5377. this._popStateInProgress = false;
  5378. this._blockHashChange = 0;
  5379. this._currentHash = getCurrentHash();
  5380. this._numPositionUpdates = 0;
  5381. this._uid = this._maxUid = 0;
  5382. this._destination = null;
  5383. this._position = null;
  5384. if (!this.#isValidState(state, true) || resetHistory) {
  5385. const {
  5386. hash,
  5387. page,
  5388. rotation
  5389. } = this.#parseCurrentHash(true);
  5390. if (!hash || reInitialized || resetHistory) {
  5391. this.#pushOrReplaceState(null, true);
  5392. return;
  5393. }
  5394. this.#pushOrReplaceState({
  5395. hash,
  5396. page,
  5397. rotation
  5398. }, true);
  5399. return;
  5400. }
  5401. const destination = state.destination;
  5402. this.#updateInternalState(destination, state.uid, true);
  5403. if (destination.rotation !== undefined) {
  5404. this._initialRotation = destination.rotation;
  5405. }
  5406. if (destination.dest) {
  5407. this._initialBookmark = JSON.stringify(destination.dest);
  5408. this._destination.page = null;
  5409. } else if (destination.hash) {
  5410. this._initialBookmark = destination.hash;
  5411. } else if (destination.page) {
  5412. this._initialBookmark = `page=${destination.page}`;
  5413. }
  5414. }
  5415. reset() {
  5416. if (this._initialized) {
  5417. this.#pageHide();
  5418. this._initialized = false;
  5419. this.#unbindEvents();
  5420. }
  5421. if (this._updateViewareaTimeout) {
  5422. clearTimeout(this._updateViewareaTimeout);
  5423. this._updateViewareaTimeout = null;
  5424. }
  5425. this._initialBookmark = null;
  5426. this._initialRotation = null;
  5427. }
  5428. push({
  5429. namedDest = null,
  5430. explicitDest,
  5431. pageNumber
  5432. }) {
  5433. if (!this._initialized) {
  5434. return;
  5435. }
  5436. if (namedDest && typeof namedDest !== "string") {
  5437. console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`);
  5438. return;
  5439. } else if (!Array.isArray(explicitDest)) {
  5440. console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`);
  5441. return;
  5442. } else if (!this.#isValidPage(pageNumber)) {
  5443. if (pageNumber !== null || this._destination) {
  5444. console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`);
  5445. return;
  5446. }
  5447. }
  5448. const hash = namedDest || JSON.stringify(explicitDest);
  5449. if (!hash) {
  5450. return;
  5451. }
  5452. let forceReplace = false;
  5453. if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) {
  5454. if (this._destination.page) {
  5455. return;
  5456. }
  5457. forceReplace = true;
  5458. }
  5459. if (this._popStateInProgress && !forceReplace) {
  5460. return;
  5461. }
  5462. this.#pushOrReplaceState({
  5463. dest: explicitDest,
  5464. hash,
  5465. page: pageNumber,
  5466. rotation: this.linkService.rotation
  5467. }, forceReplace);
  5468. if (!this._popStateInProgress) {
  5469. this._popStateInProgress = true;
  5470. Promise.resolve().then(() => {
  5471. this._popStateInProgress = false;
  5472. });
  5473. }
  5474. }
  5475. pushPage(pageNumber) {
  5476. if (!this._initialized) {
  5477. return;
  5478. }
  5479. if (!this.#isValidPage(pageNumber)) {
  5480. console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`);
  5481. return;
  5482. }
  5483. if (this._destination?.page === pageNumber) {
  5484. return;
  5485. }
  5486. if (this._popStateInProgress) {
  5487. return;
  5488. }
  5489. this.#pushOrReplaceState({
  5490. dest: null,
  5491. hash: `page=${pageNumber}`,
  5492. page: pageNumber,
  5493. rotation: this.linkService.rotation
  5494. });
  5495. if (!this._popStateInProgress) {
  5496. this._popStateInProgress = true;
  5497. Promise.resolve().then(() => {
  5498. this._popStateInProgress = false;
  5499. });
  5500. }
  5501. }
  5502. pushCurrentPosition() {
  5503. if (!this._initialized || this._popStateInProgress) {
  5504. return;
  5505. }
  5506. this.#tryPushCurrentPosition();
  5507. }
  5508. back() {
  5509. if (!this._initialized || this._popStateInProgress) {
  5510. return;
  5511. }
  5512. const state = window.history.state;
  5513. if (this.#isValidState(state) && state.uid > 0) {
  5514. window.history.back();
  5515. }
  5516. }
  5517. forward() {
  5518. if (!this._initialized || this._popStateInProgress) {
  5519. return;
  5520. }
  5521. const state = window.history.state;
  5522. if (this.#isValidState(state) && state.uid < this._maxUid) {
  5523. window.history.forward();
  5524. }
  5525. }
  5526. get popStateInProgress() {
  5527. return this._initialized && (this._popStateInProgress || this._blockHashChange > 0);
  5528. }
  5529. get initialBookmark() {
  5530. return this._initialized ? this._initialBookmark : null;
  5531. }
  5532. get initialRotation() {
  5533. return this._initialized ? this._initialRotation : null;
  5534. }
  5535. #pushOrReplaceState(destination, forceReplace = false) {
  5536. const shouldReplace = forceReplace || !this._destination;
  5537. const newState = {
  5538. fingerprint: this._fingerprint,
  5539. uid: shouldReplace ? this._uid : this._uid + 1,
  5540. destination
  5541. };
  5542. this.#updateInternalState(destination, newState.uid);
  5543. let newUrl;
  5544. if (this._updateUrl && destination?.hash) {
  5545. const baseUrl = document.location.href.split("#", 1)[0];
  5546. if (!baseUrl.startsWith("file://")) {
  5547. newUrl = `${baseUrl}#${destination.hash}`;
  5548. }
  5549. }
  5550. if (shouldReplace) {
  5551. window.history.replaceState(newState, "", newUrl);
  5552. } else {
  5553. window.history.pushState(newState, "", newUrl);
  5554. }
  5555. }
  5556. #tryPushCurrentPosition(temporary = false) {
  5557. if (!this._position) {
  5558. return;
  5559. }
  5560. let position = this._position;
  5561. if (temporary) {
  5562. position = Object.assign(Object.create(null), this._position);
  5563. position.temporary = true;
  5564. }
  5565. if (!this._destination) {
  5566. this.#pushOrReplaceState(position);
  5567. return;
  5568. }
  5569. if (this._destination.temporary) {
  5570. this.#pushOrReplaceState(position, true);
  5571. return;
  5572. }
  5573. if (this._destination.hash === position.hash) {
  5574. return;
  5575. }
  5576. if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) {
  5577. return;
  5578. }
  5579. let forceReplace = false;
  5580. if (this._destination.page >= position.first && this._destination.page <= position.page) {
  5581. if (this._destination.dest !== undefined || !this._destination.first) {
  5582. return;
  5583. }
  5584. forceReplace = true;
  5585. }
  5586. this.#pushOrReplaceState(position, forceReplace);
  5587. }
  5588. #isValidPage(val) {
  5589. return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount;
  5590. }
  5591. #isValidState(state, checkReload = false) {
  5592. if (!state) {
  5593. return false;
  5594. }
  5595. if (state.fingerprint !== this._fingerprint) {
  5596. if (checkReload) {
  5597. if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) {
  5598. return false;
  5599. }
  5600. const [perfEntry] = performance.getEntriesByType("navigation");
  5601. if (perfEntry?.type !== "reload") {
  5602. return false;
  5603. }
  5604. } else {
  5605. return false;
  5606. }
  5607. }
  5608. if (!Number.isInteger(state.uid) || state.uid < 0) {
  5609. return false;
  5610. }
  5611. if (state.destination === null || typeof state.destination !== "object") {
  5612. return false;
  5613. }
  5614. return true;
  5615. }
  5616. #updateInternalState(destination, uid, removeTemporary = false) {
  5617. if (this._updateViewareaTimeout) {
  5618. clearTimeout(this._updateViewareaTimeout);
  5619. this._updateViewareaTimeout = null;
  5620. }
  5621. if (removeTemporary && destination?.temporary) {
  5622. delete destination.temporary;
  5623. }
  5624. this._destination = destination;
  5625. this._uid = uid;
  5626. this._maxUid = Math.max(this._maxUid, uid);
  5627. this._numPositionUpdates = 0;
  5628. }
  5629. #parseCurrentHash(checkNameddest = false) {
  5630. const hash = unescape(getCurrentHash()).substring(1);
  5631. const params = parseQueryString(hash);
  5632. const nameddest = params.get("nameddest") || "";
  5633. let page = params.get("page") | 0;
  5634. if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) {
  5635. page = null;
  5636. }
  5637. return {
  5638. hash,
  5639. page,
  5640. rotation: this.linkService.rotation
  5641. };
  5642. }
  5643. #updateViewarea({
  5644. location
  5645. }) {
  5646. if (this._updateViewareaTimeout) {
  5647. clearTimeout(this._updateViewareaTimeout);
  5648. this._updateViewareaTimeout = null;
  5649. }
  5650. this._position = {
  5651. hash: location.pdfOpenParams.substring(1),
  5652. page: this.linkService.page,
  5653. first: location.pageNumber,
  5654. rotation: location.rotation
  5655. };
  5656. if (this._popStateInProgress) {
  5657. return;
  5658. }
  5659. if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) {
  5660. this._numPositionUpdates++;
  5661. }
  5662. if (UPDATE_VIEWAREA_TIMEOUT > 0) {
  5663. this._updateViewareaTimeout = setTimeout(() => {
  5664. if (!this._popStateInProgress) {
  5665. this.#tryPushCurrentPosition(true);
  5666. }
  5667. this._updateViewareaTimeout = null;
  5668. }, UPDATE_VIEWAREA_TIMEOUT);
  5669. }
  5670. }
  5671. #popState({
  5672. state
  5673. }) {
  5674. const newHash = getCurrentHash(),
  5675. hashChanged = this._currentHash !== newHash;
  5676. this._currentHash = newHash;
  5677. if (!state) {
  5678. this._uid++;
  5679. const {
  5680. hash,
  5681. page,
  5682. rotation
  5683. } = this.#parseCurrentHash();
  5684. this.#pushOrReplaceState({
  5685. hash,
  5686. page,
  5687. rotation
  5688. }, true);
  5689. return;
  5690. }
  5691. if (!this.#isValidState(state)) {
  5692. return;
  5693. }
  5694. this._popStateInProgress = true;
  5695. if (hashChanged) {
  5696. this._blockHashChange++;
  5697. waitOnEventOrTimeout({
  5698. target: window,
  5699. name: "hashchange",
  5700. delay: HASH_CHANGE_TIMEOUT
  5701. }).then(() => {
  5702. this._blockHashChange--;
  5703. });
  5704. }
  5705. const destination = state.destination;
  5706. this.#updateInternalState(destination, state.uid, true);
  5707. if (isValidRotation(destination.rotation)) {
  5708. this.linkService.rotation = destination.rotation;
  5709. }
  5710. if (destination.dest) {
  5711. this.linkService.goToDestination(destination.dest);
  5712. } else if (destination.hash) {
  5713. this.linkService.setHash(destination.hash);
  5714. } else if (destination.page) {
  5715. this.linkService.page = destination.page;
  5716. }
  5717. Promise.resolve().then(() => {
  5718. this._popStateInProgress = false;
  5719. });
  5720. }
  5721. #pageHide() {
  5722. if (!this._destination || this._destination.temporary) {
  5723. this.#tryPushCurrentPosition();
  5724. }
  5725. }
  5726. #bindEvents() {
  5727. if (this.#eventAbortController) {
  5728. return;
  5729. }
  5730. this.#eventAbortController = new AbortController();
  5731. const {
  5732. signal
  5733. } = this.#eventAbortController;
  5734. this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), {
  5735. signal
  5736. });
  5737. window.addEventListener("popstate", this.#popState.bind(this), {
  5738. signal
  5739. });
  5740. window.addEventListener("pagehide", this.#pageHide.bind(this), {
  5741. signal
  5742. });
  5743. }
  5744. #unbindEvents() {
  5745. this.#eventAbortController?.abort();
  5746. this.#eventAbortController = null;
  5747. }
  5748. }
  5749. function isDestHashesEqual(destHash, pushHash) {
  5750. if (typeof destHash !== "string" || typeof pushHash !== "string") {
  5751. return false;
  5752. }
  5753. if (destHash === pushHash) {
  5754. return true;
  5755. }
  5756. const nameddest = parseQueryString(destHash).get("nameddest");
  5757. if (nameddest === pushHash) {
  5758. return true;
  5759. }
  5760. return false;
  5761. }
  5762. function isDestArraysEqual(firstDest, secondDest) {
  5763. function isEntryEqual(first, second) {
  5764. if (typeof first !== typeof second) {
  5765. return false;
  5766. }
  5767. if (Array.isArray(first) || Array.isArray(second)) {
  5768. return false;
  5769. }
  5770. if (first !== null && typeof first === "object" && second !== null) {
  5771. if (Object.keys(first).length !== Object.keys(second).length) {
  5772. return false;
  5773. }
  5774. for (const key in first) {
  5775. if (!isEntryEqual(first[key], second[key])) {
  5776. return false;
  5777. }
  5778. }
  5779. return true;
  5780. }
  5781. return first === second || Number.isNaN(first) && Number.isNaN(second);
  5782. }
  5783. if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) {
  5784. return false;
  5785. }
  5786. if (firstDest.length !== secondDest.length) {
  5787. return false;
  5788. }
  5789. for (let i = 0, ii = firstDest.length; i < ii; i++) {
  5790. if (!isEntryEqual(firstDest[i], secondDest[i])) {
  5791. return false;
  5792. }
  5793. }
  5794. return true;
  5795. }
  5796. ;// CONCATENATED MODULE: ./web/pdf_layer_viewer.js
  5797. class PDFLayerViewer extends BaseTreeViewer {
  5798. constructor(options) {
  5799. super(options);
  5800. this.eventBus._on("optionalcontentconfigchanged", evt => {
  5801. this.#updateLayers(evt.promise);
  5802. });
  5803. this.eventBus._on("resetlayers", () => {
  5804. this.#updateLayers();
  5805. });
  5806. this.eventBus._on("togglelayerstree", this._toggleAllTreeItems.bind(this));
  5807. }
  5808. reset() {
  5809. super.reset();
  5810. this._optionalContentConfig = null;
  5811. this._optionalContentHash = null;
  5812. }
  5813. _dispatchEvent(layersCount) {
  5814. this.eventBus.dispatch("layersloaded", {
  5815. source: this,
  5816. layersCount
  5817. });
  5818. }
  5819. _bindLink(element, {
  5820. groupId,
  5821. input
  5822. }) {
  5823. const setVisibility = () => {
  5824. this._optionalContentConfig.setVisibility(groupId, input.checked);
  5825. this._optionalContentHash = this._optionalContentConfig.getHash();
  5826. this.eventBus.dispatch("optionalcontentconfig", {
  5827. source: this,
  5828. promise: Promise.resolve(this._optionalContentConfig)
  5829. });
  5830. };
  5831. element.onclick = evt => {
  5832. if (evt.target === input) {
  5833. setVisibility();
  5834. return true;
  5835. } else if (evt.target !== element) {
  5836. return true;
  5837. }
  5838. input.checked = !input.checked;
  5839. setVisibility();
  5840. return false;
  5841. };
  5842. }
  5843. async _setNestedName(element, {
  5844. name = null
  5845. }) {
  5846. if (typeof name === "string") {
  5847. element.textContent = this._normalizeTextContent(name);
  5848. return;
  5849. }
  5850. element.textContent = await this._l10n.get("pdfjs-additional-layers");
  5851. element.style.fontStyle = "italic";
  5852. }
  5853. _addToggleButton(div, {
  5854. name = null
  5855. }) {
  5856. super._addToggleButton(div, name === null);
  5857. }
  5858. _toggleAllTreeItems() {
  5859. if (!this._optionalContentConfig) {
  5860. return;
  5861. }
  5862. super._toggleAllTreeItems();
  5863. }
  5864. render({
  5865. optionalContentConfig,
  5866. pdfDocument
  5867. }) {
  5868. if (this._optionalContentConfig) {
  5869. this.reset();
  5870. }
  5871. this._optionalContentConfig = optionalContentConfig || null;
  5872. this._pdfDocument = pdfDocument || null;
  5873. const groups = optionalContentConfig?.getOrder();
  5874. if (!groups) {
  5875. this._dispatchEvent(0);
  5876. return;
  5877. }
  5878. this._optionalContentHash = optionalContentConfig.getHash();
  5879. const fragment = document.createDocumentFragment(),
  5880. queue = [{
  5881. parent: fragment,
  5882. groups
  5883. }];
  5884. let layersCount = 0,
  5885. hasAnyNesting = false;
  5886. while (queue.length > 0) {
  5887. const levelData = queue.shift();
  5888. for (const groupId of levelData.groups) {
  5889. const div = document.createElement("div");
  5890. div.className = "treeItem";
  5891. const element = document.createElement("a");
  5892. div.append(element);
  5893. if (typeof groupId === "object") {
  5894. hasAnyNesting = true;
  5895. this._addToggleButton(div, groupId);
  5896. this._setNestedName(element, groupId);
  5897. const itemsDiv = document.createElement("div");
  5898. itemsDiv.className = "treeItems";
  5899. div.append(itemsDiv);
  5900. queue.push({
  5901. parent: itemsDiv,
  5902. groups: groupId.order
  5903. });
  5904. } else {
  5905. const group = optionalContentConfig.getGroup(groupId);
  5906. const input = document.createElement("input");
  5907. this._bindLink(element, {
  5908. groupId,
  5909. input
  5910. });
  5911. input.type = "checkbox";
  5912. input.checked = group.visible;
  5913. const label = document.createElement("label");
  5914. label.textContent = this._normalizeTextContent(group.name);
  5915. label.append(input);
  5916. element.append(label);
  5917. layersCount++;
  5918. }
  5919. levelData.parent.append(div);
  5920. }
  5921. }
  5922. this._finishRendering(fragment, layersCount, hasAnyNesting);
  5923. }
  5924. async #updateLayers(promise = null) {
  5925. if (!this._optionalContentConfig) {
  5926. return;
  5927. }
  5928. const pdfDocument = this._pdfDocument;
  5929. const optionalContentConfig = await (promise || pdfDocument.getOptionalContentConfig({
  5930. intent: "display"
  5931. }));
  5932. if (pdfDocument !== this._pdfDocument) {
  5933. return;
  5934. }
  5935. if (promise) {
  5936. if (optionalContentConfig.getHash() === this._optionalContentHash) {
  5937. return;
  5938. }
  5939. } else {
  5940. this.eventBus.dispatch("optionalcontentconfig", {
  5941. source: this,
  5942. promise: Promise.resolve(optionalContentConfig)
  5943. });
  5944. }
  5945. this.render({
  5946. optionalContentConfig,
  5947. pdfDocument: this._pdfDocument
  5948. });
  5949. }
  5950. }
  5951. ;// CONCATENATED MODULE: ./web/pdf_outline_viewer.js
  5952. class PDFOutlineViewer extends BaseTreeViewer {
  5953. constructor(options) {
  5954. super(options);
  5955. this.linkService = options.linkService;
  5956. this.downloadManager = options.downloadManager;
  5957. this.eventBus._on("toggleoutlinetree", this._toggleAllTreeItems.bind(this));
  5958. this.eventBus._on("currentoutlineitem", this._currentOutlineItem.bind(this));
  5959. this.eventBus._on("pagechanging", evt => {
  5960. this._currentPageNumber = evt.pageNumber;
  5961. });
  5962. this.eventBus._on("pagesloaded", evt => {
  5963. this._isPagesLoaded = !!evt.pagesCount;
  5964. this._currentOutlineItemCapability?.resolve(this._isPagesLoaded);
  5965. });
  5966. this.eventBus._on("sidebarviewchanged", evt => {
  5967. this._sidebarView = evt.view;
  5968. });
  5969. }
  5970. reset() {
  5971. super.reset();
  5972. this._outline = null;
  5973. this._pageNumberToDestHashCapability = null;
  5974. this._currentPageNumber = 1;
  5975. this._isPagesLoaded = null;
  5976. this._currentOutlineItemCapability?.resolve(false);
  5977. this._currentOutlineItemCapability = null;
  5978. }
  5979. _dispatchEvent(outlineCount) {
  5980. this._currentOutlineItemCapability = Promise.withResolvers();
  5981. if (outlineCount === 0 || this._pdfDocument?.loadingParams.disableAutoFetch) {
  5982. this._currentOutlineItemCapability.resolve(false);
  5983. } else if (this._isPagesLoaded !== null) {
  5984. this._currentOutlineItemCapability.resolve(this._isPagesLoaded);
  5985. }
  5986. this.eventBus.dispatch("outlineloaded", {
  5987. source: this,
  5988. outlineCount,
  5989. currentOutlineItemPromise: this._currentOutlineItemCapability.promise
  5990. });
  5991. }
  5992. _bindLink(element, {
  5993. url,
  5994. newWindow,
  5995. action,
  5996. attachment,
  5997. dest,
  5998. setOCGState
  5999. }) {
  6000. const {
  6001. linkService
  6002. } = this;
  6003. if (url) {
  6004. linkService.addLinkAttributes(element, url, newWindow);
  6005. return;
  6006. }
  6007. if (action) {
  6008. element.href = linkService.getAnchorUrl("");
  6009. element.onclick = () => {
  6010. linkService.executeNamedAction(action);
  6011. return false;
  6012. };
  6013. return;
  6014. }
  6015. if (attachment) {
  6016. element.href = linkService.getAnchorUrl("");
  6017. element.onclick = () => {
  6018. this.downloadManager.openOrDownloadData(attachment.content, attachment.filename);
  6019. return false;
  6020. };
  6021. return;
  6022. }
  6023. if (setOCGState) {
  6024. element.href = linkService.getAnchorUrl("");
  6025. element.onclick = () => {
  6026. linkService.executeSetOCGState(setOCGState);
  6027. return false;
  6028. };
  6029. return;
  6030. }
  6031. element.href = linkService.getDestinationHash(dest);
  6032. element.onclick = evt => {
  6033. this._updateCurrentTreeItem(evt.target.parentNode);
  6034. if (dest) {
  6035. linkService.goToDestination(dest);
  6036. }
  6037. return false;
  6038. };
  6039. }
  6040. _setStyles(element, {
  6041. bold,
  6042. italic
  6043. }) {
  6044. if (bold) {
  6045. element.style.fontWeight = "bold";
  6046. }
  6047. if (italic) {
  6048. element.style.fontStyle = "italic";
  6049. }
  6050. }
  6051. _addToggleButton(div, {
  6052. count,
  6053. items
  6054. }) {
  6055. let hidden = false;
  6056. if (count < 0) {
  6057. let totalCount = items.length;
  6058. if (totalCount > 0) {
  6059. const queue = [...items];
  6060. while (queue.length > 0) {
  6061. const {
  6062. count: nestedCount,
  6063. items: nestedItems
  6064. } = queue.shift();
  6065. if (nestedCount > 0 && nestedItems.length > 0) {
  6066. totalCount += nestedItems.length;
  6067. queue.push(...nestedItems);
  6068. }
  6069. }
  6070. }
  6071. if (Math.abs(count) === totalCount) {
  6072. hidden = true;
  6073. }
  6074. }
  6075. super._addToggleButton(div, hidden);
  6076. }
  6077. _toggleAllTreeItems() {
  6078. if (!this._outline) {
  6079. return;
  6080. }
  6081. super._toggleAllTreeItems();
  6082. }
  6083. render({
  6084. outline,
  6085. pdfDocument
  6086. }) {
  6087. if (this._outline) {
  6088. this.reset();
  6089. }
  6090. this._outline = outline || null;
  6091. this._pdfDocument = pdfDocument || null;
  6092. if (!outline) {
  6093. this._dispatchEvent(0);
  6094. return;
  6095. }
  6096. const fragment = document.createDocumentFragment();
  6097. const queue = [{
  6098. parent: fragment,
  6099. items: outline
  6100. }];
  6101. let outlineCount = 0,
  6102. hasAnyNesting = false;
  6103. while (queue.length > 0) {
  6104. const levelData = queue.shift();
  6105. for (const item of levelData.items) {
  6106. const div = document.createElement("div");
  6107. div.className = "treeItem";
  6108. const element = document.createElement("a");
  6109. this._bindLink(element, item);
  6110. this._setStyles(element, item);
  6111. element.textContent = this._normalizeTextContent(item.title);
  6112. div.append(element);
  6113. if (item.items.length > 0) {
  6114. hasAnyNesting = true;
  6115. this._addToggleButton(div, item);
  6116. const itemsDiv = document.createElement("div");
  6117. itemsDiv.className = "treeItems";
  6118. div.append(itemsDiv);
  6119. queue.push({
  6120. parent: itemsDiv,
  6121. items: item.items
  6122. });
  6123. }
  6124. levelData.parent.append(div);
  6125. outlineCount++;
  6126. }
  6127. }
  6128. this._finishRendering(fragment, outlineCount, hasAnyNesting);
  6129. }
  6130. async _currentOutlineItem() {
  6131. if (!this._isPagesLoaded) {
  6132. throw new Error("_currentOutlineItem: All pages have not been loaded.");
  6133. }
  6134. if (!this._outline || !this._pdfDocument) {
  6135. return;
  6136. }
  6137. const pageNumberToDestHash = await this._getPageNumberToDestHash(this._pdfDocument);
  6138. if (!pageNumberToDestHash) {
  6139. return;
  6140. }
  6141. this._updateCurrentTreeItem(null);
  6142. if (this._sidebarView !== SidebarView.OUTLINE) {
  6143. return;
  6144. }
  6145. for (let i = this._currentPageNumber; i > 0; i--) {
  6146. const destHash = pageNumberToDestHash.get(i);
  6147. if (!destHash) {
  6148. continue;
  6149. }
  6150. const linkElement = this.container.querySelector(`a[href="${destHash}"]`);
  6151. if (!linkElement) {
  6152. continue;
  6153. }
  6154. this._scrollToCurrentTreeItem(linkElement.parentNode);
  6155. break;
  6156. }
  6157. }
  6158. async _getPageNumberToDestHash(pdfDocument) {
  6159. if (this._pageNumberToDestHashCapability) {
  6160. return this._pageNumberToDestHashCapability.promise;
  6161. }
  6162. this._pageNumberToDestHashCapability = Promise.withResolvers();
  6163. const pageNumberToDestHash = new Map(),
  6164. pageNumberNesting = new Map();
  6165. const queue = [{
  6166. nesting: 0,
  6167. items: this._outline
  6168. }];
  6169. while (queue.length > 0) {
  6170. const levelData = queue.shift(),
  6171. currentNesting = levelData.nesting;
  6172. for (const {
  6173. dest,
  6174. items
  6175. } of levelData.items) {
  6176. let explicitDest, pageNumber;
  6177. if (typeof dest === "string") {
  6178. explicitDest = await pdfDocument.getDestination(dest);
  6179. if (pdfDocument !== this._pdfDocument) {
  6180. return null;
  6181. }
  6182. } else {
  6183. explicitDest = dest;
  6184. }
  6185. if (Array.isArray(explicitDest)) {
  6186. const [destRef] = explicitDest;
  6187. if (destRef && typeof destRef === "object") {
  6188. pageNumber = pdfDocument.cachedPageNumber(destRef);
  6189. } else if (Number.isInteger(destRef)) {
  6190. pageNumber = destRef + 1;
  6191. }
  6192. if (Number.isInteger(pageNumber) && (!pageNumberToDestHash.has(pageNumber) || currentNesting > pageNumberNesting.get(pageNumber))) {
  6193. const destHash = this.linkService.getDestinationHash(dest);
  6194. pageNumberToDestHash.set(pageNumber, destHash);
  6195. pageNumberNesting.set(pageNumber, currentNesting);
  6196. }
  6197. }
  6198. if (items.length > 0) {
  6199. queue.push({
  6200. nesting: currentNesting + 1,
  6201. items
  6202. });
  6203. }
  6204. }
  6205. }
  6206. this._pageNumberToDestHashCapability.resolve(pageNumberToDestHash.size > 0 ? pageNumberToDestHash : null);
  6207. return this._pageNumberToDestHashCapability.promise;
  6208. }
  6209. }
  6210. ;// CONCATENATED MODULE: ./web/pdf_presentation_mode.js
  6211. const DELAY_BEFORE_HIDING_CONTROLS = 3000;
  6212. const ACTIVE_SELECTOR = "pdfPresentationMode";
  6213. const CONTROLS_SELECTOR = "pdfPresentationModeControls";
  6214. const MOUSE_SCROLL_COOLDOWN_TIME = 50;
  6215. const PAGE_SWITCH_THRESHOLD = 0.1;
  6216. const SWIPE_MIN_DISTANCE_THRESHOLD = 50;
  6217. const SWIPE_ANGLE_THRESHOLD = Math.PI / 6;
  6218. class PDFPresentationMode {
  6219. #state = PresentationModeState.UNKNOWN;
  6220. #args = null;
  6221. #fullscreenChangeAbortController = null;
  6222. #windowAbortController = null;
  6223. constructor({
  6224. container,
  6225. pdfViewer,
  6226. eventBus
  6227. }) {
  6228. this.container = container;
  6229. this.pdfViewer = pdfViewer;
  6230. this.eventBus = eventBus;
  6231. this.contextMenuOpen = false;
  6232. this.mouseScrollTimeStamp = 0;
  6233. this.mouseScrollDelta = 0;
  6234. this.touchSwipeState = null;
  6235. }
  6236. async request() {
  6237. const {
  6238. container,
  6239. pdfViewer
  6240. } = this;
  6241. if (this.active || !pdfViewer.pagesCount || !container.requestFullscreen) {
  6242. return false;
  6243. }
  6244. this.#addFullscreenChangeListeners();
  6245. this.#notifyStateChange(PresentationModeState.CHANGING);
  6246. const promise = container.requestFullscreen();
  6247. this.#args = {
  6248. pageNumber: pdfViewer.currentPageNumber,
  6249. scaleValue: pdfViewer.currentScaleValue,
  6250. scrollMode: pdfViewer.scrollMode,
  6251. spreadMode: null,
  6252. annotationEditorMode: null
  6253. };
  6254. if (pdfViewer.spreadMode !== SpreadMode.NONE && !(pdfViewer.pageViewsReady && pdfViewer.hasEqualPageSizes)) {
  6255. console.warn("Ignoring Spread modes when entering PresentationMode, " + "since the document may contain varying page sizes.");
  6256. this.#args.spreadMode = pdfViewer.spreadMode;
  6257. }
  6258. if (pdfViewer.annotationEditorMode !== AnnotationEditorType.DISABLE) {
  6259. this.#args.annotationEditorMode = pdfViewer.annotationEditorMode;
  6260. }
  6261. try {
  6262. await promise;
  6263. pdfViewer.focus();
  6264. return true;
  6265. } catch {
  6266. this.#removeFullscreenChangeListeners();
  6267. this.#notifyStateChange(PresentationModeState.NORMAL);
  6268. }
  6269. return false;
  6270. }
  6271. get active() {
  6272. return this.#state === PresentationModeState.CHANGING || this.#state === PresentationModeState.FULLSCREEN;
  6273. }
  6274. #mouseWheel(evt) {
  6275. if (!this.active) {
  6276. return;
  6277. }
  6278. evt.preventDefault();
  6279. const delta = normalizeWheelEventDelta(evt);
  6280. const currentTime = Date.now();
  6281. const storedTime = this.mouseScrollTimeStamp;
  6282. if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
  6283. return;
  6284. }
  6285. if (this.mouseScrollDelta > 0 && delta < 0 || this.mouseScrollDelta < 0 && delta > 0) {
  6286. this.#resetMouseScrollState();
  6287. }
  6288. this.mouseScrollDelta += delta;
  6289. if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) {
  6290. const totalDelta = this.mouseScrollDelta;
  6291. this.#resetMouseScrollState();
  6292. const success = totalDelta > 0 ? this.pdfViewer.previousPage() : this.pdfViewer.nextPage();
  6293. if (success) {
  6294. this.mouseScrollTimeStamp = currentTime;
  6295. }
  6296. }
  6297. }
  6298. #notifyStateChange(state) {
  6299. this.#state = state;
  6300. this.eventBus.dispatch("presentationmodechanged", {
  6301. source: this,
  6302. state
  6303. });
  6304. }
  6305. #enter() {
  6306. this.#notifyStateChange(PresentationModeState.FULLSCREEN);
  6307. this.container.classList.add(ACTIVE_SELECTOR);
  6308. setTimeout(() => {
  6309. this.pdfViewer.scrollMode = ScrollMode.PAGE;
  6310. if (this.#args.spreadMode !== null) {
  6311. this.pdfViewer.spreadMode = SpreadMode.NONE;
  6312. }
  6313. this.pdfViewer.currentPageNumber = this.#args.pageNumber;
  6314. this.pdfViewer.currentScaleValue = "page-fit";
  6315. if (this.#args.annotationEditorMode !== null) {
  6316. this.pdfViewer.annotationEditorMode = {
  6317. mode: AnnotationEditorType.NONE
  6318. };
  6319. }
  6320. }, 0);
  6321. this.#addWindowListeners();
  6322. this.#showControls();
  6323. this.contextMenuOpen = false;
  6324. document.getSelection().empty();
  6325. }
  6326. #exit() {
  6327. const pageNumber = this.pdfViewer.currentPageNumber;
  6328. this.container.classList.remove(ACTIVE_SELECTOR);
  6329. setTimeout(() => {
  6330. this.#removeFullscreenChangeListeners();
  6331. this.#notifyStateChange(PresentationModeState.NORMAL);
  6332. this.pdfViewer.scrollMode = this.#args.scrollMode;
  6333. if (this.#args.spreadMode !== null) {
  6334. this.pdfViewer.spreadMode = this.#args.spreadMode;
  6335. }
  6336. this.pdfViewer.currentScaleValue = this.#args.scaleValue;
  6337. this.pdfViewer.currentPageNumber = pageNumber;
  6338. if (this.#args.annotationEditorMode !== null) {
  6339. this.pdfViewer.annotationEditorMode = {
  6340. mode: this.#args.annotationEditorMode
  6341. };
  6342. }
  6343. this.#args = null;
  6344. }, 0);
  6345. this.#removeWindowListeners();
  6346. this.#hideControls();
  6347. this.#resetMouseScrollState();
  6348. this.contextMenuOpen = false;
  6349. }
  6350. #mouseDown(evt) {
  6351. if (this.contextMenuOpen) {
  6352. this.contextMenuOpen = false;
  6353. evt.preventDefault();
  6354. return;
  6355. }
  6356. if (evt.button !== 0) {
  6357. return;
  6358. }
  6359. if (evt.target.href && evt.target.parentNode?.hasAttribute("data-internal-link")) {
  6360. return;
  6361. }
  6362. evt.preventDefault();
  6363. if (evt.shiftKey) {
  6364. this.pdfViewer.previousPage();
  6365. } else {
  6366. this.pdfViewer.nextPage();
  6367. }
  6368. }
  6369. #contextMenu() {
  6370. this.contextMenuOpen = true;
  6371. }
  6372. #showControls() {
  6373. if (this.controlsTimeout) {
  6374. clearTimeout(this.controlsTimeout);
  6375. } else {
  6376. this.container.classList.add(CONTROLS_SELECTOR);
  6377. }
  6378. this.controlsTimeout = setTimeout(() => {
  6379. this.container.classList.remove(CONTROLS_SELECTOR);
  6380. delete this.controlsTimeout;
  6381. }, DELAY_BEFORE_HIDING_CONTROLS);
  6382. }
  6383. #hideControls() {
  6384. if (!this.controlsTimeout) {
  6385. return;
  6386. }
  6387. clearTimeout(this.controlsTimeout);
  6388. this.container.classList.remove(CONTROLS_SELECTOR);
  6389. delete this.controlsTimeout;
  6390. }
  6391. #resetMouseScrollState() {
  6392. this.mouseScrollTimeStamp = 0;
  6393. this.mouseScrollDelta = 0;
  6394. }
  6395. #touchSwipe(evt) {
  6396. if (!this.active) {
  6397. return;
  6398. }
  6399. if (evt.touches.length > 1) {
  6400. this.touchSwipeState = null;
  6401. return;
  6402. }
  6403. switch (evt.type) {
  6404. case "touchstart":
  6405. this.touchSwipeState = {
  6406. startX: evt.touches[0].pageX,
  6407. startY: evt.touches[0].pageY,
  6408. endX: evt.touches[0].pageX,
  6409. endY: evt.touches[0].pageY
  6410. };
  6411. break;
  6412. case "touchmove":
  6413. if (this.touchSwipeState === null) {
  6414. return;
  6415. }
  6416. this.touchSwipeState.endX = evt.touches[0].pageX;
  6417. this.touchSwipeState.endY = evt.touches[0].pageY;
  6418. evt.preventDefault();
  6419. break;
  6420. case "touchend":
  6421. if (this.touchSwipeState === null) {
  6422. return;
  6423. }
  6424. let delta = 0;
  6425. const dx = this.touchSwipeState.endX - this.touchSwipeState.startX;
  6426. const dy = this.touchSwipeState.endY - this.touchSwipeState.startY;
  6427. const absAngle = Math.abs(Math.atan2(dy, dx));
  6428. if (Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && (absAngle <= SWIPE_ANGLE_THRESHOLD || absAngle >= Math.PI - SWIPE_ANGLE_THRESHOLD)) {
  6429. delta = dx;
  6430. } else if (Math.abs(dy) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(absAngle - Math.PI / 2) <= SWIPE_ANGLE_THRESHOLD) {
  6431. delta = dy;
  6432. }
  6433. if (delta > 0) {
  6434. this.pdfViewer.previousPage();
  6435. } else if (delta < 0) {
  6436. this.pdfViewer.nextPage();
  6437. }
  6438. break;
  6439. }
  6440. }
  6441. #addWindowListeners() {
  6442. if (this.#windowAbortController) {
  6443. return;
  6444. }
  6445. this.#windowAbortController = new AbortController();
  6446. const {
  6447. signal
  6448. } = this.#windowAbortController;
  6449. const touchSwipeBind = this.#touchSwipe.bind(this);
  6450. window.addEventListener("mousemove", this.#showControls.bind(this), {
  6451. signal
  6452. });
  6453. window.addEventListener("mousedown", this.#mouseDown.bind(this), {
  6454. signal
  6455. });
  6456. window.addEventListener("wheel", this.#mouseWheel.bind(this), {
  6457. passive: false,
  6458. signal
  6459. });
  6460. window.addEventListener("keydown", this.#resetMouseScrollState.bind(this), {
  6461. signal
  6462. });
  6463. window.addEventListener("contextmenu", this.#contextMenu.bind(this), {
  6464. signal
  6465. });
  6466. window.addEventListener("touchstart", touchSwipeBind, {
  6467. signal
  6468. });
  6469. window.addEventListener("touchmove", touchSwipeBind, {
  6470. signal
  6471. });
  6472. window.addEventListener("touchend", touchSwipeBind, {
  6473. signal
  6474. });
  6475. }
  6476. #removeWindowListeners() {
  6477. this.#windowAbortController?.abort();
  6478. this.#windowAbortController = null;
  6479. }
  6480. #addFullscreenChangeListeners() {
  6481. if (this.#fullscreenChangeAbortController) {
  6482. return;
  6483. }
  6484. this.#fullscreenChangeAbortController = new AbortController();
  6485. window.addEventListener("fullscreenchange", () => {
  6486. if (document.fullscreenElement) {
  6487. this.#enter();
  6488. } else {
  6489. this.#exit();
  6490. }
  6491. }, {
  6492. signal: this.#fullscreenChangeAbortController.signal
  6493. });
  6494. }
  6495. #removeFullscreenChangeListeners() {
  6496. this.#fullscreenChangeAbortController?.abort();
  6497. this.#fullscreenChangeAbortController = null;
  6498. }
  6499. }
  6500. ;// CONCATENATED MODULE: ./web/xfa_layer_builder.js
  6501. class XfaLayerBuilder {
  6502. constructor({
  6503. pdfPage,
  6504. annotationStorage = null,
  6505. linkService,
  6506. xfaHtml = null
  6507. }) {
  6508. this.pdfPage = pdfPage;
  6509. this.annotationStorage = annotationStorage;
  6510. this.linkService = linkService;
  6511. this.xfaHtml = xfaHtml;
  6512. this.div = null;
  6513. this._cancelled = false;
  6514. }
  6515. async render(viewport, intent = "display") {
  6516. if (intent === "print") {
  6517. const parameters = {
  6518. viewport: viewport.clone({
  6519. dontFlip: true
  6520. }),
  6521. div: this.div,
  6522. xfaHtml: this.xfaHtml,
  6523. annotationStorage: this.annotationStorage,
  6524. linkService: this.linkService,
  6525. intent
  6526. };
  6527. this.div = document.createElement("div");
  6528. parameters.div = this.div;
  6529. return XfaLayer.render(parameters);
  6530. }
  6531. const xfaHtml = await this.pdfPage.getXfa();
  6532. if (this._cancelled || !xfaHtml) {
  6533. return {
  6534. textDivs: []
  6535. };
  6536. }
  6537. const parameters = {
  6538. viewport: viewport.clone({
  6539. dontFlip: true
  6540. }),
  6541. div: this.div,
  6542. xfaHtml,
  6543. annotationStorage: this.annotationStorage,
  6544. linkService: this.linkService,
  6545. intent
  6546. };
  6547. if (this.div) {
  6548. return XfaLayer.update(parameters);
  6549. }
  6550. this.div = document.createElement("div");
  6551. parameters.div = this.div;
  6552. return XfaLayer.render(parameters);
  6553. }
  6554. cancel() {
  6555. this._cancelled = true;
  6556. }
  6557. hide() {
  6558. if (!this.div) {
  6559. return;
  6560. }
  6561. this.div.hidden = true;
  6562. }
  6563. }
  6564. ;// CONCATENATED MODULE: ./web/print_utils.js
  6565. function getXfaHtmlForPrinting(printContainer, pdfDocument) {
  6566. const xfaHtml = pdfDocument.allXfaHtml;
  6567. const linkService = new SimpleLinkService();
  6568. const scale = Math.round(PixelsPerInch.PDF_TO_CSS_UNITS * 100) / 100;
  6569. for (const xfaPage of xfaHtml.children) {
  6570. const page = document.createElement("div");
  6571. page.className = "xfaPrintedPage";
  6572. printContainer.append(page);
  6573. const builder = new XfaLayerBuilder({
  6574. pdfPage: null,
  6575. annotationStorage: pdfDocument.annotationStorage,
  6576. linkService,
  6577. xfaHtml: xfaPage
  6578. });
  6579. const viewport = getXfaPageViewport(xfaPage, {
  6580. scale
  6581. });
  6582. builder.render(viewport, "print");
  6583. page.append(builder.div);
  6584. }
  6585. }
  6586. ;// CONCATENATED MODULE: ./web/pdf_print_service.js
  6587. let activeService = null;
  6588. let dialog = null;
  6589. let overlayManager = null;
  6590. let viewerApp = {
  6591. initialized: false
  6592. };
  6593. function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printResolution, optionalContentConfigPromise, printAnnotationStoragePromise) {
  6594. const scratchCanvas = activeService.scratchCanvas;
  6595. const PRINT_UNITS = printResolution / PixelsPerInch.PDF;
  6596. scratchCanvas.width = Math.floor(size.width * PRINT_UNITS);
  6597. scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);
  6598. const ctx = scratchCanvas.getContext("2d");
  6599. ctx.save();
  6600. ctx.fillStyle = "rgb(255, 255, 255)";
  6601. ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
  6602. ctx.restore();
  6603. return Promise.all([pdfDocument.getPage(pageNumber), printAnnotationStoragePromise]).then(function ([pdfPage, printAnnotationStorage]) {
  6604. const renderContext = {
  6605. canvasContext: ctx,
  6606. transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0],
  6607. viewport: pdfPage.getViewport({
  6608. scale: 1,
  6609. rotation: size.rotation
  6610. }),
  6611. intent: "print",
  6612. annotationMode: AnnotationMode.ENABLE_STORAGE,
  6613. optionalContentConfigPromise,
  6614. printAnnotationStorage
  6615. };
  6616. const renderTask = pdfPage.render(renderContext);
  6617. return renderTask.promise.catch(reason => {
  6618. if (!(reason instanceof RenderingCancelledException)) {
  6619. console.error(reason);
  6620. }
  6621. throw reason;
  6622. });
  6623. });
  6624. }
  6625. class PDFPrintService {
  6626. constructor({
  6627. pdfDocument,
  6628. pagesOverview,
  6629. printContainer,
  6630. printResolution,
  6631. printAnnotationStoragePromise = null
  6632. }) {
  6633. this.pdfDocument = pdfDocument;
  6634. this.pagesOverview = pagesOverview;
  6635. this.printContainer = printContainer;
  6636. this._printResolution = printResolution || 150;
  6637. this._optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({
  6638. intent: "print"
  6639. });
  6640. this._printAnnotationStoragePromise = printAnnotationStoragePromise || Promise.resolve();
  6641. this.currentPage = -1;
  6642. this.scratchCanvas = document.createElement("canvas");
  6643. }
  6644. layout() {
  6645. this.throwIfInactive();
  6646. const body = document.querySelector("body");
  6647. body.setAttribute("data-pdfjsprinting", true);
  6648. const {
  6649. width,
  6650. height
  6651. } = this.pagesOverview[0];
  6652. const hasEqualPageSizes = this.pagesOverview.every(size => size.width === width && size.height === height);
  6653. if (!hasEqualPageSizes) {
  6654. console.warn("Not all pages have the same size. The printed result may be incorrect!");
  6655. }
  6656. this.pageStyleSheet = document.createElement("style");
  6657. this.pageStyleSheet.textContent = `@page { size: ${width}pt ${height}pt;}`;
  6658. body.append(this.pageStyleSheet);
  6659. }
  6660. destroy() {
  6661. if (activeService !== this) {
  6662. return;
  6663. }
  6664. this.printContainer.textContent = "";
  6665. const body = document.querySelector("body");
  6666. body.removeAttribute("data-pdfjsprinting");
  6667. if (this.pageStyleSheet) {
  6668. this.pageStyleSheet.remove();
  6669. this.pageStyleSheet = null;
  6670. }
  6671. this.scratchCanvas.width = this.scratchCanvas.height = 0;
  6672. this.scratchCanvas = null;
  6673. activeService = null;
  6674. ensureOverlay().then(function () {
  6675. if (overlayManager.active === dialog) {
  6676. overlayManager.close(dialog);
  6677. }
  6678. });
  6679. }
  6680. renderPages() {
  6681. if (this.pdfDocument.isPureXfa) {
  6682. getXfaHtmlForPrinting(this.printContainer, this.pdfDocument);
  6683. return Promise.resolve();
  6684. }
  6685. const pageCount = this.pagesOverview.length;
  6686. const renderNextPage = (resolve, reject) => {
  6687. this.throwIfInactive();
  6688. if (++this.currentPage >= pageCount) {
  6689. renderProgress(pageCount, pageCount);
  6690. resolve();
  6691. return;
  6692. }
  6693. const index = this.currentPage;
  6694. renderProgress(index, pageCount);
  6695. renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index], this._printResolution, this._optionalContentConfigPromise, this._printAnnotationStoragePromise).then(this.useRenderedPage.bind(this)).then(function () {
  6696. renderNextPage(resolve, reject);
  6697. }, reject);
  6698. };
  6699. return new Promise(renderNextPage);
  6700. }
  6701. useRenderedPage() {
  6702. this.throwIfInactive();
  6703. const img = document.createElement("img");
  6704. const scratchCanvas = this.scratchCanvas;
  6705. if ("toBlob" in scratchCanvas) {
  6706. scratchCanvas.toBlob(function (blob) {
  6707. img.src = URL.createObjectURL(blob);
  6708. });
  6709. } else {
  6710. img.src = scratchCanvas.toDataURL();
  6711. }
  6712. const wrapper = document.createElement("div");
  6713. wrapper.className = "printedPage";
  6714. wrapper.append(img);
  6715. this.printContainer.append(wrapper);
  6716. return new Promise(function (resolve, reject) {
  6717. img.onload = resolve;
  6718. img.onerror = reject;
  6719. });
  6720. }
  6721. performPrint() {
  6722. this.throwIfInactive();
  6723. return new Promise(resolve => {
  6724. setTimeout(() => {
  6725. if (!this.active) {
  6726. resolve();
  6727. return;
  6728. }
  6729. print.call(window);
  6730. setTimeout(resolve, 20);
  6731. }, 0);
  6732. });
  6733. }
  6734. get active() {
  6735. return this === activeService;
  6736. }
  6737. throwIfInactive() {
  6738. if (!this.active) {
  6739. throw new Error("This print request was cancelled or completed.");
  6740. }
  6741. }
  6742. }
  6743. const print = window.print;
  6744. window.print = function () {
  6745. if (activeService) {
  6746. console.warn("Ignored window.print() because of a pending print job.");
  6747. return;
  6748. }
  6749. ensureOverlay().then(function () {
  6750. if (activeService) {
  6751. overlayManager.open(dialog);
  6752. }
  6753. });
  6754. try {
  6755. dispatchEvent("beforeprint");
  6756. } finally {
  6757. if (!activeService) {
  6758. console.error("Expected print service to be initialized.");
  6759. ensureOverlay().then(function () {
  6760. if (overlayManager.active === dialog) {
  6761. overlayManager.close(dialog);
  6762. }
  6763. });
  6764. return;
  6765. }
  6766. const activeServiceOnEntry = activeService;
  6767. activeService.renderPages().then(function () {
  6768. return activeServiceOnEntry.performPrint();
  6769. }).catch(function () {}).then(function () {
  6770. if (activeServiceOnEntry.active) {
  6771. abort();
  6772. }
  6773. });
  6774. }
  6775. };
  6776. function dispatchEvent(eventType) {
  6777. const event = new CustomEvent(eventType, {
  6778. bubbles: false,
  6779. cancelable: false,
  6780. detail: "custom"
  6781. });
  6782. window.dispatchEvent(event);
  6783. }
  6784. function abort() {
  6785. if (activeService) {
  6786. activeService.destroy();
  6787. dispatchEvent("afterprint");
  6788. }
  6789. }
  6790. function renderProgress(index, total) {
  6791. dialog ||= document.getElementById("printServiceDialog");
  6792. const progress = Math.round(100 * index / total);
  6793. const progressBar = dialog.querySelector("progress");
  6794. const progressPerc = dialog.querySelector(".relative-progress");
  6795. progressBar.value = progress;
  6796. progressPerc.setAttribute("data-l10n-args", JSON.stringify({
  6797. progress
  6798. }));
  6799. }
  6800. window.addEventListener("keydown", function (event) {
  6801. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  6802. window.print();
  6803. event.preventDefault();
  6804. event.stopImmediatePropagation();
  6805. }
  6806. }, true);
  6807. if ("onbeforeprint" in window) {
  6808. const stopPropagationIfNeeded = function (event) {
  6809. if (event.detail !== "custom") {
  6810. event.stopImmediatePropagation();
  6811. }
  6812. };
  6813. window.addEventListener("beforeprint", stopPropagationIfNeeded);
  6814. window.addEventListener("afterprint", stopPropagationIfNeeded);
  6815. }
  6816. let overlayPromise;
  6817. function ensureOverlay() {
  6818. if (!overlayPromise) {
  6819. overlayManager = viewerApp.overlayManager;
  6820. if (!overlayManager) {
  6821. throw new Error("The overlay manager has not yet been initialized.");
  6822. }
  6823. dialog ||= document.getElementById("printServiceDialog");
  6824. overlayPromise = overlayManager.register(dialog, true);
  6825. document.getElementById("printCancel").onclick = abort;
  6826. dialog.addEventListener("close", abort);
  6827. }
  6828. return overlayPromise;
  6829. }
  6830. class PDFPrintServiceFactory {
  6831. static initGlobals(app) {
  6832. viewerApp = app;
  6833. }
  6834. static get supportsPrinting() {
  6835. return shadow(this, "supportsPrinting", true);
  6836. }
  6837. static createPrintService(params) {
  6838. if (activeService) {
  6839. throw new Error("The print service is created and active.");
  6840. }
  6841. return activeService = new PDFPrintService(params);
  6842. }
  6843. }
  6844. ;// CONCATENATED MODULE: ./web/pdf_rendering_queue.js
  6845. const CLEANUP_TIMEOUT = 30000;
  6846. class PDFRenderingQueue {
  6847. constructor() {
  6848. this.pdfViewer = null;
  6849. this.pdfThumbnailViewer = null;
  6850. this.onIdle = null;
  6851. this.highestPriorityPage = null;
  6852. this.idleTimeout = null;
  6853. this.printing = false;
  6854. this.isThumbnailViewEnabled = false;
  6855. Object.defineProperty(this, "hasViewer", {
  6856. value: () => !!this.pdfViewer
  6857. });
  6858. }
  6859. setViewer(pdfViewer) {
  6860. this.pdfViewer = pdfViewer;
  6861. }
  6862. setThumbnailViewer(pdfThumbnailViewer) {
  6863. this.pdfThumbnailViewer = pdfThumbnailViewer;
  6864. }
  6865. isHighestPriority(view) {
  6866. return this.highestPriorityPage === view.renderingId;
  6867. }
  6868. renderHighestPriority(currentlyVisiblePages) {
  6869. if (this.idleTimeout) {
  6870. clearTimeout(this.idleTimeout);
  6871. this.idleTimeout = null;
  6872. }
  6873. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  6874. return;
  6875. }
  6876. if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) {
  6877. return;
  6878. }
  6879. if (this.printing) {
  6880. return;
  6881. }
  6882. if (this.onIdle) {
  6883. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  6884. }
  6885. }
  6886. getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) {
  6887. const visibleViews = visible.views,
  6888. numVisible = visibleViews.length;
  6889. if (numVisible === 0) {
  6890. return null;
  6891. }
  6892. for (let i = 0; i < numVisible; i++) {
  6893. const view = visibleViews[i].view;
  6894. if (!this.isViewFinished(view)) {
  6895. return view;
  6896. }
  6897. }
  6898. const firstId = visible.first.id,
  6899. lastId = visible.last.id;
  6900. if (lastId - firstId + 1 > numVisible) {
  6901. const visibleIds = visible.ids;
  6902. for (let i = 1, ii = lastId - firstId; i < ii; i++) {
  6903. const holeId = scrolledDown ? firstId + i : lastId - i;
  6904. if (visibleIds.has(holeId)) {
  6905. continue;
  6906. }
  6907. const holeView = views[holeId - 1];
  6908. if (!this.isViewFinished(holeView)) {
  6909. return holeView;
  6910. }
  6911. }
  6912. }
  6913. let preRenderIndex = scrolledDown ? lastId : firstId - 2;
  6914. let preRenderView = views[preRenderIndex];
  6915. if (preRenderView && !this.isViewFinished(preRenderView)) {
  6916. return preRenderView;
  6917. }
  6918. if (preRenderExtra) {
  6919. preRenderIndex += scrolledDown ? 1 : -1;
  6920. preRenderView = views[preRenderIndex];
  6921. if (preRenderView && !this.isViewFinished(preRenderView)) {
  6922. return preRenderView;
  6923. }
  6924. }
  6925. return null;
  6926. }
  6927. isViewFinished(view) {
  6928. return view.renderingState === RenderingStates.FINISHED;
  6929. }
  6930. renderView(view) {
  6931. switch (view.renderingState) {
  6932. case RenderingStates.FINISHED:
  6933. return false;
  6934. case RenderingStates.PAUSED:
  6935. this.highestPriorityPage = view.renderingId;
  6936. view.resume();
  6937. break;
  6938. case RenderingStates.RUNNING:
  6939. this.highestPriorityPage = view.renderingId;
  6940. break;
  6941. case RenderingStates.INITIAL:
  6942. this.highestPriorityPage = view.renderingId;
  6943. view.draw().finally(() => {
  6944. this.renderHighestPriority();
  6945. }).catch(reason => {
  6946. if (reason instanceof RenderingCancelledException) {
  6947. return;
  6948. }
  6949. console.error(`renderView: "${reason}"`);
  6950. });
  6951. break;
  6952. }
  6953. return true;
  6954. }
  6955. }
  6956. ;// CONCATENATED MODULE: ./web/pdf_scripting_manager.js
  6957. class PDFScriptingManager {
  6958. #closeCapability = null;
  6959. #destroyCapability = null;
  6960. #docProperties = null;
  6961. #eventAbortController = null;
  6962. #eventBus = null;
  6963. #externalServices = null;
  6964. #pdfDocument = null;
  6965. #pdfViewer = null;
  6966. #ready = false;
  6967. #scripting = null;
  6968. #willPrintCapability = null;
  6969. constructor({
  6970. eventBus,
  6971. externalServices = null,
  6972. docProperties = null
  6973. }) {
  6974. this.#eventBus = eventBus;
  6975. this.#externalServices = externalServices;
  6976. this.#docProperties = docProperties;
  6977. }
  6978. setViewer(pdfViewer) {
  6979. this.#pdfViewer = pdfViewer;
  6980. }
  6981. async setDocument(pdfDocument) {
  6982. if (this.#pdfDocument) {
  6983. await this.#destroyScripting();
  6984. }
  6985. this.#pdfDocument = pdfDocument;
  6986. if (!pdfDocument) {
  6987. return;
  6988. }
  6989. const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]);
  6990. if (!objects && !docActions) {
  6991. await this.#destroyScripting();
  6992. return;
  6993. }
  6994. if (pdfDocument !== this.#pdfDocument) {
  6995. return;
  6996. }
  6997. try {
  6998. this.#scripting = this.#initScripting();
  6999. } catch (error) {
  7000. console.error(`setDocument: "${error.message}".`);
  7001. await this.#destroyScripting();
  7002. return;
  7003. }
  7004. const eventBus = this.#eventBus;
  7005. this.#eventAbortController = new AbortController();
  7006. const {
  7007. signal
  7008. } = this.#eventAbortController;
  7009. eventBus._on("updatefromsandbox", event => {
  7010. if (event?.source === window) {
  7011. this.#updateFromSandbox(event.detail);
  7012. }
  7013. }, {
  7014. signal
  7015. });
  7016. eventBus._on("dispatcheventinsandbox", event => {
  7017. this.#scripting?.dispatchEventInSandbox(event.detail);
  7018. }, {
  7019. signal
  7020. });
  7021. eventBus._on("pagechanging", ({
  7022. pageNumber,
  7023. previous
  7024. }) => {
  7025. if (pageNumber === previous) {
  7026. return;
  7027. }
  7028. this.#dispatchPageClose(previous);
  7029. this.#dispatchPageOpen(pageNumber);
  7030. }, {
  7031. signal
  7032. });
  7033. eventBus._on("pagerendered", ({
  7034. pageNumber
  7035. }) => {
  7036. if (!this._pageOpenPending.has(pageNumber)) {
  7037. return;
  7038. }
  7039. if (pageNumber !== this.#pdfViewer.currentPageNumber) {
  7040. return;
  7041. }
  7042. this.#dispatchPageOpen(pageNumber);
  7043. }, {
  7044. signal
  7045. });
  7046. eventBus._on("pagesdestroy", async () => {
  7047. await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber);
  7048. await this.#scripting?.dispatchEventInSandbox({
  7049. id: "doc",
  7050. name: "WillClose"
  7051. });
  7052. this.#closeCapability?.resolve();
  7053. }, {
  7054. signal
  7055. });
  7056. try {
  7057. const docProperties = await this.#docProperties(pdfDocument);
  7058. if (pdfDocument !== this.#pdfDocument) {
  7059. return;
  7060. }
  7061. await this.#scripting.createSandbox({
  7062. objects,
  7063. calculationOrder,
  7064. appInfo: {
  7065. platform: navigator.platform,
  7066. language: navigator.language
  7067. },
  7068. docInfo: {
  7069. ...docProperties,
  7070. actions: docActions
  7071. }
  7072. });
  7073. eventBus.dispatch("sandboxcreated", {
  7074. source: this
  7075. });
  7076. } catch (error) {
  7077. console.error(`setDocument: "${error.message}".`);
  7078. await this.#destroyScripting();
  7079. return;
  7080. }
  7081. await this.#scripting?.dispatchEventInSandbox({
  7082. id: "doc",
  7083. name: "Open"
  7084. });
  7085. await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true);
  7086. Promise.resolve().then(() => {
  7087. if (pdfDocument === this.#pdfDocument) {
  7088. this.#ready = true;
  7089. }
  7090. });
  7091. }
  7092. async dispatchWillSave() {
  7093. return this.#scripting?.dispatchEventInSandbox({
  7094. id: "doc",
  7095. name: "WillSave"
  7096. });
  7097. }
  7098. async dispatchDidSave() {
  7099. return this.#scripting?.dispatchEventInSandbox({
  7100. id: "doc",
  7101. name: "DidSave"
  7102. });
  7103. }
  7104. async dispatchWillPrint() {
  7105. if (!this.#scripting) {
  7106. return;
  7107. }
  7108. await this.#willPrintCapability?.promise;
  7109. this.#willPrintCapability = Promise.withResolvers();
  7110. try {
  7111. await this.#scripting.dispatchEventInSandbox({
  7112. id: "doc",
  7113. name: "WillPrint"
  7114. });
  7115. } catch (ex) {
  7116. this.#willPrintCapability.resolve();
  7117. this.#willPrintCapability = null;
  7118. throw ex;
  7119. }
  7120. await this.#willPrintCapability.promise;
  7121. }
  7122. async dispatchDidPrint() {
  7123. return this.#scripting?.dispatchEventInSandbox({
  7124. id: "doc",
  7125. name: "DidPrint"
  7126. });
  7127. }
  7128. get destroyPromise() {
  7129. return this.#destroyCapability?.promise || null;
  7130. }
  7131. get ready() {
  7132. return this.#ready;
  7133. }
  7134. get _pageOpenPending() {
  7135. return shadow(this, "_pageOpenPending", new Set());
  7136. }
  7137. get _visitedPages() {
  7138. return shadow(this, "_visitedPages", new Map());
  7139. }
  7140. async #updateFromSandbox(detail) {
  7141. const pdfViewer = this.#pdfViewer;
  7142. const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode;
  7143. const {
  7144. id,
  7145. siblings,
  7146. command,
  7147. value
  7148. } = detail;
  7149. if (!id) {
  7150. switch (command) {
  7151. case "clear":
  7152. console.clear();
  7153. break;
  7154. case "error":
  7155. console.error(value);
  7156. break;
  7157. case "layout":
  7158. if (!isInPresentationMode) {
  7159. const modes = apiPageLayoutToViewerModes(value);
  7160. pdfViewer.spreadMode = modes.spreadMode;
  7161. }
  7162. break;
  7163. case "page-num":
  7164. pdfViewer.currentPageNumber = value + 1;
  7165. break;
  7166. case "print":
  7167. await pdfViewer.pagesPromise;
  7168. this.#eventBus.dispatch("print", {
  7169. source: this
  7170. });
  7171. break;
  7172. case "println":
  7173. console.log(value);
  7174. break;
  7175. case "zoom":
  7176. if (!isInPresentationMode) {
  7177. pdfViewer.currentScaleValue = value;
  7178. }
  7179. break;
  7180. case "SaveAs":
  7181. this.#eventBus.dispatch("download", {
  7182. source: this
  7183. });
  7184. break;
  7185. case "FirstPage":
  7186. pdfViewer.currentPageNumber = 1;
  7187. break;
  7188. case "LastPage":
  7189. pdfViewer.currentPageNumber = pdfViewer.pagesCount;
  7190. break;
  7191. case "NextPage":
  7192. pdfViewer.nextPage();
  7193. break;
  7194. case "PrevPage":
  7195. pdfViewer.previousPage();
  7196. break;
  7197. case "ZoomViewIn":
  7198. if (!isInPresentationMode) {
  7199. pdfViewer.increaseScale();
  7200. }
  7201. break;
  7202. case "ZoomViewOut":
  7203. if (!isInPresentationMode) {
  7204. pdfViewer.decreaseScale();
  7205. }
  7206. break;
  7207. case "WillPrintFinished":
  7208. this.#willPrintCapability?.resolve();
  7209. this.#willPrintCapability = null;
  7210. break;
  7211. }
  7212. return;
  7213. }
  7214. if (isInPresentationMode && detail.focus) {
  7215. return;
  7216. }
  7217. delete detail.id;
  7218. delete detail.siblings;
  7219. const ids = siblings ? [id, ...siblings] : [id];
  7220. for (const elementId of ids) {
  7221. const element = document.querySelector(`[data-element-id="${elementId}"]`);
  7222. if (element) {
  7223. element.dispatchEvent(new CustomEvent("updatefromsandbox", {
  7224. detail
  7225. }));
  7226. } else {
  7227. this.#pdfDocument?.annotationStorage.setValue(elementId, detail);
  7228. }
  7229. }
  7230. }
  7231. async #dispatchPageOpen(pageNumber, initialize = false) {
  7232. const pdfDocument = this.#pdfDocument,
  7233. visitedPages = this._visitedPages;
  7234. if (initialize) {
  7235. this.#closeCapability = Promise.withResolvers();
  7236. }
  7237. if (!this.#closeCapability) {
  7238. return;
  7239. }
  7240. const pageView = this.#pdfViewer.getPageView(pageNumber - 1);
  7241. if (pageView?.renderingState !== RenderingStates.FINISHED) {
  7242. this._pageOpenPending.add(pageNumber);
  7243. return;
  7244. }
  7245. this._pageOpenPending.delete(pageNumber);
  7246. const actionsPromise = (async () => {
  7247. const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null);
  7248. if (pdfDocument !== this.#pdfDocument) {
  7249. return;
  7250. }
  7251. await this.#scripting?.dispatchEventInSandbox({
  7252. id: "page",
  7253. name: "PageOpen",
  7254. pageNumber,
  7255. actions
  7256. });
  7257. })();
  7258. visitedPages.set(pageNumber, actionsPromise);
  7259. }
  7260. async #dispatchPageClose(pageNumber) {
  7261. const pdfDocument = this.#pdfDocument,
  7262. visitedPages = this._visitedPages;
  7263. if (!this.#closeCapability) {
  7264. return;
  7265. }
  7266. if (this._pageOpenPending.has(pageNumber)) {
  7267. return;
  7268. }
  7269. const actionsPromise = visitedPages.get(pageNumber);
  7270. if (!actionsPromise) {
  7271. return;
  7272. }
  7273. visitedPages.set(pageNumber, null);
  7274. await actionsPromise;
  7275. if (pdfDocument !== this.#pdfDocument) {
  7276. return;
  7277. }
  7278. await this.#scripting?.dispatchEventInSandbox({
  7279. id: "page",
  7280. name: "PageClose",
  7281. pageNumber
  7282. });
  7283. }
  7284. #initScripting() {
  7285. this.#destroyCapability = Promise.withResolvers();
  7286. if (this.#scripting) {
  7287. throw new Error("#initScripting: Scripting already exists.");
  7288. }
  7289. return this.#externalServices.createScripting();
  7290. }
  7291. async #destroyScripting() {
  7292. if (!this.#scripting) {
  7293. this.#pdfDocument = null;
  7294. this.#destroyCapability?.resolve();
  7295. return;
  7296. }
  7297. if (this.#closeCapability) {
  7298. await Promise.race([this.#closeCapability.promise, new Promise(resolve => {
  7299. setTimeout(resolve, 1000);
  7300. })]).catch(() => {});
  7301. this.#closeCapability = null;
  7302. }
  7303. this.#pdfDocument = null;
  7304. try {
  7305. await this.#scripting.destroySandbox();
  7306. } catch {}
  7307. this.#willPrintCapability?.reject(new Error("Scripting destroyed."));
  7308. this.#willPrintCapability = null;
  7309. this.#eventAbortController?.abort();
  7310. this.#eventAbortController = null;
  7311. this._pageOpenPending.clear();
  7312. this._visitedPages.clear();
  7313. this.#scripting = null;
  7314. this.#ready = false;
  7315. this.#destroyCapability?.resolve();
  7316. }
  7317. }
  7318. ;// CONCATENATED MODULE: ./web/pdf_sidebar.js
  7319. const SIDEBAR_WIDTH_VAR = "--sidebar-width";
  7320. const SIDEBAR_MIN_WIDTH = 200;
  7321. const SIDEBAR_RESIZING_CLASS = "sidebarResizing";
  7322. const UI_NOTIFICATION_CLASS = "pdfSidebarNotification";
  7323. class PDFSidebar {
  7324. #isRTL = false;
  7325. #mouseMoveBound = this.#mouseMove.bind(this);
  7326. #mouseUpBound = this.#mouseUp.bind(this);
  7327. #outerContainerWidth = null;
  7328. #width = null;
  7329. constructor({
  7330. elements,
  7331. eventBus,
  7332. l10n
  7333. }) {
  7334. this.isOpen = false;
  7335. this.active = SidebarView.THUMBS;
  7336. this.isInitialViewSet = false;
  7337. this.isInitialEventDispatched = false;
  7338. this.onToggled = null;
  7339. this.onUpdateThumbnails = null;
  7340. this.outerContainer = elements.outerContainer;
  7341. this.sidebarContainer = elements.sidebarContainer;
  7342. this.toggleButton = elements.toggleButton;
  7343. this.resizer = elements.resizer;
  7344. this.thumbnailButton = elements.thumbnailButton;
  7345. this.outlineButton = elements.outlineButton;
  7346. this.attachmentsButton = elements.attachmentsButton;
  7347. this.layersButton = elements.layersButton;
  7348. this.thumbnailView = elements.thumbnailView;
  7349. this.outlineView = elements.outlineView;
  7350. this.attachmentsView = elements.attachmentsView;
  7351. this.layersView = elements.layersView;
  7352. this._currentOutlineItemButton = elements.currentOutlineItemButton;
  7353. this.eventBus = eventBus;
  7354. this.#isRTL = l10n.getDirection() === "rtl";
  7355. this.#addEventListeners();
  7356. }
  7357. reset() {
  7358. this.isInitialViewSet = false;
  7359. this.isInitialEventDispatched = false;
  7360. this.#hideUINotification(true);
  7361. this.switchView(SidebarView.THUMBS);
  7362. this.outlineButton.disabled = false;
  7363. this.attachmentsButton.disabled = false;
  7364. this.layersButton.disabled = false;
  7365. this._currentOutlineItemButton.disabled = true;
  7366. }
  7367. get visibleView() {
  7368. return this.isOpen ? this.active : SidebarView.NONE;
  7369. }
  7370. setInitialView(view = SidebarView.NONE) {
  7371. if (this.isInitialViewSet) {
  7372. return;
  7373. }
  7374. this.isInitialViewSet = true;
  7375. if (view === SidebarView.NONE || view === SidebarView.UNKNOWN) {
  7376. this.#dispatchEvent();
  7377. return;
  7378. }
  7379. this.switchView(view, true);
  7380. if (!this.isInitialEventDispatched) {
  7381. this.#dispatchEvent();
  7382. }
  7383. }
  7384. switchView(view, forceOpen = false) {
  7385. const isViewChanged = view !== this.active;
  7386. let forceRendering = false;
  7387. switch (view) {
  7388. case SidebarView.NONE:
  7389. if (this.isOpen) {
  7390. this.close();
  7391. }
  7392. return;
  7393. case SidebarView.THUMBS:
  7394. if (this.isOpen && isViewChanged) {
  7395. forceRendering = true;
  7396. }
  7397. break;
  7398. case SidebarView.OUTLINE:
  7399. if (this.outlineButton.disabled) {
  7400. return;
  7401. }
  7402. break;
  7403. case SidebarView.ATTACHMENTS:
  7404. if (this.attachmentsButton.disabled) {
  7405. return;
  7406. }
  7407. break;
  7408. case SidebarView.LAYERS:
  7409. if (this.layersButton.disabled) {
  7410. return;
  7411. }
  7412. break;
  7413. default:
  7414. console.error(`PDFSidebar.switchView: "${view}" is not a valid view.`);
  7415. return;
  7416. }
  7417. this.active = view;
  7418. toggleCheckedBtn(this.thumbnailButton, view === SidebarView.THUMBS, this.thumbnailView);
  7419. toggleCheckedBtn(this.outlineButton, view === SidebarView.OUTLINE, this.outlineView);
  7420. toggleCheckedBtn(this.attachmentsButton, view === SidebarView.ATTACHMENTS, this.attachmentsView);
  7421. toggleCheckedBtn(this.layersButton, view === SidebarView.LAYERS, this.layersView);
  7422. if (forceOpen && !this.isOpen) {
  7423. this.open();
  7424. return;
  7425. }
  7426. if (forceRendering) {
  7427. this.onUpdateThumbnails();
  7428. this.onToggled();
  7429. }
  7430. if (isViewChanged) {
  7431. this.#dispatchEvent();
  7432. }
  7433. }
  7434. open() {
  7435. if (this.isOpen) {
  7436. return;
  7437. }
  7438. this.isOpen = true;
  7439. toggleExpandedBtn(this.toggleButton, true);
  7440. this.outerContainer.classList.add("sidebarMoving", "sidebarOpen");
  7441. if (this.active === SidebarView.THUMBS) {
  7442. this.onUpdateThumbnails();
  7443. }
  7444. this.onToggled();
  7445. this.#dispatchEvent();
  7446. this.#hideUINotification();
  7447. }
  7448. close(evt = null) {
  7449. if (!this.isOpen) {
  7450. return;
  7451. }
  7452. this.isOpen = false;
  7453. toggleExpandedBtn(this.toggleButton, false);
  7454. this.outerContainer.classList.add("sidebarMoving");
  7455. this.outerContainer.classList.remove("sidebarOpen");
  7456. this.onToggled();
  7457. this.#dispatchEvent();
  7458. if (evt?.detail > 0) {
  7459. this.toggleButton.blur();
  7460. }
  7461. }
  7462. toggle(evt = null) {
  7463. if (this.isOpen) {
  7464. this.close(evt);
  7465. } else {
  7466. this.open();
  7467. }
  7468. }
  7469. #dispatchEvent() {
  7470. if (this.isInitialViewSet) {
  7471. this.isInitialEventDispatched ||= true;
  7472. }
  7473. this.eventBus.dispatch("sidebarviewchanged", {
  7474. source: this,
  7475. view: this.visibleView
  7476. });
  7477. }
  7478. #showUINotification() {
  7479. this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-notification-button");
  7480. if (!this.isOpen) {
  7481. this.toggleButton.classList.add(UI_NOTIFICATION_CLASS);
  7482. }
  7483. }
  7484. #hideUINotification(reset = false) {
  7485. if (this.isOpen || reset) {
  7486. this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS);
  7487. }
  7488. if (reset) {
  7489. this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-button");
  7490. }
  7491. }
  7492. #addEventListeners() {
  7493. this.sidebarContainer.addEventListener("transitionend", evt => {
  7494. if (evt.target === this.sidebarContainer) {
  7495. this.outerContainer.classList.remove("sidebarMoving");
  7496. this.eventBus.dispatch("resize", {
  7497. source: this
  7498. });
  7499. }
  7500. });
  7501. this.toggleButton.addEventListener("click", evt => {
  7502. this.toggle(evt);
  7503. });
  7504. this.thumbnailButton.addEventListener("click", () => {
  7505. this.switchView(SidebarView.THUMBS);
  7506. });
  7507. this.outlineButton.addEventListener("click", () => {
  7508. this.switchView(SidebarView.OUTLINE);
  7509. });
  7510. this.outlineButton.addEventListener("dblclick", () => {
  7511. this.eventBus.dispatch("toggleoutlinetree", {
  7512. source: this
  7513. });
  7514. });
  7515. this.attachmentsButton.addEventListener("click", () => {
  7516. this.switchView(SidebarView.ATTACHMENTS);
  7517. });
  7518. this.layersButton.addEventListener("click", () => {
  7519. this.switchView(SidebarView.LAYERS);
  7520. });
  7521. this.layersButton.addEventListener("dblclick", () => {
  7522. this.eventBus.dispatch("resetlayers", {
  7523. source: this
  7524. });
  7525. });
  7526. this._currentOutlineItemButton.addEventListener("click", () => {
  7527. this.eventBus.dispatch("currentoutlineitem", {
  7528. source: this
  7529. });
  7530. });
  7531. const onTreeLoaded = (count, button, view) => {
  7532. button.disabled = !count;
  7533. if (count) {
  7534. this.#showUINotification();
  7535. } else if (this.active === view) {
  7536. this.switchView(SidebarView.THUMBS);
  7537. }
  7538. };
  7539. this.eventBus._on("outlineloaded", evt => {
  7540. onTreeLoaded(evt.outlineCount, this.outlineButton, SidebarView.OUTLINE);
  7541. evt.currentOutlineItemPromise.then(enabled => {
  7542. if (!this.isInitialViewSet) {
  7543. return;
  7544. }
  7545. this._currentOutlineItemButton.disabled = !enabled;
  7546. });
  7547. });
  7548. this.eventBus._on("attachmentsloaded", evt => {
  7549. onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, SidebarView.ATTACHMENTS);
  7550. });
  7551. this.eventBus._on("layersloaded", evt => {
  7552. onTreeLoaded(evt.layersCount, this.layersButton, SidebarView.LAYERS);
  7553. });
  7554. this.eventBus._on("presentationmodechanged", evt => {
  7555. if (evt.state === PresentationModeState.NORMAL && this.visibleView === SidebarView.THUMBS) {
  7556. this.onUpdateThumbnails();
  7557. }
  7558. });
  7559. this.resizer.addEventListener("mousedown", evt => {
  7560. if (evt.button !== 0) {
  7561. return;
  7562. }
  7563. this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS);
  7564. window.addEventListener("mousemove", this.#mouseMoveBound);
  7565. window.addEventListener("mouseup", this.#mouseUpBound);
  7566. });
  7567. this.eventBus._on("resize", evt => {
  7568. if (evt.source !== window) {
  7569. return;
  7570. }
  7571. this.#outerContainerWidth = null;
  7572. if (!this.#width) {
  7573. return;
  7574. }
  7575. if (!this.isOpen) {
  7576. this.#updateWidth(this.#width);
  7577. return;
  7578. }
  7579. this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS);
  7580. const updated = this.#updateWidth(this.#width);
  7581. Promise.resolve().then(() => {
  7582. this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS);
  7583. if (updated) {
  7584. this.eventBus.dispatch("resize", {
  7585. source: this
  7586. });
  7587. }
  7588. });
  7589. });
  7590. }
  7591. get outerContainerWidth() {
  7592. return this.#outerContainerWidth ||= this.outerContainer.clientWidth;
  7593. }
  7594. #updateWidth(width = 0) {
  7595. const maxWidth = Math.floor(this.outerContainerWidth / 2);
  7596. if (width > maxWidth) {
  7597. width = maxWidth;
  7598. }
  7599. if (width < SIDEBAR_MIN_WIDTH) {
  7600. width = SIDEBAR_MIN_WIDTH;
  7601. }
  7602. if (width === this.#width) {
  7603. return false;
  7604. }
  7605. this.#width = width;
  7606. docStyle.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`);
  7607. return true;
  7608. }
  7609. #mouseMove(evt) {
  7610. let width = evt.clientX;
  7611. if (this.#isRTL) {
  7612. width = this.outerContainerWidth - width;
  7613. }
  7614. this.#updateWidth(width);
  7615. }
  7616. #mouseUp(evt) {
  7617. this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS);
  7618. this.eventBus.dispatch("resize", {
  7619. source: this
  7620. });
  7621. window.removeEventListener("mousemove", this.#mouseMoveBound);
  7622. window.removeEventListener("mouseup", this.#mouseUpBound);
  7623. }
  7624. }
  7625. ;// CONCATENATED MODULE: ./web/pdf_thumbnail_view.js
  7626. const DRAW_UPSCALE_FACTOR = 2;
  7627. const MAX_NUM_SCALING_STEPS = 3;
  7628. const THUMBNAIL_WIDTH = 98;
  7629. class TempImageFactory {
  7630. static #tempCanvas = null;
  7631. static getCanvas(width, height) {
  7632. const tempCanvas = this.#tempCanvas ||= document.createElement("canvas");
  7633. tempCanvas.width = width;
  7634. tempCanvas.height = height;
  7635. const ctx = tempCanvas.getContext("2d", {
  7636. alpha: false
  7637. });
  7638. ctx.save();
  7639. ctx.fillStyle = "rgb(255, 255, 255)";
  7640. ctx.fillRect(0, 0, width, height);
  7641. ctx.restore();
  7642. return [tempCanvas, tempCanvas.getContext("2d")];
  7643. }
  7644. static destroyCanvas() {
  7645. const tempCanvas = this.#tempCanvas;
  7646. if (tempCanvas) {
  7647. tempCanvas.width = 0;
  7648. tempCanvas.height = 0;
  7649. }
  7650. this.#tempCanvas = null;
  7651. }
  7652. }
  7653. class PDFThumbnailView {
  7654. constructor({
  7655. container,
  7656. eventBus,
  7657. id,
  7658. defaultViewport,
  7659. optionalContentConfigPromise,
  7660. linkService,
  7661. renderingQueue,
  7662. pageColors,
  7663. enableHWA
  7664. }) {
  7665. this.id = id;
  7666. this.renderingId = "thumbnail" + id;
  7667. this.pageLabel = null;
  7668. this.pdfPage = null;
  7669. this.rotation = 0;
  7670. this.viewport = defaultViewport;
  7671. this.pdfPageRotate = defaultViewport.rotation;
  7672. this._optionalContentConfigPromise = optionalContentConfigPromise || null;
  7673. this.pageColors = pageColors || null;
  7674. this.enableHWA = enableHWA || false;
  7675. this.eventBus = eventBus;
  7676. this.linkService = linkService;
  7677. this.renderingQueue = renderingQueue;
  7678. this.renderTask = null;
  7679. this.renderingState = RenderingStates.INITIAL;
  7680. this.resume = null;
  7681. const anchor = document.createElement("a");
  7682. anchor.href = linkService.getAnchorUrl("#page=" + id);
  7683. anchor.setAttribute("data-l10n-id", "pdfjs-thumb-page-title");
  7684. anchor.setAttribute("data-l10n-args", this.#pageL10nArgs);
  7685. anchor.onclick = function () {
  7686. linkService.goToPage(id);
  7687. return false;
  7688. };
  7689. this.anchor = anchor;
  7690. const div = document.createElement("div");
  7691. div.className = "thumbnail";
  7692. div.setAttribute("data-page-number", this.id);
  7693. this.div = div;
  7694. this.#updateDims();
  7695. const img = document.createElement("div");
  7696. img.className = "thumbnailImage";
  7697. this._placeholderImg = img;
  7698. div.append(img);
  7699. anchor.append(div);
  7700. container.append(anchor);
  7701. }
  7702. #updateDims() {
  7703. const {
  7704. width,
  7705. height
  7706. } = this.viewport;
  7707. const ratio = width / height;
  7708. this.canvasWidth = THUMBNAIL_WIDTH;
  7709. this.canvasHeight = this.canvasWidth / ratio | 0;
  7710. this.scale = this.canvasWidth / width;
  7711. const {
  7712. style
  7713. } = this.div;
  7714. style.setProperty("--thumbnail-width", `${this.canvasWidth}px`);
  7715. style.setProperty("--thumbnail-height", `${this.canvasHeight}px`);
  7716. }
  7717. setPdfPage(pdfPage) {
  7718. this.pdfPage = pdfPage;
  7719. this.pdfPageRotate = pdfPage.rotate;
  7720. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  7721. this.viewport = pdfPage.getViewport({
  7722. scale: 1,
  7723. rotation: totalRotation
  7724. });
  7725. this.reset();
  7726. }
  7727. reset() {
  7728. this.cancelRendering();
  7729. this.renderingState = RenderingStates.INITIAL;
  7730. this.div.removeAttribute("data-loaded");
  7731. this.image?.replaceWith(this._placeholderImg);
  7732. this.#updateDims();
  7733. if (this.image) {
  7734. this.image.removeAttribute("src");
  7735. delete this.image;
  7736. }
  7737. }
  7738. update({
  7739. rotation = null
  7740. }) {
  7741. if (typeof rotation === "number") {
  7742. this.rotation = rotation;
  7743. }
  7744. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  7745. this.viewport = this.viewport.clone({
  7746. scale: 1,
  7747. rotation: totalRotation
  7748. });
  7749. this.reset();
  7750. }
  7751. cancelRendering() {
  7752. if (this.renderTask) {
  7753. this.renderTask.cancel();
  7754. this.renderTask = null;
  7755. }
  7756. this.resume = null;
  7757. }
  7758. #getPageDrawContext(upscaleFactor = 1, enableHWA = this.enableHWA) {
  7759. const canvas = document.createElement("canvas");
  7760. const ctx = canvas.getContext("2d", {
  7761. alpha: false,
  7762. willReadFrequently: !enableHWA
  7763. });
  7764. const outputScale = new OutputScale();
  7765. canvas.width = upscaleFactor * this.canvasWidth * outputScale.sx | 0;
  7766. canvas.height = upscaleFactor * this.canvasHeight * outputScale.sy | 0;
  7767. const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null;
  7768. return {
  7769. ctx,
  7770. canvas,
  7771. transform
  7772. };
  7773. }
  7774. #convertCanvasToImage(canvas) {
  7775. if (this.renderingState !== RenderingStates.FINISHED) {
  7776. throw new Error("#convertCanvasToImage: Rendering has not finished.");
  7777. }
  7778. const reducedCanvas = this.#reduceImage(canvas);
  7779. const image = document.createElement("img");
  7780. image.className = "thumbnailImage";
  7781. image.setAttribute("data-l10n-id", "pdfjs-thumb-page-canvas");
  7782. image.setAttribute("data-l10n-args", this.#pageL10nArgs);
  7783. image.src = reducedCanvas.toDataURL();
  7784. this.image = image;
  7785. this.div.setAttribute("data-loaded", true);
  7786. this._placeholderImg.replaceWith(image);
  7787. reducedCanvas.width = 0;
  7788. reducedCanvas.height = 0;
  7789. }
  7790. async #finishRenderTask(renderTask, canvas, error = null) {
  7791. if (renderTask === this.renderTask) {
  7792. this.renderTask = null;
  7793. }
  7794. if (error instanceof RenderingCancelledException) {
  7795. return;
  7796. }
  7797. this.renderingState = RenderingStates.FINISHED;
  7798. this.#convertCanvasToImage(canvas);
  7799. if (error) {
  7800. throw error;
  7801. }
  7802. }
  7803. async draw() {
  7804. if (this.renderingState !== RenderingStates.INITIAL) {
  7805. console.error("Must be in new state before drawing");
  7806. return undefined;
  7807. }
  7808. const {
  7809. pdfPage
  7810. } = this;
  7811. if (!pdfPage) {
  7812. this.renderingState = RenderingStates.FINISHED;
  7813. throw new Error("pdfPage is not loaded");
  7814. }
  7815. this.renderingState = RenderingStates.RUNNING;
  7816. const {
  7817. ctx,
  7818. canvas,
  7819. transform
  7820. } = this.#getPageDrawContext(DRAW_UPSCALE_FACTOR);
  7821. const drawViewport = this.viewport.clone({
  7822. scale: DRAW_UPSCALE_FACTOR * this.scale
  7823. });
  7824. const renderContinueCallback = cont => {
  7825. if (!this.renderingQueue.isHighestPriority(this)) {
  7826. this.renderingState = RenderingStates.PAUSED;
  7827. this.resume = () => {
  7828. this.renderingState = RenderingStates.RUNNING;
  7829. cont();
  7830. };
  7831. return;
  7832. }
  7833. cont();
  7834. };
  7835. const renderContext = {
  7836. canvasContext: ctx,
  7837. transform,
  7838. viewport: drawViewport,
  7839. optionalContentConfigPromise: this._optionalContentConfigPromise,
  7840. pageColors: this.pageColors
  7841. };
  7842. const renderTask = this.renderTask = pdfPage.render(renderContext);
  7843. renderTask.onContinue = renderContinueCallback;
  7844. const resultPromise = renderTask.promise.then(() => this.#finishRenderTask(renderTask, canvas), error => this.#finishRenderTask(renderTask, canvas, error));
  7845. resultPromise.finally(() => {
  7846. canvas.width = 0;
  7847. canvas.height = 0;
  7848. this.eventBus.dispatch("thumbnailrendered", {
  7849. source: this,
  7850. pageNumber: this.id,
  7851. pdfPage: this.pdfPage
  7852. });
  7853. });
  7854. return resultPromise;
  7855. }
  7856. setImage(pageView) {
  7857. if (this.renderingState !== RenderingStates.INITIAL) {
  7858. return;
  7859. }
  7860. const {
  7861. thumbnailCanvas: canvas,
  7862. pdfPage,
  7863. scale
  7864. } = pageView;
  7865. if (!canvas) {
  7866. return;
  7867. }
  7868. if (!this.pdfPage) {
  7869. this.setPdfPage(pdfPage);
  7870. }
  7871. if (scale < this.scale) {
  7872. return;
  7873. }
  7874. this.renderingState = RenderingStates.FINISHED;
  7875. this.#convertCanvasToImage(canvas);
  7876. }
  7877. #reduceImage(img) {
  7878. const {
  7879. ctx,
  7880. canvas
  7881. } = this.#getPageDrawContext(1, true);
  7882. if (img.width <= 2 * canvas.width) {
  7883. ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
  7884. return canvas;
  7885. }
  7886. let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
  7887. let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
  7888. const [reducedImage, reducedImageCtx] = TempImageFactory.getCanvas(reducedWidth, reducedHeight);
  7889. while (reducedWidth > img.width || reducedHeight > img.height) {
  7890. reducedWidth >>= 1;
  7891. reducedHeight >>= 1;
  7892. }
  7893. reducedImageCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, reducedWidth, reducedHeight);
  7894. while (reducedWidth > 2 * canvas.width) {
  7895. reducedImageCtx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, reducedWidth >> 1, reducedHeight >> 1);
  7896. reducedWidth >>= 1;
  7897. reducedHeight >>= 1;
  7898. }
  7899. ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height);
  7900. return canvas;
  7901. }
  7902. get #pageL10nArgs() {
  7903. return JSON.stringify({
  7904. page: this.pageLabel ?? this.id
  7905. });
  7906. }
  7907. setPageLabel(label) {
  7908. this.pageLabel = typeof label === "string" ? label : null;
  7909. this.anchor.setAttribute("data-l10n-args", this.#pageL10nArgs);
  7910. if (this.renderingState !== RenderingStates.FINISHED) {
  7911. return;
  7912. }
  7913. this.image?.setAttribute("data-l10n-args", this.#pageL10nArgs);
  7914. }
  7915. }
  7916. ;// CONCATENATED MODULE: ./web/pdf_thumbnail_viewer.js
  7917. const THUMBNAIL_SCROLL_MARGIN = -19;
  7918. const THUMBNAIL_SELECTED_CLASS = "selected";
  7919. class PDFThumbnailViewer {
  7920. constructor({
  7921. container,
  7922. eventBus,
  7923. linkService,
  7924. renderingQueue,
  7925. pageColors,
  7926. abortSignal,
  7927. enableHWA
  7928. }) {
  7929. this.container = container;
  7930. this.eventBus = eventBus;
  7931. this.linkService = linkService;
  7932. this.renderingQueue = renderingQueue;
  7933. this.pageColors = pageColors || null;
  7934. this.enableHWA = enableHWA || false;
  7935. this.scroll = watchScroll(this.container, this.#scrollUpdated.bind(this), abortSignal);
  7936. this.#resetView();
  7937. }
  7938. #scrollUpdated() {
  7939. this.renderingQueue.renderHighestPriority();
  7940. }
  7941. getThumbnail(index) {
  7942. return this._thumbnails[index];
  7943. }
  7944. #getVisibleThumbs() {
  7945. return getVisibleElements({
  7946. scrollEl: this.container,
  7947. views: this._thumbnails
  7948. });
  7949. }
  7950. scrollThumbnailIntoView(pageNumber) {
  7951. if (!this.pdfDocument) {
  7952. return;
  7953. }
  7954. const thumbnailView = this._thumbnails[pageNumber - 1];
  7955. if (!thumbnailView) {
  7956. console.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.');
  7957. return;
  7958. }
  7959. if (pageNumber !== this._currentPageNumber) {
  7960. const prevThumbnailView = this._thumbnails[this._currentPageNumber - 1];
  7961. prevThumbnailView.div.classList.remove(THUMBNAIL_SELECTED_CLASS);
  7962. thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS);
  7963. }
  7964. const {
  7965. first,
  7966. last,
  7967. views
  7968. } = this.#getVisibleThumbs();
  7969. if (views.length > 0) {
  7970. let shouldScroll = false;
  7971. if (pageNumber <= first.id || pageNumber >= last.id) {
  7972. shouldScroll = true;
  7973. } else {
  7974. for (const {
  7975. id,
  7976. percent
  7977. } of views) {
  7978. if (id !== pageNumber) {
  7979. continue;
  7980. }
  7981. shouldScroll = percent < 100;
  7982. break;
  7983. }
  7984. }
  7985. if (shouldScroll) {
  7986. scrollIntoView(thumbnailView.div, {
  7987. top: THUMBNAIL_SCROLL_MARGIN
  7988. });
  7989. }
  7990. }
  7991. this._currentPageNumber = pageNumber;
  7992. }
  7993. get pagesRotation() {
  7994. return this._pagesRotation;
  7995. }
  7996. set pagesRotation(rotation) {
  7997. if (!isValidRotation(rotation)) {
  7998. throw new Error("Invalid thumbnails rotation angle.");
  7999. }
  8000. if (!this.pdfDocument) {
  8001. return;
  8002. }
  8003. if (this._pagesRotation === rotation) {
  8004. return;
  8005. }
  8006. this._pagesRotation = rotation;
  8007. const updateArgs = {
  8008. rotation
  8009. };
  8010. for (const thumbnail of this._thumbnails) {
  8011. thumbnail.update(updateArgs);
  8012. }
  8013. }
  8014. cleanup() {
  8015. for (const thumbnail of this._thumbnails) {
  8016. if (thumbnail.renderingState !== RenderingStates.FINISHED) {
  8017. thumbnail.reset();
  8018. }
  8019. }
  8020. TempImageFactory.destroyCanvas();
  8021. }
  8022. #resetView() {
  8023. this._thumbnails = [];
  8024. this._currentPageNumber = 1;
  8025. this._pageLabels = null;
  8026. this._pagesRotation = 0;
  8027. this.container.textContent = "";
  8028. }
  8029. setDocument(pdfDocument) {
  8030. if (this.pdfDocument) {
  8031. this.#cancelRendering();
  8032. this.#resetView();
  8033. }
  8034. this.pdfDocument = pdfDocument;
  8035. if (!pdfDocument) {
  8036. return;
  8037. }
  8038. const firstPagePromise = pdfDocument.getPage(1);
  8039. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({
  8040. intent: "display"
  8041. });
  8042. firstPagePromise.then(firstPdfPage => {
  8043. const pagesCount = pdfDocument.numPages;
  8044. const viewport = firstPdfPage.getViewport({
  8045. scale: 1
  8046. });
  8047. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  8048. const thumbnail = new PDFThumbnailView({
  8049. container: this.container,
  8050. eventBus: this.eventBus,
  8051. id: pageNum,
  8052. defaultViewport: viewport.clone(),
  8053. optionalContentConfigPromise,
  8054. linkService: this.linkService,
  8055. renderingQueue: this.renderingQueue,
  8056. pageColors: this.pageColors,
  8057. enableHWA: this.enableHWA
  8058. });
  8059. this._thumbnails.push(thumbnail);
  8060. }
  8061. this._thumbnails[0]?.setPdfPage(firstPdfPage);
  8062. const thumbnailView = this._thumbnails[this._currentPageNumber - 1];
  8063. thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS);
  8064. }).catch(reason => {
  8065. console.error("Unable to initialize thumbnail viewer", reason);
  8066. });
  8067. }
  8068. #cancelRendering() {
  8069. for (const thumbnail of this._thumbnails) {
  8070. thumbnail.cancelRendering();
  8071. }
  8072. }
  8073. setPageLabels(labels) {
  8074. if (!this.pdfDocument) {
  8075. return;
  8076. }
  8077. if (!labels) {
  8078. this._pageLabels = null;
  8079. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  8080. this._pageLabels = null;
  8081. console.error("PDFThumbnailViewer_setPageLabels: Invalid page labels.");
  8082. } else {
  8083. this._pageLabels = labels;
  8084. }
  8085. for (let i = 0, ii = this._thumbnails.length; i < ii; i++) {
  8086. this._thumbnails[i].setPageLabel(this._pageLabels?.[i] ?? null);
  8087. }
  8088. }
  8089. async #ensurePdfPageLoaded(thumbView) {
  8090. if (thumbView.pdfPage) {
  8091. return thumbView.pdfPage;
  8092. }
  8093. try {
  8094. const pdfPage = await this.pdfDocument.getPage(thumbView.id);
  8095. if (!thumbView.pdfPage) {
  8096. thumbView.setPdfPage(pdfPage);
  8097. }
  8098. return pdfPage;
  8099. } catch (reason) {
  8100. console.error("Unable to get page for thumb view", reason);
  8101. return null;
  8102. }
  8103. }
  8104. #getScrollAhead(visible) {
  8105. if (visible.first?.id === 1) {
  8106. return true;
  8107. } else if (visible.last?.id === this._thumbnails.length) {
  8108. return false;
  8109. }
  8110. return this.scroll.down;
  8111. }
  8112. forceRendering() {
  8113. const visibleThumbs = this.#getVisibleThumbs();
  8114. const scrollAhead = this.#getScrollAhead(visibleThumbs);
  8115. const thumbView = this.renderingQueue.getHighestPriority(visibleThumbs, this._thumbnails, scrollAhead);
  8116. if (thumbView) {
  8117. this.#ensurePdfPageLoaded(thumbView).then(() => {
  8118. this.renderingQueue.renderView(thumbView);
  8119. });
  8120. return true;
  8121. }
  8122. return false;
  8123. }
  8124. }
  8125. ;// CONCATENATED MODULE: ./web/annotation_editor_layer_builder.js
  8126. class AnnotationEditorLayerBuilder {
  8127. #annotationLayer = null;
  8128. #drawLayer = null;
  8129. #onAppend = null;
  8130. #textLayer = null;
  8131. #uiManager;
  8132. constructor(options) {
  8133. this.pdfPage = options.pdfPage;
  8134. this.accessibilityManager = options.accessibilityManager;
  8135. this.l10n = options.l10n;
  8136. this.l10n ||= new genericl10n_GenericL10n();
  8137. this.annotationEditorLayer = null;
  8138. this.div = null;
  8139. this._cancelled = false;
  8140. this.#uiManager = options.uiManager;
  8141. this.#annotationLayer = options.annotationLayer || null;
  8142. this.#textLayer = options.textLayer || null;
  8143. this.#drawLayer = options.drawLayer || null;
  8144. this.#onAppend = options.onAppend || null;
  8145. }
  8146. async render(viewport, intent = "display") {
  8147. if (intent !== "display") {
  8148. return;
  8149. }
  8150. if (this._cancelled) {
  8151. return;
  8152. }
  8153. const clonedViewport = viewport.clone({
  8154. dontFlip: true
  8155. });
  8156. if (this.div) {
  8157. this.annotationEditorLayer.update({
  8158. viewport: clonedViewport
  8159. });
  8160. this.show();
  8161. return;
  8162. }
  8163. const div = this.div = document.createElement("div");
  8164. div.className = "annotationEditorLayer";
  8165. div.hidden = true;
  8166. div.dir = this.#uiManager.direction;
  8167. this.#onAppend?.(div);
  8168. this.annotationEditorLayer = new AnnotationEditorLayer({
  8169. uiManager: this.#uiManager,
  8170. div,
  8171. accessibilityManager: this.accessibilityManager,
  8172. pageIndex: this.pdfPage.pageNumber - 1,
  8173. l10n: this.l10n,
  8174. viewport: clonedViewport,
  8175. annotationLayer: this.#annotationLayer,
  8176. textLayer: this.#textLayer,
  8177. drawLayer: this.#drawLayer
  8178. });
  8179. const parameters = {
  8180. viewport: clonedViewport,
  8181. div,
  8182. annotations: null,
  8183. intent
  8184. };
  8185. this.annotationEditorLayer.render(parameters);
  8186. this.show();
  8187. }
  8188. cancel() {
  8189. this._cancelled = true;
  8190. if (!this.div) {
  8191. return;
  8192. }
  8193. this.annotationEditorLayer.destroy();
  8194. }
  8195. hide() {
  8196. if (!this.div) {
  8197. return;
  8198. }
  8199. this.div.hidden = true;
  8200. }
  8201. show() {
  8202. if (!this.div || this.annotationEditorLayer.isInvisible) {
  8203. return;
  8204. }
  8205. this.div.hidden = false;
  8206. }
  8207. }
  8208. ;// CONCATENATED MODULE: ./web/annotation_layer_builder.js
  8209. class AnnotationLayerBuilder {
  8210. #onAppend = null;
  8211. #eventAbortController = null;
  8212. constructor({
  8213. pdfPage,
  8214. linkService,
  8215. downloadManager,
  8216. annotationStorage = null,
  8217. imageResourcesPath = "",
  8218. renderForms = true,
  8219. enableScripting = false,
  8220. hasJSActionsPromise = null,
  8221. fieldObjectsPromise = null,
  8222. annotationCanvasMap = null,
  8223. accessibilityManager = null,
  8224. annotationEditorUIManager = null,
  8225. onAppend = null
  8226. }) {
  8227. this.pdfPage = pdfPage;
  8228. this.linkService = linkService;
  8229. this.downloadManager = downloadManager;
  8230. this.imageResourcesPath = imageResourcesPath;
  8231. this.renderForms = renderForms;
  8232. this.annotationStorage = annotationStorage;
  8233. this.enableScripting = enableScripting;
  8234. this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false);
  8235. this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null);
  8236. this._annotationCanvasMap = annotationCanvasMap;
  8237. this._accessibilityManager = accessibilityManager;
  8238. this._annotationEditorUIManager = annotationEditorUIManager;
  8239. this.#onAppend = onAppend;
  8240. this.annotationLayer = null;
  8241. this.div = null;
  8242. this._cancelled = false;
  8243. this._eventBus = linkService.eventBus;
  8244. }
  8245. async render(viewport, intent = "display") {
  8246. if (this.div) {
  8247. if (this._cancelled || !this.annotationLayer) {
  8248. return;
  8249. }
  8250. this.annotationLayer.update({
  8251. viewport: viewport.clone({
  8252. dontFlip: true
  8253. })
  8254. });
  8255. return;
  8256. }
  8257. const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({
  8258. intent
  8259. }), this._hasJSActionsPromise, this._fieldObjectsPromise]);
  8260. if (this._cancelled) {
  8261. return;
  8262. }
  8263. const div = this.div = document.createElement("div");
  8264. div.className = "annotationLayer";
  8265. this.#onAppend?.(div);
  8266. if (annotations.length === 0) {
  8267. this.hide();
  8268. return;
  8269. }
  8270. this.annotationLayer = new AnnotationLayer({
  8271. div,
  8272. accessibilityManager: this._accessibilityManager,
  8273. annotationCanvasMap: this._annotationCanvasMap,
  8274. annotationEditorUIManager: this._annotationEditorUIManager,
  8275. page: this.pdfPage,
  8276. viewport: viewport.clone({
  8277. dontFlip: true
  8278. })
  8279. });
  8280. await this.annotationLayer.render({
  8281. annotations,
  8282. imageResourcesPath: this.imageResourcesPath,
  8283. renderForms: this.renderForms,
  8284. linkService: this.linkService,
  8285. downloadManager: this.downloadManager,
  8286. annotationStorage: this.annotationStorage,
  8287. enableScripting: this.enableScripting,
  8288. hasJSActions,
  8289. fieldObjects
  8290. });
  8291. if (this.linkService.isInPresentationMode) {
  8292. this.#updatePresentationModeState(PresentationModeState.FULLSCREEN);
  8293. }
  8294. if (!this.#eventAbortController) {
  8295. this.#eventAbortController = new AbortController();
  8296. this._eventBus?._on("presentationmodechanged", evt => {
  8297. this.#updatePresentationModeState(evt.state);
  8298. }, {
  8299. signal: this.#eventAbortController.signal
  8300. });
  8301. }
  8302. }
  8303. cancel() {
  8304. this._cancelled = true;
  8305. this.#eventAbortController?.abort();
  8306. this.#eventAbortController = null;
  8307. }
  8308. hide() {
  8309. if (!this.div) {
  8310. return;
  8311. }
  8312. this.div.hidden = true;
  8313. }
  8314. hasEditableAnnotations() {
  8315. return !!this.annotationLayer?.hasEditableAnnotations();
  8316. }
  8317. #updatePresentationModeState(state) {
  8318. if (!this.div) {
  8319. return;
  8320. }
  8321. let disableFormElements = false;
  8322. switch (state) {
  8323. case PresentationModeState.FULLSCREEN:
  8324. disableFormElements = true;
  8325. break;
  8326. case PresentationModeState.NORMAL:
  8327. break;
  8328. default:
  8329. return;
  8330. }
  8331. for (const section of this.div.childNodes) {
  8332. if (section.hasAttribute("data-internal-link")) {
  8333. continue;
  8334. }
  8335. section.inert = disableFormElements;
  8336. }
  8337. }
  8338. }
  8339. ;// CONCATENATED MODULE: ./web/draw_layer_builder.js
  8340. class DrawLayerBuilder {
  8341. #drawLayer = null;
  8342. constructor(options) {
  8343. this.pageIndex = options.pageIndex;
  8344. }
  8345. async render(intent = "display") {
  8346. if (intent !== "display" || this.#drawLayer || this._cancelled) {
  8347. return;
  8348. }
  8349. this.#drawLayer = new DrawLayer({
  8350. pageIndex: this.pageIndex
  8351. });
  8352. }
  8353. cancel() {
  8354. this._cancelled = true;
  8355. if (!this.#drawLayer) {
  8356. return;
  8357. }
  8358. this.#drawLayer.destroy();
  8359. this.#drawLayer = null;
  8360. }
  8361. setParent(parent) {
  8362. this.#drawLayer?.setParent(parent);
  8363. }
  8364. getDrawLayer() {
  8365. return this.#drawLayer;
  8366. }
  8367. }
  8368. ;// CONCATENATED MODULE: ./web/struct_tree_layer_builder.js
  8369. const PDF_ROLE_TO_HTML_ROLE = {
  8370. Document: null,
  8371. DocumentFragment: null,
  8372. Part: "group",
  8373. Sect: "group",
  8374. Div: "group",
  8375. Aside: "note",
  8376. NonStruct: "none",
  8377. P: null,
  8378. H: "heading",
  8379. Title: null,
  8380. FENote: "note",
  8381. Sub: "group",
  8382. Lbl: null,
  8383. Span: null,
  8384. Em: null,
  8385. Strong: null,
  8386. Link: "link",
  8387. Annot: "note",
  8388. Form: "form",
  8389. Ruby: null,
  8390. RB: null,
  8391. RT: null,
  8392. RP: null,
  8393. Warichu: null,
  8394. WT: null,
  8395. WP: null,
  8396. L: "list",
  8397. LI: "listitem",
  8398. LBody: null,
  8399. Table: "table",
  8400. TR: "row",
  8401. TH: "columnheader",
  8402. TD: "cell",
  8403. THead: "columnheader",
  8404. TBody: null,
  8405. TFoot: null,
  8406. Caption: null,
  8407. Figure: "figure",
  8408. Formula: null,
  8409. Artifact: null
  8410. };
  8411. const HEADING_PATTERN = /^H(\d+)$/;
  8412. class StructTreeLayerBuilder {
  8413. #treeDom = undefined;
  8414. get renderingDone() {
  8415. return this.#treeDom !== undefined;
  8416. }
  8417. render(structTree) {
  8418. if (this.#treeDom !== undefined) {
  8419. return this.#treeDom;
  8420. }
  8421. const treeDom = this.#walk(structTree);
  8422. treeDom?.classList.add("structTree");
  8423. return this.#treeDom = treeDom;
  8424. }
  8425. hide() {
  8426. if (this.#treeDom && !this.#treeDom.hidden) {
  8427. this.#treeDom.hidden = true;
  8428. }
  8429. }
  8430. show() {
  8431. if (this.#treeDom?.hidden) {
  8432. this.#treeDom.hidden = false;
  8433. }
  8434. }
  8435. #setAttributes(structElement, htmlElement) {
  8436. const {
  8437. alt,
  8438. id,
  8439. lang
  8440. } = structElement;
  8441. if (alt !== undefined) {
  8442. htmlElement.setAttribute("aria-label", removeNullCharacters(alt));
  8443. }
  8444. if (id !== undefined) {
  8445. htmlElement.setAttribute("aria-owns", id);
  8446. }
  8447. if (lang !== undefined) {
  8448. htmlElement.setAttribute("lang", removeNullCharacters(lang, true));
  8449. }
  8450. }
  8451. #walk(node) {
  8452. if (!node) {
  8453. return null;
  8454. }
  8455. const element = document.createElement("span");
  8456. if ("role" in node) {
  8457. const {
  8458. role
  8459. } = node;
  8460. const match = role.match(HEADING_PATTERN);
  8461. if (match) {
  8462. element.setAttribute("role", "heading");
  8463. element.setAttribute("aria-level", match[1]);
  8464. } else if (PDF_ROLE_TO_HTML_ROLE[role]) {
  8465. element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]);
  8466. }
  8467. }
  8468. this.#setAttributes(node, element);
  8469. if (node.children) {
  8470. if (node.children.length === 1 && "id" in node.children[0]) {
  8471. this.#setAttributes(node.children[0], element);
  8472. } else {
  8473. for (const kid of node.children) {
  8474. element.append(this.#walk(kid));
  8475. }
  8476. }
  8477. }
  8478. return element;
  8479. }
  8480. }
  8481. ;// CONCATENATED MODULE: ./web/text_accessibility.js
  8482. class TextAccessibilityManager {
  8483. #enabled = false;
  8484. #textChildren = null;
  8485. #textNodes = new Map();
  8486. #waitingElements = new Map();
  8487. setTextMapping(textDivs) {
  8488. this.#textChildren = textDivs;
  8489. }
  8490. static #compareElementPositions(e1, e2) {
  8491. const rect1 = e1.getBoundingClientRect();
  8492. const rect2 = e2.getBoundingClientRect();
  8493. if (rect1.width === 0 && rect1.height === 0) {
  8494. return +1;
  8495. }
  8496. if (rect2.width === 0 && rect2.height === 0) {
  8497. return -1;
  8498. }
  8499. const top1 = rect1.y;
  8500. const bot1 = rect1.y + rect1.height;
  8501. const mid1 = rect1.y + rect1.height / 2;
  8502. const top2 = rect2.y;
  8503. const bot2 = rect2.y + rect2.height;
  8504. const mid2 = rect2.y + rect2.height / 2;
  8505. if (mid1 <= top2 && mid2 >= bot1) {
  8506. return -1;
  8507. }
  8508. if (mid2 <= top1 && mid1 >= bot2) {
  8509. return +1;
  8510. }
  8511. const centerX1 = rect1.x + rect1.width / 2;
  8512. const centerX2 = rect2.x + rect2.width / 2;
  8513. return centerX1 - centerX2;
  8514. }
  8515. enable() {
  8516. if (this.#enabled) {
  8517. throw new Error("TextAccessibilityManager is already enabled.");
  8518. }
  8519. if (!this.#textChildren) {
  8520. throw new Error("Text divs and strings have not been set.");
  8521. }
  8522. this.#enabled = true;
  8523. this.#textChildren = this.#textChildren.slice();
  8524. this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions);
  8525. if (this.#textNodes.size > 0) {
  8526. const textChildren = this.#textChildren;
  8527. for (const [id, nodeIndex] of this.#textNodes) {
  8528. const element = document.getElementById(id);
  8529. if (!element) {
  8530. this.#textNodes.delete(id);
  8531. continue;
  8532. }
  8533. this.#addIdToAriaOwns(id, textChildren[nodeIndex]);
  8534. }
  8535. }
  8536. for (const [element, isRemovable] of this.#waitingElements) {
  8537. this.addPointerInTextLayer(element, isRemovable);
  8538. }
  8539. this.#waitingElements.clear();
  8540. }
  8541. disable() {
  8542. if (!this.#enabled) {
  8543. return;
  8544. }
  8545. this.#waitingElements.clear();
  8546. this.#textChildren = null;
  8547. this.#enabled = false;
  8548. }
  8549. removePointerInTextLayer(element) {
  8550. if (!this.#enabled) {
  8551. this.#waitingElements.delete(element);
  8552. return;
  8553. }
  8554. const children = this.#textChildren;
  8555. if (!children || children.length === 0) {
  8556. return;
  8557. }
  8558. const {
  8559. id
  8560. } = element;
  8561. const nodeIndex = this.#textNodes.get(id);
  8562. if (nodeIndex === undefined) {
  8563. return;
  8564. }
  8565. const node = children[nodeIndex];
  8566. this.#textNodes.delete(id);
  8567. let owns = node.getAttribute("aria-owns");
  8568. if (owns?.includes(id)) {
  8569. owns = owns.split(" ").filter(x => x !== id).join(" ");
  8570. if (owns) {
  8571. node.setAttribute("aria-owns", owns);
  8572. } else {
  8573. node.removeAttribute("aria-owns");
  8574. node.setAttribute("role", "presentation");
  8575. }
  8576. }
  8577. }
  8578. #addIdToAriaOwns(id, node) {
  8579. const owns = node.getAttribute("aria-owns");
  8580. if (!owns?.includes(id)) {
  8581. node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id);
  8582. }
  8583. node.removeAttribute("role");
  8584. }
  8585. addPointerInTextLayer(element, isRemovable) {
  8586. const {
  8587. id
  8588. } = element;
  8589. if (!id) {
  8590. return null;
  8591. }
  8592. if (!this.#enabled) {
  8593. this.#waitingElements.set(element, isRemovable);
  8594. return null;
  8595. }
  8596. if (isRemovable) {
  8597. this.removePointerInTextLayer(element);
  8598. }
  8599. const children = this.#textChildren;
  8600. if (!children || children.length === 0) {
  8601. return null;
  8602. }
  8603. const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0);
  8604. const nodeIndex = Math.max(0, index - 1);
  8605. const child = children[nodeIndex];
  8606. this.#addIdToAriaOwns(id, child);
  8607. this.#textNodes.set(id, nodeIndex);
  8608. const parent = child.parentNode;
  8609. return parent?.classList.contains("markedContent") ? parent.id : null;
  8610. }
  8611. moveElementInDOM(container, element, contentElement, isRemovable) {
  8612. const id = this.addPointerInTextLayer(contentElement, isRemovable);
  8613. if (!container.hasChildNodes()) {
  8614. container.append(element);
  8615. return id;
  8616. }
  8617. const children = Array.from(container.childNodes).filter(node => node !== element);
  8618. if (children.length === 0) {
  8619. return id;
  8620. }
  8621. const elementToCompare = contentElement || element;
  8622. const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0);
  8623. if (index === 0) {
  8624. children[0].before(element);
  8625. } else {
  8626. children[index - 1].after(element);
  8627. }
  8628. return id;
  8629. }
  8630. }
  8631. ;// CONCATENATED MODULE: ./web/text_highlighter.js
  8632. class TextHighlighter {
  8633. #eventAbortController = null;
  8634. constructor({
  8635. findController,
  8636. eventBus,
  8637. pageIndex
  8638. }) {
  8639. this.findController = findController;
  8640. this.matches = [];
  8641. this.eventBus = eventBus;
  8642. this.pageIdx = pageIndex;
  8643. this.textDivs = null;
  8644. this.textContentItemsStr = null;
  8645. this.enabled = false;
  8646. }
  8647. setTextMapping(divs, texts) {
  8648. this.textDivs = divs;
  8649. this.textContentItemsStr = texts;
  8650. }
  8651. enable() {
  8652. if (!this.textDivs || !this.textContentItemsStr) {
  8653. throw new Error("Text divs and strings have not been set.");
  8654. }
  8655. if (this.enabled) {
  8656. throw new Error("TextHighlighter is already enabled.");
  8657. }
  8658. this.enabled = true;
  8659. if (!this.#eventAbortController) {
  8660. this.#eventAbortController = new AbortController();
  8661. this.eventBus._on("updatetextlayermatches", evt => {
  8662. if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) {
  8663. this._updateMatches();
  8664. }
  8665. }, {
  8666. signal: this.#eventAbortController.signal
  8667. });
  8668. }
  8669. this._updateMatches();
  8670. }
  8671. disable() {
  8672. if (!this.enabled) {
  8673. return;
  8674. }
  8675. this.enabled = false;
  8676. this.#eventAbortController?.abort();
  8677. this.#eventAbortController = null;
  8678. this._updateMatches(true);
  8679. }
  8680. _convertMatches(matches, matchesLength) {
  8681. if (!matches) {
  8682. return [];
  8683. }
  8684. const {
  8685. textContentItemsStr
  8686. } = this;
  8687. let i = 0,
  8688. iIndex = 0;
  8689. const end = textContentItemsStr.length - 1;
  8690. const result = [];
  8691. for (let m = 0, mm = matches.length; m < mm; m++) {
  8692. let matchIdx = matches[m];
  8693. while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) {
  8694. iIndex += textContentItemsStr[i].length;
  8695. i++;
  8696. }
  8697. if (i === textContentItemsStr.length) {
  8698. console.error("Could not find a matching mapping");
  8699. }
  8700. const match = {
  8701. begin: {
  8702. divIdx: i,
  8703. offset: matchIdx - iIndex
  8704. }
  8705. };
  8706. matchIdx += matchesLength[m];
  8707. while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) {
  8708. iIndex += textContentItemsStr[i].length;
  8709. i++;
  8710. }
  8711. match.end = {
  8712. divIdx: i,
  8713. offset: matchIdx - iIndex
  8714. };
  8715. result.push(match);
  8716. }
  8717. return result;
  8718. }
  8719. _renderMatches(matches) {
  8720. if (matches.length === 0) {
  8721. return;
  8722. }
  8723. const {
  8724. findController,
  8725. pageIdx
  8726. } = this;
  8727. const {
  8728. textContentItemsStr,
  8729. textDivs
  8730. } = this;
  8731. const isSelectedPage = pageIdx === findController.selected.pageIdx;
  8732. const selectedMatchIdx = findController.selected.matchIdx;
  8733. const highlightAll = findController.state.highlightAll;
  8734. let prevEnd = null;
  8735. const infinity = {
  8736. divIdx: -1,
  8737. offset: undefined
  8738. };
  8739. function beginText(begin, className) {
  8740. const divIdx = begin.divIdx;
  8741. textDivs[divIdx].textContent = "";
  8742. return appendTextToDiv(divIdx, 0, begin.offset, className);
  8743. }
  8744. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  8745. let div = textDivs[divIdx];
  8746. if (div.nodeType === Node.TEXT_NODE) {
  8747. const span = document.createElement("span");
  8748. div.before(span);
  8749. span.append(div);
  8750. textDivs[divIdx] = span;
  8751. div = span;
  8752. }
  8753. const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
  8754. const node = document.createTextNode(content);
  8755. if (className) {
  8756. const span = document.createElement("span");
  8757. span.className = `${className} appended`;
  8758. span.append(node);
  8759. div.append(span);
  8760. return className.includes("selected") ? span.offsetLeft : 0;
  8761. }
  8762. div.append(node);
  8763. return 0;
  8764. }
  8765. let i0 = selectedMatchIdx,
  8766. i1 = i0 + 1;
  8767. if (highlightAll) {
  8768. i0 = 0;
  8769. i1 = matches.length;
  8770. } else if (!isSelectedPage) {
  8771. return;
  8772. }
  8773. let lastDivIdx = -1;
  8774. let lastOffset = -1;
  8775. for (let i = i0; i < i1; i++) {
  8776. const match = matches[i];
  8777. const begin = match.begin;
  8778. if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) {
  8779. continue;
  8780. }
  8781. lastDivIdx = begin.divIdx;
  8782. lastOffset = begin.offset;
  8783. const end = match.end;
  8784. const isSelected = isSelectedPage && i === selectedMatchIdx;
  8785. const highlightSuffix = isSelected ? " selected" : "";
  8786. let selectedLeft = 0;
  8787. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  8788. if (prevEnd !== null) {
  8789. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  8790. }
  8791. beginText(begin);
  8792. } else {
  8793. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  8794. }
  8795. if (begin.divIdx === end.divIdx) {
  8796. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix);
  8797. } else {
  8798. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix);
  8799. for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  8800. textDivs[n0].className = "highlight middle" + highlightSuffix;
  8801. }
  8802. beginText(end, "highlight end" + highlightSuffix);
  8803. }
  8804. prevEnd = end;
  8805. if (isSelected) {
  8806. findController.scrollMatchIntoView({
  8807. element: textDivs[begin.divIdx],
  8808. selectedLeft,
  8809. pageIndex: pageIdx,
  8810. matchIndex: selectedMatchIdx
  8811. });
  8812. }
  8813. }
  8814. if (prevEnd) {
  8815. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  8816. }
  8817. }
  8818. _updateMatches(reset = false) {
  8819. if (!this.enabled && !reset) {
  8820. return;
  8821. }
  8822. const {
  8823. findController,
  8824. matches,
  8825. pageIdx
  8826. } = this;
  8827. const {
  8828. textContentItemsStr,
  8829. textDivs
  8830. } = this;
  8831. let clearedUntilDivIdx = -1;
  8832. for (const match of matches) {
  8833. const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  8834. for (let n = begin, end = match.end.divIdx; n <= end; n++) {
  8835. const div = textDivs[n];
  8836. div.textContent = textContentItemsStr[n];
  8837. div.className = "";
  8838. }
  8839. clearedUntilDivIdx = match.end.divIdx + 1;
  8840. }
  8841. if (!findController?.highlightMatches || reset) {
  8842. return;
  8843. }
  8844. const pageMatches = findController.pageMatches[pageIdx] || null;
  8845. const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null;
  8846. this.matches = this._convertMatches(pageMatches, pageMatchesLength);
  8847. this._renderMatches(this.matches);
  8848. }
  8849. }
  8850. ;// CONCATENATED MODULE: ./web/text_layer_builder.js
  8851. class TextLayerBuilder {
  8852. #enablePermissions = false;
  8853. #onAppend = null;
  8854. #renderingDone = false;
  8855. #textLayer = null;
  8856. static #textLayers = new Map();
  8857. static #selectionChangeAbortController = null;
  8858. constructor({
  8859. pdfPage,
  8860. highlighter = null,
  8861. accessibilityManager = null,
  8862. enablePermissions = false,
  8863. onAppend = null
  8864. }) {
  8865. this.pdfPage = pdfPage;
  8866. this.highlighter = highlighter;
  8867. this.accessibilityManager = accessibilityManager;
  8868. this.#enablePermissions = enablePermissions === true;
  8869. this.#onAppend = onAppend;
  8870. this.div = document.createElement("div");
  8871. this.div.tabIndex = 0;
  8872. this.div.className = "textLayer";
  8873. }
  8874. async render(viewport, textContentParams = null) {
  8875. if (this.#renderingDone && this.#textLayer) {
  8876. this.#textLayer.update({
  8877. viewport,
  8878. onBefore: this.hide.bind(this)
  8879. });
  8880. this.show();
  8881. return;
  8882. }
  8883. this.cancel();
  8884. this.#textLayer = new TextLayer({
  8885. textContentSource: this.pdfPage.streamTextContent(textContentParams || {
  8886. includeMarkedContent: true,
  8887. disableNormalization: true
  8888. }),
  8889. container: this.div,
  8890. viewport
  8891. });
  8892. const {
  8893. textDivs,
  8894. textContentItemsStr
  8895. } = this.#textLayer;
  8896. this.highlighter?.setTextMapping(textDivs, textContentItemsStr);
  8897. this.accessibilityManager?.setTextMapping(textDivs);
  8898. await this.#textLayer.render();
  8899. this.#renderingDone = true;
  8900. const endOfContent = document.createElement("div");
  8901. endOfContent.className = "endOfContent";
  8902. this.div.append(endOfContent);
  8903. this.#bindMouse(endOfContent);
  8904. this.#onAppend?.(this.div);
  8905. this.highlighter?.enable();
  8906. this.accessibilityManager?.enable();
  8907. }
  8908. hide() {
  8909. if (!this.div.hidden && this.#renderingDone) {
  8910. this.highlighter?.disable();
  8911. this.div.hidden = true;
  8912. }
  8913. }
  8914. show() {
  8915. if (this.div.hidden && this.#renderingDone) {
  8916. this.div.hidden = false;
  8917. this.highlighter?.enable();
  8918. }
  8919. }
  8920. cancel() {
  8921. this.#textLayer?.cancel();
  8922. this.#textLayer = null;
  8923. this.highlighter?.disable();
  8924. this.accessibilityManager?.disable();
  8925. TextLayerBuilder.#removeGlobalSelectionListener(this.div);
  8926. }
  8927. #bindMouse(end) {
  8928. const {
  8929. div
  8930. } = this;
  8931. div.addEventListener("mousedown", evt => {
  8932. end.classList.add("active");
  8933. });
  8934. div.addEventListener("copy", event => {
  8935. if (!this.#enablePermissions) {
  8936. const selection = document.getSelection();
  8937. event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString())));
  8938. }
  8939. event.preventDefault();
  8940. event.stopPropagation();
  8941. });
  8942. TextLayerBuilder.#textLayers.set(div, end);
  8943. TextLayerBuilder.#enableGlobalSelectionListener();
  8944. }
  8945. static #removeGlobalSelectionListener(textLayerDiv) {
  8946. this.#textLayers.delete(textLayerDiv);
  8947. if (this.#textLayers.size === 0) {
  8948. this.#selectionChangeAbortController?.abort();
  8949. this.#selectionChangeAbortController = null;
  8950. }
  8951. }
  8952. static #enableGlobalSelectionListener() {
  8953. if (this.#selectionChangeAbortController) {
  8954. return;
  8955. }
  8956. this.#selectionChangeAbortController = new AbortController();
  8957. const {
  8958. signal
  8959. } = this.#selectionChangeAbortController;
  8960. const reset = (end, textLayer) => {
  8961. textLayer.append(end);
  8962. end.style.width = "";
  8963. end.style.height = "";
  8964. end.classList.remove("active");
  8965. };
  8966. document.addEventListener("pointerup", () => {
  8967. this.#textLayers.forEach(reset);
  8968. }, {
  8969. signal
  8970. });
  8971. var isFirefox, prevRange;
  8972. document.addEventListener("selectionchange", () => {
  8973. const selection = document.getSelection();
  8974. if (selection.rangeCount === 0) {
  8975. this.#textLayers.forEach(reset);
  8976. return;
  8977. }
  8978. const activeTextLayers = new Set();
  8979. for (let i = 0; i < selection.rangeCount; i++) {
  8980. const range = selection.getRangeAt(i);
  8981. for (const textLayerDiv of this.#textLayers.keys()) {
  8982. if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) {
  8983. activeTextLayers.add(textLayerDiv);
  8984. }
  8985. }
  8986. }
  8987. for (const [textLayerDiv, endDiv] of this.#textLayers) {
  8988. if (activeTextLayers.has(textLayerDiv)) {
  8989. endDiv.classList.add("active");
  8990. } else {
  8991. reset(endDiv, textLayerDiv);
  8992. }
  8993. }
  8994. isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none";
  8995. if (isFirefox) {
  8996. return;
  8997. }
  8998. const range = selection.getRangeAt(0);
  8999. const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0);
  9000. let anchor = modifyStart ? range.startContainer : range.endContainer;
  9001. if (anchor.nodeType === Node.TEXT_NODE) {
  9002. anchor = anchor.parentNode;
  9003. }
  9004. const parentTextLayer = anchor.parentElement.closest(".textLayer");
  9005. const endDiv = this.#textLayers.get(parentTextLayer);
  9006. if (endDiv) {
  9007. endDiv.style.width = parentTextLayer.style.width;
  9008. endDiv.style.height = parentTextLayer.style.height;
  9009. anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling);
  9010. }
  9011. prevRange = range.cloneRange();
  9012. }, {
  9013. signal
  9014. });
  9015. }
  9016. }
  9017. ;// CONCATENATED MODULE: ./web/pdf_page_view.js
  9018. const DEFAULT_LAYER_PROPERTIES = null;
  9019. const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]);
  9020. class PDFPageView {
  9021. #annotationMode = AnnotationMode.ENABLE_FORMS;
  9022. #enableHWA = false;
  9023. #hasRestrictedScaling = false;
  9024. #isEditing = false;
  9025. #layerProperties = null;
  9026. #loadingId = null;
  9027. #previousRotation = null;
  9028. #renderError = null;
  9029. #renderingState = RenderingStates.INITIAL;
  9030. #textLayerMode = TextLayerMode.ENABLE;
  9031. #useThumbnailCanvas = {
  9032. directDrawing: true,
  9033. initialOptionalContent: true,
  9034. regularAnnotations: true
  9035. };
  9036. #viewportMap = new WeakMap();
  9037. #layers = [null, null, null, null];
  9038. constructor(options) {
  9039. const container = options.container;
  9040. const defaultViewport = options.defaultViewport;
  9041. this.id = options.id;
  9042. this.renderingId = "page" + this.id;
  9043. this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES;
  9044. this.pdfPage = null;
  9045. this.pageLabel = null;
  9046. this.rotation = 0;
  9047. this.scale = options.scale || DEFAULT_SCALE;
  9048. this.viewport = defaultViewport;
  9049. this.pdfPageRotate = defaultViewport.rotation;
  9050. this._optionalContentConfigPromise = options.optionalContentConfigPromise || null;
  9051. this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE;
  9052. this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS;
  9053. this.imageResourcesPath = options.imageResourcesPath || "";
  9054. this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels");
  9055. this.pageColors = options.pageColors || null;
  9056. this.#enableHWA = options.enableHWA || false;
  9057. this.eventBus = options.eventBus;
  9058. this.renderingQueue = options.renderingQueue;
  9059. this.l10n = options.l10n;
  9060. this.l10n ||= new genericl10n_GenericL10n();
  9061. this.renderTask = null;
  9062. this.resume = null;
  9063. this._isStandalone = !this.renderingQueue?.hasViewer();
  9064. this._container = container;
  9065. this._annotationCanvasMap = null;
  9066. this.annotationLayer = null;
  9067. this.annotationEditorLayer = null;
  9068. this.textLayer = null;
  9069. this.zoomLayer = null;
  9070. this.xfaLayer = null;
  9071. this.structTreeLayer = null;
  9072. this.drawLayer = null;
  9073. const div = document.createElement("div");
  9074. div.className = "page";
  9075. div.setAttribute("data-page-number", this.id);
  9076. div.setAttribute("role", "region");
  9077. div.setAttribute("data-l10n-id", "pdfjs-page-landmark");
  9078. div.setAttribute("data-l10n-args", JSON.stringify({
  9079. page: this.id
  9080. }));
  9081. this.div = div;
  9082. this.#setDimensions();
  9083. container?.append(div);
  9084. if (this._isStandalone) {
  9085. container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS);
  9086. const {
  9087. optionalContentConfigPromise
  9088. } = options;
  9089. if (optionalContentConfigPromise) {
  9090. optionalContentConfigPromise.then(optionalContentConfig => {
  9091. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  9092. return;
  9093. }
  9094. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  9095. });
  9096. }
  9097. if (!options.l10n) {
  9098. this.l10n.translate(this.div);
  9099. }
  9100. }
  9101. }
  9102. #addLayer(div, name) {
  9103. const pos = LAYERS_ORDER.get(name);
  9104. const oldDiv = this.#layers[pos];
  9105. this.#layers[pos] = div;
  9106. if (oldDiv) {
  9107. oldDiv.replaceWith(div);
  9108. return;
  9109. }
  9110. for (let i = pos - 1; i >= 0; i--) {
  9111. const layer = this.#layers[i];
  9112. if (layer) {
  9113. layer.after(div);
  9114. return;
  9115. }
  9116. }
  9117. this.div.prepend(div);
  9118. }
  9119. get renderingState() {
  9120. return this.#renderingState;
  9121. }
  9122. set renderingState(state) {
  9123. if (state === this.#renderingState) {
  9124. return;
  9125. }
  9126. this.#renderingState = state;
  9127. if (this.#loadingId) {
  9128. clearTimeout(this.#loadingId);
  9129. this.#loadingId = null;
  9130. }
  9131. switch (state) {
  9132. case RenderingStates.PAUSED:
  9133. this.div.classList.remove("loading");
  9134. break;
  9135. case RenderingStates.RUNNING:
  9136. this.div.classList.add("loadingIcon");
  9137. this.#loadingId = setTimeout(() => {
  9138. this.div.classList.add("loading");
  9139. this.#loadingId = null;
  9140. }, 0);
  9141. break;
  9142. case RenderingStates.INITIAL:
  9143. case RenderingStates.FINISHED:
  9144. this.div.classList.remove("loadingIcon", "loading");
  9145. break;
  9146. }
  9147. }
  9148. #setDimensions() {
  9149. const {
  9150. viewport
  9151. } = this;
  9152. if (this.pdfPage) {
  9153. if (this.#previousRotation === viewport.rotation) {
  9154. return;
  9155. }
  9156. this.#previousRotation = viewport.rotation;
  9157. }
  9158. setLayerDimensions(this.div, viewport, true, false);
  9159. }
  9160. setPdfPage(pdfPage) {
  9161. if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) {
  9162. this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight"));
  9163. this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight"));
  9164. }
  9165. this.pdfPage = pdfPage;
  9166. this.pdfPageRotate = pdfPage.rotate;
  9167. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  9168. this.viewport = pdfPage.getViewport({
  9169. scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS,
  9170. rotation: totalRotation
  9171. });
  9172. this.#setDimensions();
  9173. this.reset();
  9174. }
  9175. destroy() {
  9176. this.reset();
  9177. this.pdfPage?.cleanup();
  9178. }
  9179. hasEditableAnnotations() {
  9180. return !!this.annotationLayer?.hasEditableAnnotations();
  9181. }
  9182. get _textHighlighter() {
  9183. return shadow(this, "_textHighlighter", new TextHighlighter({
  9184. pageIndex: this.id - 1,
  9185. eventBus: this.eventBus,
  9186. findController: this.#layerProperties.findController
  9187. }));
  9188. }
  9189. #dispatchLayerRendered(name, error) {
  9190. this.eventBus.dispatch(name, {
  9191. source: this,
  9192. pageNumber: this.id,
  9193. error
  9194. });
  9195. }
  9196. async #renderAnnotationLayer() {
  9197. let error = null;
  9198. try {
  9199. await this.annotationLayer.render(this.viewport, "display");
  9200. } catch (ex) {
  9201. console.error(`#renderAnnotationLayer: "${ex}".`);
  9202. error = ex;
  9203. } finally {
  9204. this.#dispatchLayerRendered("annotationlayerrendered", error);
  9205. }
  9206. }
  9207. async #renderAnnotationEditorLayer() {
  9208. let error = null;
  9209. try {
  9210. await this.annotationEditorLayer.render(this.viewport, "display");
  9211. } catch (ex) {
  9212. console.error(`#renderAnnotationEditorLayer: "${ex}".`);
  9213. error = ex;
  9214. } finally {
  9215. this.#dispatchLayerRendered("annotationeditorlayerrendered", error);
  9216. }
  9217. }
  9218. async #renderDrawLayer() {
  9219. try {
  9220. await this.drawLayer.render("display");
  9221. } catch (ex) {
  9222. console.error(`#renderDrawLayer: "${ex}".`);
  9223. }
  9224. }
  9225. async #renderXfaLayer() {
  9226. let error = null;
  9227. try {
  9228. const result = await this.xfaLayer.render(this.viewport, "display");
  9229. if (result?.textDivs && this._textHighlighter) {
  9230. this.#buildXfaTextContentItems(result.textDivs);
  9231. }
  9232. } catch (ex) {
  9233. console.error(`#renderXfaLayer: "${ex}".`);
  9234. error = ex;
  9235. } finally {
  9236. if (this.xfaLayer?.div) {
  9237. this.l10n.pause();
  9238. this.#addLayer(this.xfaLayer.div, "xfaLayer");
  9239. this.l10n.resume();
  9240. }
  9241. this.#dispatchLayerRendered("xfalayerrendered", error);
  9242. }
  9243. }
  9244. async #renderTextLayer() {
  9245. if (!this.textLayer) {
  9246. return;
  9247. }
  9248. let error = null;
  9249. try {
  9250. await this.textLayer.render(this.viewport);
  9251. } catch (ex) {
  9252. if (ex instanceof AbortException) {
  9253. return;
  9254. }
  9255. console.error(`#renderTextLayer: "${ex}".`);
  9256. error = ex;
  9257. }
  9258. this.#dispatchLayerRendered("textlayerrendered", error);
  9259. this.#renderStructTreeLayer();
  9260. }
  9261. async #renderStructTreeLayer() {
  9262. if (!this.textLayer) {
  9263. return;
  9264. }
  9265. this.structTreeLayer ||= new StructTreeLayerBuilder();
  9266. const tree = await (!this.structTreeLayer.renderingDone ? this.pdfPage.getStructTree() : null);
  9267. const treeDom = this.structTreeLayer?.render(tree);
  9268. if (treeDom) {
  9269. this.l10n.pause();
  9270. this.canvas?.append(treeDom);
  9271. this.l10n.resume();
  9272. }
  9273. this.structTreeLayer?.show();
  9274. }
  9275. async #buildXfaTextContentItems(textDivs) {
  9276. const text = await this.pdfPage.getTextContent();
  9277. const items = [];
  9278. for (const item of text.items) {
  9279. items.push(item.str);
  9280. }
  9281. this._textHighlighter.setTextMapping(textDivs, items);
  9282. this._textHighlighter.enable();
  9283. }
  9284. _resetZoomLayer(removeFromDOM = false) {
  9285. if (!this.zoomLayer) {
  9286. return;
  9287. }
  9288. const zoomLayerCanvas = this.zoomLayer.firstChild;
  9289. this.#viewportMap.delete(zoomLayerCanvas);
  9290. zoomLayerCanvas.width = 0;
  9291. zoomLayerCanvas.height = 0;
  9292. if (removeFromDOM) {
  9293. this.zoomLayer.remove();
  9294. }
  9295. this.zoomLayer = null;
  9296. }
  9297. reset({
  9298. keepZoomLayer = false,
  9299. keepAnnotationLayer = false,
  9300. keepAnnotationEditorLayer = false,
  9301. keepXfaLayer = false,
  9302. keepTextLayer = false
  9303. } = {}) {
  9304. this.cancelRendering({
  9305. keepAnnotationLayer,
  9306. keepAnnotationEditorLayer,
  9307. keepXfaLayer,
  9308. keepTextLayer
  9309. });
  9310. this.renderingState = RenderingStates.INITIAL;
  9311. const div = this.div;
  9312. const childNodes = div.childNodes,
  9313. zoomLayerNode = keepZoomLayer && this.zoomLayer || null,
  9314. annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null,
  9315. annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null,
  9316. xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null,
  9317. textLayerNode = keepTextLayer && this.textLayer?.div || null;
  9318. for (let i = childNodes.length - 1; i >= 0; i--) {
  9319. const node = childNodes[i];
  9320. switch (node) {
  9321. case zoomLayerNode:
  9322. case annotationLayerNode:
  9323. case annotationEditorLayerNode:
  9324. case xfaLayerNode:
  9325. case textLayerNode:
  9326. continue;
  9327. }
  9328. node.remove();
  9329. const layerIndex = this.#layers.indexOf(node);
  9330. if (layerIndex >= 0) {
  9331. this.#layers[layerIndex] = null;
  9332. }
  9333. }
  9334. div.removeAttribute("data-loaded");
  9335. if (annotationLayerNode) {
  9336. this.annotationLayer.hide();
  9337. }
  9338. if (annotationEditorLayerNode) {
  9339. this.annotationEditorLayer.hide();
  9340. }
  9341. if (xfaLayerNode) {
  9342. this.xfaLayer.hide();
  9343. }
  9344. if (textLayerNode) {
  9345. this.textLayer.hide();
  9346. }
  9347. this.structTreeLayer?.hide();
  9348. if (!zoomLayerNode) {
  9349. if (this.canvas) {
  9350. this.#viewportMap.delete(this.canvas);
  9351. this.canvas.width = 0;
  9352. this.canvas.height = 0;
  9353. delete this.canvas;
  9354. }
  9355. this._resetZoomLayer();
  9356. }
  9357. }
  9358. toggleEditingMode(isEditing) {
  9359. if (!this.hasEditableAnnotations()) {
  9360. return;
  9361. }
  9362. this.#isEditing = isEditing;
  9363. this.reset({
  9364. keepZoomLayer: true,
  9365. keepAnnotationLayer: true,
  9366. keepAnnotationEditorLayer: true,
  9367. keepXfaLayer: true,
  9368. keepTextLayer: true
  9369. });
  9370. }
  9371. update({
  9372. scale = 0,
  9373. rotation = null,
  9374. optionalContentConfigPromise = null,
  9375. drawingDelay = -1
  9376. }) {
  9377. this.scale = scale || this.scale;
  9378. if (typeof rotation === "number") {
  9379. this.rotation = rotation;
  9380. }
  9381. if (optionalContentConfigPromise instanceof Promise) {
  9382. this._optionalContentConfigPromise = optionalContentConfigPromise;
  9383. optionalContentConfigPromise.then(optionalContentConfig => {
  9384. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  9385. return;
  9386. }
  9387. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  9388. });
  9389. }
  9390. this.#useThumbnailCanvas.directDrawing = true;
  9391. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  9392. this.viewport = this.viewport.clone({
  9393. scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS,
  9394. rotation: totalRotation
  9395. });
  9396. this.#setDimensions();
  9397. if (this._isStandalone) {
  9398. this._container?.style.setProperty("--scale-factor", this.viewport.scale);
  9399. }
  9400. if (this.canvas) {
  9401. let onlyCssZoom = false;
  9402. if (this.#hasRestrictedScaling) {
  9403. if (this.maxCanvasPixels === 0) {
  9404. onlyCssZoom = true;
  9405. } else if (this.maxCanvasPixels > 0) {
  9406. const {
  9407. width,
  9408. height
  9409. } = this.viewport;
  9410. const {
  9411. sx,
  9412. sy
  9413. } = this.outputScale;
  9414. onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels;
  9415. }
  9416. }
  9417. const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000;
  9418. if (postponeDrawing || onlyCssZoom) {
  9419. if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) {
  9420. this.cancelRendering({
  9421. keepZoomLayer: true,
  9422. keepAnnotationLayer: true,
  9423. keepAnnotationEditorLayer: true,
  9424. keepXfaLayer: true,
  9425. keepTextLayer: true,
  9426. cancelExtraDelay: drawingDelay
  9427. });
  9428. this.renderingState = RenderingStates.FINISHED;
  9429. this.#useThumbnailCanvas.directDrawing = false;
  9430. }
  9431. this.cssTransform({
  9432. target: this.canvas,
  9433. redrawAnnotationLayer: true,
  9434. redrawAnnotationEditorLayer: true,
  9435. redrawXfaLayer: true,
  9436. redrawTextLayer: !postponeDrawing,
  9437. hideTextLayer: postponeDrawing
  9438. });
  9439. if (postponeDrawing) {
  9440. return;
  9441. }
  9442. this.eventBus.dispatch("pagerendered", {
  9443. source: this,
  9444. pageNumber: this.id,
  9445. cssTransform: true,
  9446. timestamp: performance.now(),
  9447. error: this.#renderError
  9448. });
  9449. return;
  9450. }
  9451. if (!this.zoomLayer && !this.canvas.hidden) {
  9452. this.zoomLayer = this.canvas.parentNode;
  9453. this.zoomLayer.style.position = "absolute";
  9454. }
  9455. }
  9456. if (this.zoomLayer) {
  9457. this.cssTransform({
  9458. target: this.zoomLayer.firstChild
  9459. });
  9460. }
  9461. this.reset({
  9462. keepZoomLayer: true,
  9463. keepAnnotationLayer: true,
  9464. keepAnnotationEditorLayer: true,
  9465. keepXfaLayer: true,
  9466. keepTextLayer: true
  9467. });
  9468. }
  9469. cancelRendering({
  9470. keepAnnotationLayer = false,
  9471. keepAnnotationEditorLayer = false,
  9472. keepXfaLayer = false,
  9473. keepTextLayer = false,
  9474. cancelExtraDelay = 0
  9475. } = {}) {
  9476. if (this.renderTask) {
  9477. this.renderTask.cancel(cancelExtraDelay);
  9478. this.renderTask = null;
  9479. }
  9480. this.resume = null;
  9481. if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) {
  9482. this.textLayer.cancel();
  9483. this.textLayer = null;
  9484. }
  9485. if (this.structTreeLayer && !this.textLayer) {
  9486. this.structTreeLayer = null;
  9487. }
  9488. if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) {
  9489. this.annotationLayer.cancel();
  9490. this.annotationLayer = null;
  9491. this._annotationCanvasMap = null;
  9492. }
  9493. if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) {
  9494. if (this.drawLayer) {
  9495. this.drawLayer.cancel();
  9496. this.drawLayer = null;
  9497. }
  9498. this.annotationEditorLayer.cancel();
  9499. this.annotationEditorLayer = null;
  9500. }
  9501. if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) {
  9502. this.xfaLayer.cancel();
  9503. this.xfaLayer = null;
  9504. this._textHighlighter?.disable();
  9505. }
  9506. }
  9507. cssTransform({
  9508. target,
  9509. redrawAnnotationLayer = false,
  9510. redrawAnnotationEditorLayer = false,
  9511. redrawXfaLayer = false,
  9512. redrawTextLayer = false,
  9513. hideTextLayer = false
  9514. }) {
  9515. if (!target.hasAttribute("zooming")) {
  9516. target.setAttribute("zooming", true);
  9517. const {
  9518. style
  9519. } = target;
  9520. style.width = style.height = "";
  9521. }
  9522. const originalViewport = this.#viewportMap.get(target);
  9523. if (this.viewport !== originalViewport) {
  9524. const relativeRotation = this.viewport.rotation - originalViewport.rotation;
  9525. const absRotation = Math.abs(relativeRotation);
  9526. let scaleX = 1,
  9527. scaleY = 1;
  9528. if (absRotation === 90 || absRotation === 270) {
  9529. const {
  9530. width,
  9531. height
  9532. } = this.viewport;
  9533. scaleX = height / width;
  9534. scaleY = width / height;
  9535. }
  9536. target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`;
  9537. }
  9538. if (redrawAnnotationLayer && this.annotationLayer) {
  9539. this.#renderAnnotationLayer();
  9540. }
  9541. if (redrawAnnotationEditorLayer && this.annotationEditorLayer) {
  9542. if (this.drawLayer) {
  9543. this.#renderDrawLayer();
  9544. }
  9545. this.#renderAnnotationEditorLayer();
  9546. }
  9547. if (redrawXfaLayer && this.xfaLayer) {
  9548. this.#renderXfaLayer();
  9549. }
  9550. if (this.textLayer) {
  9551. if (hideTextLayer) {
  9552. this.textLayer.hide();
  9553. this.structTreeLayer?.hide();
  9554. } else if (redrawTextLayer) {
  9555. this.#renderTextLayer();
  9556. }
  9557. }
  9558. }
  9559. get width() {
  9560. return this.viewport.width;
  9561. }
  9562. get height() {
  9563. return this.viewport.height;
  9564. }
  9565. getPagePoint(x, y) {
  9566. return this.viewport.convertToPdfPoint(x, y);
  9567. }
  9568. async #finishRenderTask(renderTask, error = null) {
  9569. if (renderTask === this.renderTask) {
  9570. this.renderTask = null;
  9571. }
  9572. if (error instanceof RenderingCancelledException) {
  9573. this.#renderError = null;
  9574. return;
  9575. }
  9576. this.#renderError = error;
  9577. this.renderingState = RenderingStates.FINISHED;
  9578. this._resetZoomLayer(true);
  9579. this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots;
  9580. this.eventBus.dispatch("pagerendered", {
  9581. source: this,
  9582. pageNumber: this.id,
  9583. cssTransform: false,
  9584. timestamp: performance.now(),
  9585. error: this.#renderError
  9586. });
  9587. if (error) {
  9588. throw error;
  9589. }
  9590. }
  9591. async draw() {
  9592. if (this.renderingState !== RenderingStates.INITIAL) {
  9593. console.error("Must be in new state before drawing");
  9594. this.reset();
  9595. }
  9596. const {
  9597. div,
  9598. l10n,
  9599. pageColors,
  9600. pdfPage,
  9601. viewport
  9602. } = this;
  9603. if (!pdfPage) {
  9604. this.renderingState = RenderingStates.FINISHED;
  9605. throw new Error("pdfPage is not loaded");
  9606. }
  9607. this.renderingState = RenderingStates.RUNNING;
  9608. const canvasWrapper = document.createElement("div");
  9609. canvasWrapper.classList.add("canvasWrapper");
  9610. this.#addLayer(canvasWrapper, "canvasWrapper");
  9611. if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) {
  9612. this._accessibilityManager ||= new TextAccessibilityManager();
  9613. this.textLayer = new TextLayerBuilder({
  9614. pdfPage,
  9615. highlighter: this._textHighlighter,
  9616. accessibilityManager: this._accessibilityManager,
  9617. enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS,
  9618. onAppend: textLayerDiv => {
  9619. this.l10n.pause();
  9620. this.#addLayer(textLayerDiv, "textLayer");
  9621. this.l10n.resume();
  9622. }
  9623. });
  9624. }
  9625. if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) {
  9626. const {
  9627. annotationStorage,
  9628. annotationEditorUIManager,
  9629. downloadManager,
  9630. enableScripting,
  9631. fieldObjectsPromise,
  9632. hasJSActionsPromise,
  9633. linkService
  9634. } = this.#layerProperties;
  9635. this._annotationCanvasMap ||= new Map();
  9636. this.annotationLayer = new AnnotationLayerBuilder({
  9637. pdfPage,
  9638. annotationStorage,
  9639. imageResourcesPath: this.imageResourcesPath,
  9640. renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS,
  9641. linkService,
  9642. downloadManager,
  9643. enableScripting,
  9644. hasJSActionsPromise,
  9645. fieldObjectsPromise,
  9646. annotationCanvasMap: this._annotationCanvasMap,
  9647. accessibilityManager: this._accessibilityManager,
  9648. annotationEditorUIManager,
  9649. onAppend: annotationLayerDiv => {
  9650. this.#addLayer(annotationLayerDiv, "annotationLayer");
  9651. }
  9652. });
  9653. }
  9654. const renderContinueCallback = cont => {
  9655. showCanvas?.(false);
  9656. if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) {
  9657. this.renderingState = RenderingStates.PAUSED;
  9658. this.resume = () => {
  9659. this.renderingState = RenderingStates.RUNNING;
  9660. cont();
  9661. };
  9662. return;
  9663. }
  9664. cont();
  9665. };
  9666. const {
  9667. width,
  9668. height
  9669. } = viewport;
  9670. const canvas = document.createElement("canvas");
  9671. canvas.setAttribute("role", "presentation");
  9672. canvas.hidden = true;
  9673. const hasHCM = !!(pageColors?.background && pageColors?.foreground);
  9674. let showCanvas = isLastShow => {
  9675. if (!hasHCM || isLastShow) {
  9676. canvas.hidden = false;
  9677. showCanvas = null;
  9678. }
  9679. };
  9680. canvasWrapper.append(canvas);
  9681. this.canvas = canvas;
  9682. const ctx = canvas.getContext("2d", {
  9683. alpha: false,
  9684. willReadFrequently: !this.#enableHWA
  9685. });
  9686. const outputScale = this.outputScale = new OutputScale();
  9687. if (this.maxCanvasPixels === 0) {
  9688. const invScale = 1 / this.scale;
  9689. outputScale.sx *= invScale;
  9690. outputScale.sy *= invScale;
  9691. this.#hasRestrictedScaling = true;
  9692. } else if (this.maxCanvasPixels > 0) {
  9693. const pixelsInViewport = width * height;
  9694. const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport);
  9695. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  9696. outputScale.sx = maxScale;
  9697. outputScale.sy = maxScale;
  9698. this.#hasRestrictedScaling = true;
  9699. } else {
  9700. this.#hasRestrictedScaling = false;
  9701. }
  9702. }
  9703. const sfx = approximateFraction(outputScale.sx);
  9704. const sfy = approximateFraction(outputScale.sy);
  9705. canvas.width = floorToDivide(width * outputScale.sx, sfx[0]);
  9706. canvas.height = floorToDivide(height * outputScale.sy, sfy[0]);
  9707. const {
  9708. style
  9709. } = canvas;
  9710. style.width = floorToDivide(width, sfx[1]) + "px";
  9711. style.height = floorToDivide(height, sfy[1]) + "px";
  9712. this.#viewportMap.set(canvas, viewport);
  9713. const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null;
  9714. const renderContext = {
  9715. canvasContext: ctx,
  9716. transform,
  9717. viewport,
  9718. annotationMode: this.#annotationMode,
  9719. optionalContentConfigPromise: this._optionalContentConfigPromise,
  9720. annotationCanvasMap: this._annotationCanvasMap,
  9721. pageColors,
  9722. isEditing: this.#isEditing
  9723. };
  9724. const renderTask = this.renderTask = pdfPage.render(renderContext);
  9725. renderTask.onContinue = renderContinueCallback;
  9726. const resultPromise = renderTask.promise.then(async () => {
  9727. showCanvas?.(true);
  9728. await this.#finishRenderTask(renderTask);
  9729. this.#renderTextLayer();
  9730. if (this.annotationLayer) {
  9731. await this.#renderAnnotationLayer();
  9732. }
  9733. const {
  9734. annotationEditorUIManager
  9735. } = this.#layerProperties;
  9736. if (!annotationEditorUIManager) {
  9737. return;
  9738. }
  9739. this.drawLayer ||= new DrawLayerBuilder({
  9740. pageIndex: this.id
  9741. });
  9742. await this.#renderDrawLayer();
  9743. this.drawLayer.setParent(canvasWrapper);
  9744. if (!this.annotationEditorLayer) {
  9745. this.annotationEditorLayer = new AnnotationEditorLayerBuilder({
  9746. uiManager: annotationEditorUIManager,
  9747. pdfPage,
  9748. l10n,
  9749. accessibilityManager: this._accessibilityManager,
  9750. annotationLayer: this.annotationLayer?.annotationLayer,
  9751. textLayer: this.textLayer,
  9752. drawLayer: this.drawLayer.getDrawLayer(),
  9753. onAppend: annotationEditorLayerDiv => {
  9754. this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer");
  9755. }
  9756. });
  9757. }
  9758. this.#renderAnnotationEditorLayer();
  9759. }, error => {
  9760. if (!(error instanceof RenderingCancelledException)) {
  9761. showCanvas?.(true);
  9762. }
  9763. return this.#finishRenderTask(renderTask, error);
  9764. });
  9765. if (pdfPage.isPureXfa) {
  9766. if (!this.xfaLayer) {
  9767. const {
  9768. annotationStorage,
  9769. linkService
  9770. } = this.#layerProperties;
  9771. this.xfaLayer = new XfaLayerBuilder({
  9772. pdfPage,
  9773. annotationStorage,
  9774. linkService
  9775. });
  9776. }
  9777. this.#renderXfaLayer();
  9778. }
  9779. div.setAttribute("data-loaded", true);
  9780. this.eventBus.dispatch("pagerender", {
  9781. source: this,
  9782. pageNumber: this.id
  9783. });
  9784. return resultPromise;
  9785. }
  9786. setPageLabel(label) {
  9787. this.pageLabel = typeof label === "string" ? label : null;
  9788. this.div.setAttribute("data-l10n-args", JSON.stringify({
  9789. page: this.pageLabel ?? this.id
  9790. }));
  9791. if (this.pageLabel !== null) {
  9792. this.div.setAttribute("data-page-label", this.pageLabel);
  9793. } else {
  9794. this.div.removeAttribute("data-page-label");
  9795. }
  9796. }
  9797. get thumbnailCanvas() {
  9798. const {
  9799. directDrawing,
  9800. initialOptionalContent,
  9801. regularAnnotations
  9802. } = this.#useThumbnailCanvas;
  9803. return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null;
  9804. }
  9805. }
  9806. ;// CONCATENATED MODULE: ./web/pdf_viewer.js
  9807. const DEFAULT_CACHE_SIZE = 10;
  9808. const PagesCountLimit = {
  9809. FORCE_SCROLL_MODE_PAGE: 10000,
  9810. FORCE_LAZY_PAGE_INIT: 5000,
  9811. PAUSE_EAGER_PAGE_INIT: 250
  9812. };
  9813. function isValidAnnotationEditorMode(mode) {
  9814. return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE;
  9815. }
  9816. class PDFPageViewBuffer {
  9817. #buf = new Set();
  9818. #size = 0;
  9819. constructor(size) {
  9820. this.#size = size;
  9821. }
  9822. push(view) {
  9823. const buf = this.#buf;
  9824. if (buf.has(view)) {
  9825. buf.delete(view);
  9826. }
  9827. buf.add(view);
  9828. if (buf.size > this.#size) {
  9829. this.#destroyFirstView();
  9830. }
  9831. }
  9832. resize(newSize, idsToKeep = null) {
  9833. this.#size = newSize;
  9834. const buf = this.#buf;
  9835. if (idsToKeep) {
  9836. const ii = buf.size;
  9837. let i = 1;
  9838. for (const view of buf) {
  9839. if (idsToKeep.has(view.id)) {
  9840. buf.delete(view);
  9841. buf.add(view);
  9842. }
  9843. if (++i > ii) {
  9844. break;
  9845. }
  9846. }
  9847. }
  9848. while (buf.size > this.#size) {
  9849. this.#destroyFirstView();
  9850. }
  9851. }
  9852. has(view) {
  9853. return this.#buf.has(view);
  9854. }
  9855. [Symbol.iterator]() {
  9856. return this.#buf.keys();
  9857. }
  9858. #destroyFirstView() {
  9859. const firstView = this.#buf.keys().next().value;
  9860. firstView?.destroy();
  9861. this.#buf.delete(firstView);
  9862. }
  9863. }
  9864. class PDFViewer {
  9865. #buffer = null;
  9866. #altTextManager = null;
  9867. #annotationEditorHighlightColors = null;
  9868. #annotationEditorMode = AnnotationEditorType.NONE;
  9869. #annotationEditorUIManager = null;
  9870. #annotationMode = AnnotationMode.ENABLE_FORMS;
  9871. #containerTopLeft = null;
  9872. #enableHWA = false;
  9873. #enableHighlightFloatingButton = false;
  9874. #enablePermissions = false;
  9875. #enableUpdatedAddImage = false;
  9876. #eventAbortController = null;
  9877. #mlManager = null;
  9878. #onPageRenderedCallback = null;
  9879. #switchAnnotationEditorModeTimeoutId = null;
  9880. #getAllTextInProgress = false;
  9881. #hiddenCopyElement = null;
  9882. #interruptCopyCondition = false;
  9883. #previousContainerHeight = 0;
  9884. #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this));
  9885. #scrollModePageState = null;
  9886. #scaleTimeoutId = null;
  9887. #textLayerMode = TextLayerMode.ENABLE;
  9888. constructor(options) {
  9889. const viewerVersion = "4.5.136";
  9890. if (version !== viewerVersion) {
  9891. throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`);
  9892. }
  9893. this.container = options.container;
  9894. this.viewer = options.viewer || options.container.firstElementChild;
  9895. if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") {
  9896. throw new Error("Invalid `container` and/or `viewer` option.");
  9897. }
  9898. if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") {
  9899. throw new Error("The `container` must be absolutely positioned.");
  9900. }
  9901. this.#resizeObserver.observe(this.container);
  9902. this.eventBus = options.eventBus;
  9903. this.linkService = options.linkService || new SimpleLinkService();
  9904. this.downloadManager = options.downloadManager || null;
  9905. this.findController = options.findController || null;
  9906. this.#altTextManager = options.altTextManager || null;
  9907. if (this.findController) {
  9908. this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber);
  9909. }
  9910. this._scriptingManager = options.scriptingManager || null;
  9911. this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE;
  9912. this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS;
  9913. this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE;
  9914. this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null;
  9915. this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true;
  9916. this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true;
  9917. this.imageResourcesPath = options.imageResourcesPath || "";
  9918. this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;
  9919. this.removePageBorders = options.removePageBorders || false;
  9920. this.maxCanvasPixels = options.maxCanvasPixels;
  9921. this.l10n = options.l10n;
  9922. this.l10n ||= new genericl10n_GenericL10n();
  9923. this.#enablePermissions = options.enablePermissions || false;
  9924. this.pageColors = options.pageColors || null;
  9925. this.#mlManager = options.mlManager || null;
  9926. this.#enableHWA = options.enableHWA || false;
  9927. this.defaultRenderingQueue = !options.renderingQueue;
  9928. if (this.defaultRenderingQueue) {
  9929. this.renderingQueue = new PDFRenderingQueue();
  9930. this.renderingQueue.setViewer(this);
  9931. } else {
  9932. this.renderingQueue = options.renderingQueue;
  9933. }
  9934. const {
  9935. abortSignal
  9936. } = options;
  9937. abortSignal?.addEventListener("abort", () => {
  9938. this.#resizeObserver.disconnect();
  9939. this.#resizeObserver = null;
  9940. }, {
  9941. once: true
  9942. });
  9943. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal);
  9944. this.presentationModeState = PresentationModeState.UNKNOWN;
  9945. this._resetView();
  9946. if (this.removePageBorders) {
  9947. this.viewer.classList.add("removePageBorders");
  9948. }
  9949. this.#updateContainerHeightCss();
  9950. this.eventBus._on("thumbnailrendered", ({
  9951. pageNumber,
  9952. pdfPage
  9953. }) => {
  9954. const pageView = this._pages[pageNumber - 1];
  9955. if (!this.#buffer.has(pageView)) {
  9956. pdfPage?.cleanup();
  9957. }
  9958. });
  9959. if (!options.l10n) {
  9960. this.l10n.translate(this.container);
  9961. }
  9962. }
  9963. get pagesCount() {
  9964. return this._pages.length;
  9965. }
  9966. getPageView(index) {
  9967. return this._pages[index];
  9968. }
  9969. getCachedPageViews() {
  9970. return new Set(this.#buffer);
  9971. }
  9972. get pageViewsReady() {
  9973. return this._pages.every(pageView => pageView?.pdfPage);
  9974. }
  9975. get renderForms() {
  9976. return this.#annotationMode === AnnotationMode.ENABLE_FORMS;
  9977. }
  9978. get enableScripting() {
  9979. return !!this._scriptingManager;
  9980. }
  9981. get currentPageNumber() {
  9982. return this._currentPageNumber;
  9983. }
  9984. set currentPageNumber(val) {
  9985. if (!Number.isInteger(val)) {
  9986. throw new Error("Invalid page number.");
  9987. }
  9988. if (!this.pdfDocument) {
  9989. return;
  9990. }
  9991. if (!this._setCurrentPageNumber(val, true)) {
  9992. console.error(`currentPageNumber: "${val}" is not a valid page.`);
  9993. }
  9994. }
  9995. _setCurrentPageNumber(val, resetCurrentPageView = false) {
  9996. if (this._currentPageNumber === val) {
  9997. if (resetCurrentPageView) {
  9998. this.#resetCurrentPageView();
  9999. }
  10000. return true;
  10001. }
  10002. if (!(0 < val && val <= this.pagesCount)) {
  10003. return false;
  10004. }
  10005. const previous = this._currentPageNumber;
  10006. this._currentPageNumber = val;
  10007. this.eventBus.dispatch("pagechanging", {
  10008. source: this,
  10009. pageNumber: val,
  10010. pageLabel: this._pageLabels?.[val - 1] ?? null,
  10011. previous
  10012. });
  10013. if (resetCurrentPageView) {
  10014. this.#resetCurrentPageView();
  10015. }
  10016. return true;
  10017. }
  10018. get currentPageLabel() {
  10019. return this._pageLabels?.[this._currentPageNumber - 1] ?? null;
  10020. }
  10021. set currentPageLabel(val) {
  10022. if (!this.pdfDocument) {
  10023. return;
  10024. }
  10025. let page = val | 0;
  10026. if (this._pageLabels) {
  10027. const i = this._pageLabels.indexOf(val);
  10028. if (i >= 0) {
  10029. page = i + 1;
  10030. }
  10031. }
  10032. if (!this._setCurrentPageNumber(page, true)) {
  10033. console.error(`currentPageLabel: "${val}" is not a valid page.`);
  10034. }
  10035. }
  10036. get currentScale() {
  10037. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE;
  10038. }
  10039. set currentScale(val) {
  10040. if (isNaN(val)) {
  10041. throw new Error("Invalid numeric scale.");
  10042. }
  10043. if (!this.pdfDocument) {
  10044. return;
  10045. }
  10046. this.#setScale(val, {
  10047. noScroll: false
  10048. });
  10049. }
  10050. get currentScaleValue() {
  10051. return this._currentScaleValue;
  10052. }
  10053. set currentScaleValue(val) {
  10054. if (!this.pdfDocument) {
  10055. return;
  10056. }
  10057. this.#setScale(val, {
  10058. noScroll: false
  10059. });
  10060. }
  10061. get pagesRotation() {
  10062. return this._pagesRotation;
  10063. }
  10064. set pagesRotation(rotation) {
  10065. if (!isValidRotation(rotation)) {
  10066. throw new Error("Invalid pages rotation angle.");
  10067. }
  10068. if (!this.pdfDocument) {
  10069. return;
  10070. }
  10071. rotation %= 360;
  10072. if (rotation < 0) {
  10073. rotation += 360;
  10074. }
  10075. if (this._pagesRotation === rotation) {
  10076. return;
  10077. }
  10078. this._pagesRotation = rotation;
  10079. const pageNumber = this._currentPageNumber;
  10080. this.refresh(true, {
  10081. rotation
  10082. });
  10083. if (this._currentScaleValue) {
  10084. this.#setScale(this._currentScaleValue, {
  10085. noScroll: true
  10086. });
  10087. }
  10088. this.eventBus.dispatch("rotationchanging", {
  10089. source: this,
  10090. pagesRotation: rotation,
  10091. pageNumber
  10092. });
  10093. if (this.defaultRenderingQueue) {
  10094. this.update();
  10095. }
  10096. }
  10097. get firstPagePromise() {
  10098. return this.pdfDocument ? this._firstPageCapability.promise : null;
  10099. }
  10100. get onePageRendered() {
  10101. return this.pdfDocument ? this._onePageRenderedCapability.promise : null;
  10102. }
  10103. get pagesPromise() {
  10104. return this.pdfDocument ? this._pagesCapability.promise : null;
  10105. }
  10106. get _layerProperties() {
  10107. const self = this;
  10108. return shadow(this, "_layerProperties", {
  10109. get annotationEditorUIManager() {
  10110. return self.#annotationEditorUIManager;
  10111. },
  10112. get annotationStorage() {
  10113. return self.pdfDocument?.annotationStorage;
  10114. },
  10115. get downloadManager() {
  10116. return self.downloadManager;
  10117. },
  10118. get enableScripting() {
  10119. return !!self._scriptingManager;
  10120. },
  10121. get fieldObjectsPromise() {
  10122. return self.pdfDocument?.getFieldObjects();
  10123. },
  10124. get findController() {
  10125. return self.findController;
  10126. },
  10127. get hasJSActionsPromise() {
  10128. return self.pdfDocument?.hasJSActions();
  10129. },
  10130. get linkService() {
  10131. return self.linkService;
  10132. }
  10133. });
  10134. }
  10135. #initializePermissions(permissions) {
  10136. const params = {
  10137. annotationEditorMode: this.#annotationEditorMode,
  10138. annotationMode: this.#annotationMode,
  10139. textLayerMode: this.#textLayerMode
  10140. };
  10141. if (!permissions) {
  10142. return params;
  10143. }
  10144. if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) {
  10145. params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS;
  10146. }
  10147. if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) {
  10148. params.annotationEditorMode = AnnotationEditorType.DISABLE;
  10149. }
  10150. if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) {
  10151. params.annotationMode = AnnotationMode.ENABLE;
  10152. }
  10153. return params;
  10154. }
  10155. async #onePageRenderedOrForceFetch(signal) {
  10156. if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) {
  10157. return;
  10158. }
  10159. const hiddenCapability = Promise.withResolvers();
  10160. function onVisibilityChange() {
  10161. if (document.visibilityState === "hidden") {
  10162. hiddenCapability.resolve();
  10163. }
  10164. }
  10165. document.addEventListener("visibilitychange", onVisibilityChange, {
  10166. signal
  10167. });
  10168. await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]);
  10169. document.removeEventListener("visibilitychange", onVisibilityChange);
  10170. }
  10171. async getAllText() {
  10172. const texts = [];
  10173. const buffer = [];
  10174. for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) {
  10175. if (this.#interruptCopyCondition) {
  10176. return null;
  10177. }
  10178. buffer.length = 0;
  10179. const page = await this.pdfDocument.getPage(pageNum);
  10180. const {
  10181. items
  10182. } = await page.getTextContent();
  10183. for (const item of items) {
  10184. if (item.str) {
  10185. buffer.push(item.str);
  10186. }
  10187. if (item.hasEOL) {
  10188. buffer.push("\n");
  10189. }
  10190. }
  10191. texts.push(removeNullCharacters(buffer.join("")));
  10192. }
  10193. return texts.join("\n");
  10194. }
  10195. #copyCallback(textLayerMode, event) {
  10196. const selection = document.getSelection();
  10197. const {
  10198. focusNode,
  10199. anchorNode
  10200. } = selection;
  10201. if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) {
  10202. if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) {
  10203. event.preventDefault();
  10204. event.stopPropagation();
  10205. return;
  10206. }
  10207. this.#getAllTextInProgress = true;
  10208. const {
  10209. classList
  10210. } = this.viewer;
  10211. classList.add("copyAll");
  10212. const ac = new AbortController();
  10213. window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", {
  10214. signal: ac.signal
  10215. });
  10216. this.getAllText().then(async text => {
  10217. if (text !== null) {
  10218. await navigator.clipboard.writeText(text);
  10219. }
  10220. }).catch(reason => {
  10221. console.warn(`Something goes wrong when extracting the text: ${reason.message}`);
  10222. }).finally(() => {
  10223. this.#getAllTextInProgress = false;
  10224. this.#interruptCopyCondition = false;
  10225. ac.abort();
  10226. classList.remove("copyAll");
  10227. });
  10228. event.preventDefault();
  10229. event.stopPropagation();
  10230. }
  10231. }
  10232. setDocument(pdfDocument) {
  10233. if (this.pdfDocument) {
  10234. this.eventBus.dispatch("pagesdestroy", {
  10235. source: this
  10236. });
  10237. this._cancelRendering();
  10238. this._resetView();
  10239. this.findController?.setDocument(null);
  10240. this._scriptingManager?.setDocument(null);
  10241. if (this.#annotationEditorUIManager) {
  10242. this.#annotationEditorUIManager.destroy();
  10243. this.#annotationEditorUIManager = null;
  10244. }
  10245. }
  10246. this.pdfDocument = pdfDocument;
  10247. if (!pdfDocument) {
  10248. return;
  10249. }
  10250. const pagesCount = pdfDocument.numPages;
  10251. const firstPagePromise = pdfDocument.getPage(1);
  10252. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({
  10253. intent: "display"
  10254. });
  10255. const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve();
  10256. const {
  10257. eventBus,
  10258. pageColors,
  10259. viewer
  10260. } = this;
  10261. this.#eventAbortController = new AbortController();
  10262. const {
  10263. signal
  10264. } = this.#eventAbortController;
  10265. if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  10266. console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");
  10267. const mode = this._scrollMode = ScrollMode.PAGE;
  10268. eventBus.dispatch("scrollmodechanged", {
  10269. source: this,
  10270. mode
  10271. });
  10272. }
  10273. this._pagesCapability.promise.then(() => {
  10274. eventBus.dispatch("pagesloaded", {
  10275. source: this,
  10276. pagesCount
  10277. });
  10278. }, () => {});
  10279. const onBeforeDraw = evt => {
  10280. const pageView = this._pages[evt.pageNumber - 1];
  10281. if (!pageView) {
  10282. return;
  10283. }
  10284. this.#buffer.push(pageView);
  10285. };
  10286. eventBus._on("pagerender", onBeforeDraw, {
  10287. signal
  10288. });
  10289. const onAfterDraw = evt => {
  10290. if (evt.cssTransform) {
  10291. return;
  10292. }
  10293. this._onePageRenderedCapability.resolve({
  10294. timestamp: evt.timestamp
  10295. });
  10296. eventBus._off("pagerendered", onAfterDraw);
  10297. };
  10298. eventBus._on("pagerendered", onAfterDraw, {
  10299. signal
  10300. });
  10301. Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => {
  10302. if (pdfDocument !== this.pdfDocument) {
  10303. return;
  10304. }
  10305. this._firstPageCapability.resolve(firstPdfPage);
  10306. this._optionalContentConfigPromise = optionalContentConfigPromise;
  10307. const {
  10308. annotationEditorMode,
  10309. annotationMode,
  10310. textLayerMode
  10311. } = this.#initializePermissions(permissions);
  10312. if (textLayerMode !== TextLayerMode.DISABLE) {
  10313. const element = this.#hiddenCopyElement = document.createElement("div");
  10314. element.id = "hiddenCopyElement";
  10315. viewer.before(element);
  10316. }
  10317. if (annotationEditorMode !== AnnotationEditorType.DISABLE) {
  10318. const mode = annotationEditorMode;
  10319. if (pdfDocument.isPureXfa) {
  10320. console.warn("Warning: XFA-editing is not implemented.");
  10321. } else if (isValidAnnotationEditorMode(mode)) {
  10322. this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#mlManager);
  10323. eventBus.dispatch("annotationeditoruimanager", {
  10324. source: this,
  10325. uiManager: this.#annotationEditorUIManager
  10326. });
  10327. if (mode !== AnnotationEditorType.NONE) {
  10328. this.#annotationEditorUIManager.updateMode(mode);
  10329. }
  10330. } else {
  10331. console.error(`Invalid AnnotationEditor mode: ${mode}`);
  10332. }
  10333. }
  10334. const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer;
  10335. const scale = this.currentScale;
  10336. const viewport = firstPdfPage.getViewport({
  10337. scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS
  10338. });
  10339. viewer.style.setProperty("--scale-factor", viewport.scale);
  10340. if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") {
  10341. viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight"));
  10342. viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText"));
  10343. }
  10344. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  10345. const pageView = new PDFPageView({
  10346. container: viewerElement,
  10347. eventBus,
  10348. id: pageNum,
  10349. scale,
  10350. defaultViewport: viewport.clone(),
  10351. optionalContentConfigPromise,
  10352. renderingQueue: this.renderingQueue,
  10353. textLayerMode,
  10354. annotationMode,
  10355. imageResourcesPath: this.imageResourcesPath,
  10356. maxCanvasPixels: this.maxCanvasPixels,
  10357. pageColors,
  10358. l10n: this.l10n,
  10359. layerProperties: this._layerProperties,
  10360. enableHWA: this.#enableHWA
  10361. });
  10362. this._pages.push(pageView);
  10363. }
  10364. this._pages[0]?.setPdfPage(firstPdfPage);
  10365. if (this._scrollMode === ScrollMode.PAGE) {
  10366. this.#ensurePageViewVisible();
  10367. } else if (this._spreadMode !== SpreadMode.NONE) {
  10368. this._updateSpreadMode();
  10369. }
  10370. this.#onePageRenderedOrForceFetch(signal).then(async () => {
  10371. if (pdfDocument !== this.pdfDocument) {
  10372. return;
  10373. }
  10374. this.findController?.setDocument(pdfDocument);
  10375. this._scriptingManager?.setDocument(pdfDocument);
  10376. if (this.#hiddenCopyElement) {
  10377. document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), {
  10378. signal
  10379. });
  10380. }
  10381. if (this.#annotationEditorUIManager) {
  10382. eventBus.dispatch("annotationeditormodechanged", {
  10383. source: this,
  10384. mode: this.#annotationEditorMode
  10385. });
  10386. }
  10387. if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) {
  10388. this._pagesCapability.resolve();
  10389. return;
  10390. }
  10391. let getPagesLeft = pagesCount - 1;
  10392. if (getPagesLeft <= 0) {
  10393. this._pagesCapability.resolve();
  10394. return;
  10395. }
  10396. for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) {
  10397. const promise = pdfDocument.getPage(pageNum).then(pdfPage => {
  10398. const pageView = this._pages[pageNum - 1];
  10399. if (!pageView.pdfPage) {
  10400. pageView.setPdfPage(pdfPage);
  10401. }
  10402. if (--getPagesLeft === 0) {
  10403. this._pagesCapability.resolve();
  10404. }
  10405. }, reason => {
  10406. console.error(`Unable to get page ${pageNum} to initialize viewer`, reason);
  10407. if (--getPagesLeft === 0) {
  10408. this._pagesCapability.resolve();
  10409. }
  10410. });
  10411. if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) {
  10412. await promise;
  10413. }
  10414. }
  10415. });
  10416. eventBus.dispatch("pagesinit", {
  10417. source: this
  10418. });
  10419. pdfDocument.getMetadata().then(({
  10420. info
  10421. }) => {
  10422. if (pdfDocument !== this.pdfDocument) {
  10423. return;
  10424. }
  10425. if (info.Language) {
  10426. viewer.lang = info.Language;
  10427. }
  10428. });
  10429. if (this.defaultRenderingQueue) {
  10430. this.update();
  10431. }
  10432. }).catch(reason => {
  10433. console.error("Unable to initialize viewer", reason);
  10434. this._pagesCapability.reject(reason);
  10435. });
  10436. }
  10437. setPageLabels(labels) {
  10438. if (!this.pdfDocument) {
  10439. return;
  10440. }
  10441. if (!labels) {
  10442. this._pageLabels = null;
  10443. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  10444. this._pageLabels = null;
  10445. console.error(`setPageLabels: Invalid page labels.`);
  10446. } else {
  10447. this._pageLabels = labels;
  10448. }
  10449. for (let i = 0, ii = this._pages.length; i < ii; i++) {
  10450. this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null);
  10451. }
  10452. }
  10453. _resetView() {
  10454. this._pages = [];
  10455. this._currentPageNumber = 1;
  10456. this._currentScale = UNKNOWN_SCALE;
  10457. this._currentScaleValue = null;
  10458. this._pageLabels = null;
  10459. this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  10460. this._location = null;
  10461. this._pagesRotation = 0;
  10462. this._optionalContentConfigPromise = null;
  10463. this._firstPageCapability = Promise.withResolvers();
  10464. this._onePageRenderedCapability = Promise.withResolvers();
  10465. this._pagesCapability = Promise.withResolvers();
  10466. this._scrollMode = ScrollMode.VERTICAL;
  10467. this._previousScrollMode = ScrollMode.UNKNOWN;
  10468. this._spreadMode = SpreadMode.NONE;
  10469. this.#scrollModePageState = {
  10470. previousPageNumber: 1,
  10471. scrollDown: true,
  10472. pages: []
  10473. };
  10474. this.#eventAbortController?.abort();
  10475. this.#eventAbortController = null;
  10476. this.viewer.textContent = "";
  10477. this._updateScrollMode();
  10478. this.viewer.removeAttribute("lang");
  10479. this.#hiddenCopyElement?.remove();
  10480. this.#hiddenCopyElement = null;
  10481. this.#cleanupSwitchAnnotationEditorMode();
  10482. }
  10483. #ensurePageViewVisible() {
  10484. if (this._scrollMode !== ScrollMode.PAGE) {
  10485. throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");
  10486. }
  10487. const pageNumber = this._currentPageNumber,
  10488. state = this.#scrollModePageState,
  10489. viewer = this.viewer;
  10490. viewer.textContent = "";
  10491. state.pages.length = 0;
  10492. if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) {
  10493. const pageView = this._pages[pageNumber - 1];
  10494. viewer.append(pageView.div);
  10495. state.pages.push(pageView);
  10496. } else {
  10497. const pageIndexSet = new Set(),
  10498. parity = this._spreadMode - 1;
  10499. if (parity === -1) {
  10500. pageIndexSet.add(pageNumber - 1);
  10501. } else if (pageNumber % 2 !== parity) {
  10502. pageIndexSet.add(pageNumber - 1);
  10503. pageIndexSet.add(pageNumber);
  10504. } else {
  10505. pageIndexSet.add(pageNumber - 2);
  10506. pageIndexSet.add(pageNumber - 1);
  10507. }
  10508. const spread = document.createElement("div");
  10509. spread.className = "spread";
  10510. if (this.isInPresentationMode) {
  10511. const dummyPage = document.createElement("div");
  10512. dummyPage.className = "dummyPage";
  10513. spread.append(dummyPage);
  10514. }
  10515. for (const i of pageIndexSet) {
  10516. const pageView = this._pages[i];
  10517. if (!pageView) {
  10518. continue;
  10519. }
  10520. spread.append(pageView.div);
  10521. state.pages.push(pageView);
  10522. }
  10523. viewer.append(spread);
  10524. }
  10525. state.scrollDown = pageNumber >= state.previousPageNumber;
  10526. state.previousPageNumber = pageNumber;
  10527. }
  10528. _scrollUpdate() {
  10529. if (this.pagesCount === 0) {
  10530. return;
  10531. }
  10532. this.update();
  10533. }
  10534. #scrollIntoView(pageView, pageSpot = null) {
  10535. const {
  10536. div,
  10537. id
  10538. } = pageView;
  10539. if (this._currentPageNumber !== id) {
  10540. this._setCurrentPageNumber(id);
  10541. }
  10542. if (this._scrollMode === ScrollMode.PAGE) {
  10543. this.#ensurePageViewVisible();
  10544. this.update();
  10545. }
  10546. if (!pageSpot && !this.isInPresentationMode) {
  10547. const left = div.offsetLeft + div.clientLeft,
  10548. right = left + div.clientWidth;
  10549. const {
  10550. scrollLeft,
  10551. clientWidth
  10552. } = this.container;
  10553. if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) {
  10554. pageSpot = {
  10555. left: 0,
  10556. top: 0
  10557. };
  10558. }
  10559. }
  10560. scrollIntoView(div, pageSpot);
  10561. if (!this._currentScaleValue && this._location) {
  10562. this._location = null;
  10563. }
  10564. }
  10565. #isSameScale(newScale) {
  10566. return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15;
  10567. }
  10568. #setScaleUpdatePages(newScale, newValue, {
  10569. noScroll = false,
  10570. preset = false,
  10571. drawingDelay = -1,
  10572. origin = null
  10573. }) {
  10574. this._currentScaleValue = newValue.toString();
  10575. if (this.#isSameScale(newScale)) {
  10576. if (preset) {
  10577. this.eventBus.dispatch("scalechanging", {
  10578. source: this,
  10579. scale: newScale,
  10580. presetValue: newValue
  10581. });
  10582. }
  10583. return;
  10584. }
  10585. this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS);
  10586. const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000;
  10587. this.refresh(true, {
  10588. scale: newScale,
  10589. drawingDelay: postponeDrawing ? drawingDelay : -1
  10590. });
  10591. if (postponeDrawing) {
  10592. this.#scaleTimeoutId = setTimeout(() => {
  10593. this.#scaleTimeoutId = null;
  10594. this.refresh();
  10595. }, drawingDelay);
  10596. }
  10597. const previousScale = this._currentScale;
  10598. this._currentScale = newScale;
  10599. if (!noScroll) {
  10600. let page = this._currentPageNumber,
  10601. dest;
  10602. if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  10603. page = this._location.pageNumber;
  10604. dest = [null, {
  10605. name: "XYZ"
  10606. }, this._location.left, this._location.top, null];
  10607. }
  10608. this.scrollPageIntoView({
  10609. pageNumber: page,
  10610. destArray: dest,
  10611. allowNegativeOffset: true
  10612. });
  10613. if (Array.isArray(origin)) {
  10614. const scaleDiff = newScale / previousScale - 1;
  10615. const [top, left] = this.containerTopLeft;
  10616. this.container.scrollLeft += (origin[0] - left) * scaleDiff;
  10617. this.container.scrollTop += (origin[1] - top) * scaleDiff;
  10618. }
  10619. }
  10620. this.eventBus.dispatch("scalechanging", {
  10621. source: this,
  10622. scale: newScale,
  10623. presetValue: preset ? newValue : undefined
  10624. });
  10625. if (this.defaultRenderingQueue) {
  10626. this.update();
  10627. }
  10628. }
  10629. get #pageWidthScaleFactor() {
  10630. if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) {
  10631. return 2;
  10632. }
  10633. return 1;
  10634. }
  10635. #setScale(value, options) {
  10636. let scale = parseFloat(value);
  10637. if (scale > 0) {
  10638. options.preset = false;
  10639. this.#setScaleUpdatePages(scale, value, options);
  10640. } else {
  10641. const currentPage = this._pages[this._currentPageNumber - 1];
  10642. if (!currentPage) {
  10643. return;
  10644. }
  10645. let hPadding = SCROLLBAR_PADDING,
  10646. vPadding = VERTICAL_PADDING;
  10647. if (this.isInPresentationMode) {
  10648. hPadding = vPadding = 4;
  10649. if (this._spreadMode !== SpreadMode.NONE) {
  10650. hPadding *= 2;
  10651. }
  10652. } else if (this.removePageBorders) {
  10653. hPadding = vPadding = 0;
  10654. } else if (this._scrollMode === ScrollMode.HORIZONTAL) {
  10655. [hPadding, vPadding] = [vPadding, hPadding];
  10656. }
  10657. const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor;
  10658. const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  10659. switch (value) {
  10660. case "page-actual":
  10661. scale = 1;
  10662. break;
  10663. case "page-width":
  10664. scale = pageWidthScale;
  10665. break;
  10666. case "page-height":
  10667. scale = pageHeightScale;
  10668. break;
  10669. case "page-fit":
  10670. scale = Math.min(pageWidthScale, pageHeightScale);
  10671. break;
  10672. case "auto":
  10673. const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale);
  10674. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  10675. break;
  10676. default:
  10677. console.error(`#setScale: "${value}" is an unknown zoom value.`);
  10678. return;
  10679. }
  10680. options.preset = true;
  10681. this.#setScaleUpdatePages(scale, value, options);
  10682. }
  10683. }
  10684. #resetCurrentPageView() {
  10685. const pageView = this._pages[this._currentPageNumber - 1];
  10686. if (this.isInPresentationMode) {
  10687. this.#setScale(this._currentScaleValue, {
  10688. noScroll: true
  10689. });
  10690. }
  10691. this.#scrollIntoView(pageView);
  10692. }
  10693. pageLabelToPageNumber(label) {
  10694. if (!this._pageLabels) {
  10695. return null;
  10696. }
  10697. const i = this._pageLabels.indexOf(label);
  10698. if (i < 0) {
  10699. return null;
  10700. }
  10701. return i + 1;
  10702. }
  10703. scrollPageIntoView({
  10704. pageNumber,
  10705. destArray = null,
  10706. allowNegativeOffset = false,
  10707. ignoreDestinationZoom = false
  10708. }) {
  10709. if (!this.pdfDocument) {
  10710. return;
  10711. }
  10712. const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1];
  10713. if (!pageView) {
  10714. console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`);
  10715. return;
  10716. }
  10717. if (this.isInPresentationMode || !destArray) {
  10718. this._setCurrentPageNumber(pageNumber, true);
  10719. return;
  10720. }
  10721. let x = 0,
  10722. y = 0;
  10723. let width = 0,
  10724. height = 0,
  10725. widthScale,
  10726. heightScale;
  10727. const changeOrientation = pageView.rotation % 180 !== 0;
  10728. const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS;
  10729. const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS;
  10730. let scale = 0;
  10731. switch (destArray[1].name) {
  10732. case "XYZ":
  10733. x = destArray[2];
  10734. y = destArray[3];
  10735. scale = destArray[4];
  10736. x = x !== null ? x : 0;
  10737. y = y !== null ? y : pageHeight;
  10738. break;
  10739. case "Fit":
  10740. case "FitB":
  10741. scale = "page-fit";
  10742. break;
  10743. case "FitH":
  10744. case "FitBH":
  10745. y = destArray[2];
  10746. scale = "page-width";
  10747. if (y === null && this._location) {
  10748. x = this._location.left;
  10749. y = this._location.top;
  10750. } else if (typeof y !== "number" || y < 0) {
  10751. y = pageHeight;
  10752. }
  10753. break;
  10754. case "FitV":
  10755. case "FitBV":
  10756. x = destArray[2];
  10757. width = pageWidth;
  10758. height = pageHeight;
  10759. scale = "page-height";
  10760. break;
  10761. case "FitR":
  10762. x = destArray[2];
  10763. y = destArray[3];
  10764. width = destArray[4] - x;
  10765. height = destArray[5] - y;
  10766. let hPadding = SCROLLBAR_PADDING,
  10767. vPadding = VERTICAL_PADDING;
  10768. if (this.removePageBorders) {
  10769. hPadding = vPadding = 0;
  10770. }
  10771. widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS;
  10772. heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS;
  10773. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  10774. break;
  10775. default:
  10776. console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`);
  10777. return;
  10778. }
  10779. if (!ignoreDestinationZoom) {
  10780. if (scale && scale !== this._currentScale) {
  10781. this.currentScaleValue = scale;
  10782. } else if (this._currentScale === UNKNOWN_SCALE) {
  10783. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  10784. }
  10785. }
  10786. if (scale === "page-fit" && !destArray[4]) {
  10787. this.#scrollIntoView(pageView);
  10788. return;
  10789. }
  10790. const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)];
  10791. let left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  10792. let top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  10793. if (!allowNegativeOffset) {
  10794. left = Math.max(left, 0);
  10795. top = Math.max(top, 0);
  10796. }
  10797. this.#scrollIntoView(pageView, {
  10798. left,
  10799. top
  10800. });
  10801. }
  10802. _updateLocation(firstPage) {
  10803. const currentScale = this._currentScale;
  10804. const currentScaleValue = this._currentScaleValue;
  10805. const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  10806. const pageNumber = firstPage.id;
  10807. const currentPageView = this._pages[pageNumber - 1];
  10808. const container = this.container;
  10809. const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  10810. const intLeft = Math.round(topLeft[0]);
  10811. const intTop = Math.round(topLeft[1]);
  10812. let pdfOpenParams = `#page=${pageNumber}`;
  10813. if (!this.isInPresentationMode) {
  10814. pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`;
  10815. }
  10816. this._location = {
  10817. pageNumber,
  10818. scale: normalizedScaleValue,
  10819. top: intTop,
  10820. left: intLeft,
  10821. rotation: this._pagesRotation,
  10822. pdfOpenParams
  10823. };
  10824. }
  10825. update() {
  10826. const visible = this._getVisiblePages();
  10827. const visiblePages = visible.views,
  10828. numVisiblePages = visiblePages.length;
  10829. if (numVisiblePages === 0) {
  10830. return;
  10831. }
  10832. const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1);
  10833. this.#buffer.resize(newCacheSize, visible.ids);
  10834. this.renderingQueue.renderHighestPriority(visible);
  10835. const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL);
  10836. const currentId = this._currentPageNumber;
  10837. let stillFullyVisible = false;
  10838. for (const page of visiblePages) {
  10839. if (page.percent < 100) {
  10840. break;
  10841. }
  10842. if (page.id === currentId && isSimpleLayout) {
  10843. stillFullyVisible = true;
  10844. break;
  10845. }
  10846. }
  10847. this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id);
  10848. this._updateLocation(visible.first);
  10849. this.eventBus.dispatch("updateviewarea", {
  10850. source: this,
  10851. location: this._location
  10852. });
  10853. }
  10854. #switchToEditAnnotationMode() {
  10855. const visible = this._getVisiblePages();
  10856. const pagesToRefresh = [];
  10857. const {
  10858. ids,
  10859. views
  10860. } = visible;
  10861. for (const page of views) {
  10862. const {
  10863. view
  10864. } = page;
  10865. if (!view.hasEditableAnnotations()) {
  10866. ids.delete(view.id);
  10867. continue;
  10868. }
  10869. pagesToRefresh.push(page);
  10870. }
  10871. if (pagesToRefresh.length === 0) {
  10872. return null;
  10873. }
  10874. this.renderingQueue.renderHighestPriority({
  10875. first: pagesToRefresh[0],
  10876. last: pagesToRefresh.at(-1),
  10877. views: pagesToRefresh,
  10878. ids
  10879. });
  10880. return ids;
  10881. }
  10882. containsElement(element) {
  10883. return this.container.contains(element);
  10884. }
  10885. focus() {
  10886. this.container.focus();
  10887. }
  10888. get _isContainerRtl() {
  10889. return getComputedStyle(this.container).direction === "rtl";
  10890. }
  10891. get isInPresentationMode() {
  10892. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  10893. }
  10894. get isChangingPresentationMode() {
  10895. return this.presentationModeState === PresentationModeState.CHANGING;
  10896. }
  10897. get isHorizontalScrollbarEnabled() {
  10898. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  10899. }
  10900. get isVerticalScrollbarEnabled() {
  10901. return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight;
  10902. }
  10903. _getVisiblePages() {
  10904. const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages,
  10905. horizontal = this._scrollMode === ScrollMode.HORIZONTAL,
  10906. rtl = horizontal && this._isContainerRtl;
  10907. return getVisibleElements({
  10908. scrollEl: this.container,
  10909. views,
  10910. sortByVisibility: true,
  10911. horizontal,
  10912. rtl
  10913. });
  10914. }
  10915. cleanup() {
  10916. for (const pageView of this._pages) {
  10917. if (pageView.renderingState !== RenderingStates.FINISHED) {
  10918. pageView.reset();
  10919. }
  10920. }
  10921. }
  10922. _cancelRendering() {
  10923. for (const pageView of this._pages) {
  10924. pageView.cancelRendering();
  10925. }
  10926. }
  10927. async #ensurePdfPageLoaded(pageView) {
  10928. if (pageView.pdfPage) {
  10929. return pageView.pdfPage;
  10930. }
  10931. try {
  10932. const pdfPage = await this.pdfDocument.getPage(pageView.id);
  10933. if (!pageView.pdfPage) {
  10934. pageView.setPdfPage(pdfPage);
  10935. }
  10936. return pdfPage;
  10937. } catch (reason) {
  10938. console.error("Unable to get page for page view", reason);
  10939. return null;
  10940. }
  10941. }
  10942. #getScrollAhead(visible) {
  10943. if (visible.first?.id === 1) {
  10944. return true;
  10945. } else if (visible.last?.id === this.pagesCount) {
  10946. return false;
  10947. }
  10948. switch (this._scrollMode) {
  10949. case ScrollMode.PAGE:
  10950. return this.#scrollModePageState.scrollDown;
  10951. case ScrollMode.HORIZONTAL:
  10952. return this.scroll.right;
  10953. }
  10954. return this.scroll.down;
  10955. }
  10956. forceRendering(currentlyVisiblePages) {
  10957. const visiblePages = currentlyVisiblePages || this._getVisiblePages();
  10958. const scrollAhead = this.#getScrollAhead(visiblePages);
  10959. const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL;
  10960. const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra);
  10961. if (pageView) {
  10962. this.#ensurePdfPageLoaded(pageView).then(() => {
  10963. this.renderingQueue.renderView(pageView);
  10964. });
  10965. return true;
  10966. }
  10967. return false;
  10968. }
  10969. get hasEqualPageSizes() {
  10970. const firstPageView = this._pages[0];
  10971. for (let i = 1, ii = this._pages.length; i < ii; ++i) {
  10972. const pageView = this._pages[i];
  10973. if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) {
  10974. return false;
  10975. }
  10976. }
  10977. return true;
  10978. }
  10979. getPagesOverview() {
  10980. let initialOrientation;
  10981. return this._pages.map(pageView => {
  10982. const viewport = pageView.pdfPage.getViewport({
  10983. scale: 1
  10984. });
  10985. const orientation = isPortraitOrientation(viewport);
  10986. if (initialOrientation === undefined) {
  10987. initialOrientation = orientation;
  10988. } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) {
  10989. return {
  10990. width: viewport.height,
  10991. height: viewport.width,
  10992. rotation: (viewport.rotation - 90) % 360
  10993. };
  10994. }
  10995. return {
  10996. width: viewport.width,
  10997. height: viewport.height,
  10998. rotation: viewport.rotation
  10999. };
  11000. });
  11001. }
  11002. get optionalContentConfigPromise() {
  11003. if (!this.pdfDocument) {
  11004. return Promise.resolve(null);
  11005. }
  11006. if (!this._optionalContentConfigPromise) {
  11007. console.error("optionalContentConfigPromise: Not initialized yet.");
  11008. return this.pdfDocument.getOptionalContentConfig({
  11009. intent: "display"
  11010. });
  11011. }
  11012. return this._optionalContentConfigPromise;
  11013. }
  11014. set optionalContentConfigPromise(promise) {
  11015. if (!(promise instanceof Promise)) {
  11016. throw new Error(`Invalid optionalContentConfigPromise: ${promise}`);
  11017. }
  11018. if (!this.pdfDocument) {
  11019. return;
  11020. }
  11021. if (!this._optionalContentConfigPromise) {
  11022. return;
  11023. }
  11024. this._optionalContentConfigPromise = promise;
  11025. this.refresh(false, {
  11026. optionalContentConfigPromise: promise
  11027. });
  11028. this.eventBus.dispatch("optionalcontentconfigchanged", {
  11029. source: this,
  11030. promise
  11031. });
  11032. }
  11033. get scrollMode() {
  11034. return this._scrollMode;
  11035. }
  11036. set scrollMode(mode) {
  11037. if (this._scrollMode === mode) {
  11038. return;
  11039. }
  11040. if (!isValidScrollMode(mode)) {
  11041. throw new Error(`Invalid scroll mode: ${mode}`);
  11042. }
  11043. if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  11044. return;
  11045. }
  11046. this._previousScrollMode = this._scrollMode;
  11047. this._scrollMode = mode;
  11048. this.eventBus.dispatch("scrollmodechanged", {
  11049. source: this,
  11050. mode
  11051. });
  11052. this._updateScrollMode(this._currentPageNumber);
  11053. }
  11054. _updateScrollMode(pageNumber = null) {
  11055. const scrollMode = this._scrollMode,
  11056. viewer = this.viewer;
  11057. viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL);
  11058. viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED);
  11059. if (!this.pdfDocument || !pageNumber) {
  11060. return;
  11061. }
  11062. if (scrollMode === ScrollMode.PAGE) {
  11063. this.#ensurePageViewVisible();
  11064. } else if (this._previousScrollMode === ScrollMode.PAGE) {
  11065. this._updateSpreadMode();
  11066. }
  11067. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  11068. this.#setScale(this._currentScaleValue, {
  11069. noScroll: true
  11070. });
  11071. }
  11072. this._setCurrentPageNumber(pageNumber, true);
  11073. this.update();
  11074. }
  11075. get spreadMode() {
  11076. return this._spreadMode;
  11077. }
  11078. set spreadMode(mode) {
  11079. if (this._spreadMode === mode) {
  11080. return;
  11081. }
  11082. if (!isValidSpreadMode(mode)) {
  11083. throw new Error(`Invalid spread mode: ${mode}`);
  11084. }
  11085. this._spreadMode = mode;
  11086. this.eventBus.dispatch("spreadmodechanged", {
  11087. source: this,
  11088. mode
  11089. });
  11090. this._updateSpreadMode(this._currentPageNumber);
  11091. }
  11092. _updateSpreadMode(pageNumber = null) {
  11093. if (!this.pdfDocument) {
  11094. return;
  11095. }
  11096. const viewer = this.viewer,
  11097. pages = this._pages;
  11098. if (this._scrollMode === ScrollMode.PAGE) {
  11099. this.#ensurePageViewVisible();
  11100. } else {
  11101. viewer.textContent = "";
  11102. if (this._spreadMode === SpreadMode.NONE) {
  11103. for (const pageView of this._pages) {
  11104. viewer.append(pageView.div);
  11105. }
  11106. } else {
  11107. const parity = this._spreadMode - 1;
  11108. let spread = null;
  11109. for (let i = 0, ii = pages.length; i < ii; ++i) {
  11110. if (spread === null) {
  11111. spread = document.createElement("div");
  11112. spread.className = "spread";
  11113. viewer.append(spread);
  11114. } else if (i % 2 === parity) {
  11115. spread = spread.cloneNode(false);
  11116. viewer.append(spread);
  11117. }
  11118. spread.append(pages[i].div);
  11119. }
  11120. }
  11121. }
  11122. if (!pageNumber) {
  11123. return;
  11124. }
  11125. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  11126. this.#setScale(this._currentScaleValue, {
  11127. noScroll: true
  11128. });
  11129. }
  11130. this._setCurrentPageNumber(pageNumber, true);
  11131. this.update();
  11132. }
  11133. _getPageAdvance(currentPageNumber, previous = false) {
  11134. switch (this._scrollMode) {
  11135. case ScrollMode.WRAPPED:
  11136. {
  11137. const {
  11138. views
  11139. } = this._getVisiblePages(),
  11140. pageLayout = new Map();
  11141. for (const {
  11142. id,
  11143. y,
  11144. percent,
  11145. widthPercent
  11146. } of views) {
  11147. if (percent === 0 || widthPercent < 100) {
  11148. continue;
  11149. }
  11150. let yArray = pageLayout.get(y);
  11151. if (!yArray) {
  11152. pageLayout.set(y, yArray ||= []);
  11153. }
  11154. yArray.push(id);
  11155. }
  11156. for (const yArray of pageLayout.values()) {
  11157. const currentIndex = yArray.indexOf(currentPageNumber);
  11158. if (currentIndex === -1) {
  11159. continue;
  11160. }
  11161. const numPages = yArray.length;
  11162. if (numPages === 1) {
  11163. break;
  11164. }
  11165. if (previous) {
  11166. for (let i = currentIndex - 1, ii = 0; i >= ii; i--) {
  11167. const currentId = yArray[i],
  11168. expectedId = yArray[i + 1] - 1;
  11169. if (currentId < expectedId) {
  11170. return currentPageNumber - expectedId;
  11171. }
  11172. }
  11173. } else {
  11174. for (let i = currentIndex + 1, ii = numPages; i < ii; i++) {
  11175. const currentId = yArray[i],
  11176. expectedId = yArray[i - 1] + 1;
  11177. if (currentId > expectedId) {
  11178. return expectedId - currentPageNumber;
  11179. }
  11180. }
  11181. }
  11182. if (previous) {
  11183. const firstId = yArray[0];
  11184. if (firstId < currentPageNumber) {
  11185. return currentPageNumber - firstId + 1;
  11186. }
  11187. } else {
  11188. const lastId = yArray[numPages - 1];
  11189. if (lastId > currentPageNumber) {
  11190. return lastId - currentPageNumber + 1;
  11191. }
  11192. }
  11193. break;
  11194. }
  11195. break;
  11196. }
  11197. case ScrollMode.HORIZONTAL:
  11198. {
  11199. break;
  11200. }
  11201. case ScrollMode.PAGE:
  11202. case ScrollMode.VERTICAL:
  11203. {
  11204. if (this._spreadMode === SpreadMode.NONE) {
  11205. break;
  11206. }
  11207. const parity = this._spreadMode - 1;
  11208. if (previous && currentPageNumber % 2 !== parity) {
  11209. break;
  11210. } else if (!previous && currentPageNumber % 2 === parity) {
  11211. break;
  11212. }
  11213. const {
  11214. views
  11215. } = this._getVisiblePages(),
  11216. expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1;
  11217. for (const {
  11218. id,
  11219. percent,
  11220. widthPercent
  11221. } of views) {
  11222. if (id !== expectedId) {
  11223. continue;
  11224. }
  11225. if (percent > 0 && widthPercent === 100) {
  11226. return 2;
  11227. }
  11228. break;
  11229. }
  11230. break;
  11231. }
  11232. }
  11233. return 1;
  11234. }
  11235. nextPage() {
  11236. const currentPageNumber = this._currentPageNumber,
  11237. pagesCount = this.pagesCount;
  11238. if (currentPageNumber >= pagesCount) {
  11239. return false;
  11240. }
  11241. const advance = this._getPageAdvance(currentPageNumber, false) || 1;
  11242. this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount);
  11243. return true;
  11244. }
  11245. previousPage() {
  11246. const currentPageNumber = this._currentPageNumber;
  11247. if (currentPageNumber <= 1) {
  11248. return false;
  11249. }
  11250. const advance = this._getPageAdvance(currentPageNumber, true) || 1;
  11251. this.currentPageNumber = Math.max(currentPageNumber - advance, 1);
  11252. return true;
  11253. }
  11254. updateScale({
  11255. drawingDelay,
  11256. scaleFactor = null,
  11257. steps = null,
  11258. origin
  11259. }) {
  11260. if (steps === null && scaleFactor === null) {
  11261. throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");
  11262. }
  11263. if (!this.pdfDocument) {
  11264. return;
  11265. }
  11266. let newScale = this._currentScale;
  11267. if (scaleFactor > 0 && scaleFactor !== 1) {
  11268. newScale = Math.round(newScale * scaleFactor * 100) / 100;
  11269. } else if (steps) {
  11270. const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA;
  11271. const round = steps > 0 ? Math.ceil : Math.floor;
  11272. steps = Math.abs(steps);
  11273. do {
  11274. newScale = round((newScale * delta).toFixed(2) * 10) / 10;
  11275. } while (--steps > 0);
  11276. }
  11277. newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale));
  11278. this.#setScale(newScale, {
  11279. noScroll: false,
  11280. drawingDelay,
  11281. origin
  11282. });
  11283. }
  11284. increaseScale(options = {}) {
  11285. this.updateScale({
  11286. ...options,
  11287. steps: options.steps ?? 1
  11288. });
  11289. }
  11290. decreaseScale(options = {}) {
  11291. this.updateScale({
  11292. ...options,
  11293. steps: -(options.steps ?? 1)
  11294. });
  11295. }
  11296. #updateContainerHeightCss(height = this.container.clientHeight) {
  11297. if (height !== this.#previousContainerHeight) {
  11298. this.#previousContainerHeight = height;
  11299. docStyle.setProperty("--viewer-container-height", `${height}px`);
  11300. }
  11301. }
  11302. #resizeObserverCallback(entries) {
  11303. for (const entry of entries) {
  11304. if (entry.target === this.container) {
  11305. this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize));
  11306. this.#containerTopLeft = null;
  11307. break;
  11308. }
  11309. }
  11310. }
  11311. get containerTopLeft() {
  11312. return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft];
  11313. }
  11314. #cleanupSwitchAnnotationEditorMode() {
  11315. if (this.#onPageRenderedCallback) {
  11316. this.eventBus._off("pagerendered", this.#onPageRenderedCallback);
  11317. this.#onPageRenderedCallback = null;
  11318. }
  11319. if (this.#switchAnnotationEditorModeTimeoutId !== null) {
  11320. clearTimeout(this.#switchAnnotationEditorModeTimeoutId);
  11321. this.#switchAnnotationEditorModeTimeoutId = null;
  11322. }
  11323. }
  11324. get annotationEditorMode() {
  11325. return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE;
  11326. }
  11327. set annotationEditorMode({
  11328. mode,
  11329. editId = null,
  11330. isFromKeyboard = false
  11331. }) {
  11332. if (!this.#annotationEditorUIManager) {
  11333. throw new Error(`The AnnotationEditor is not enabled.`);
  11334. }
  11335. if (this.#annotationEditorMode === mode) {
  11336. return;
  11337. }
  11338. if (!isValidAnnotationEditorMode(mode)) {
  11339. throw new Error(`Invalid AnnotationEditor mode: ${mode}`);
  11340. }
  11341. if (!this.pdfDocument) {
  11342. return;
  11343. }
  11344. const {
  11345. eventBus
  11346. } = this;
  11347. const updater = () => {
  11348. this.#cleanupSwitchAnnotationEditorMode();
  11349. this.#annotationEditorMode = mode;
  11350. this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard);
  11351. eventBus.dispatch("annotationeditormodechanged", {
  11352. source: this,
  11353. mode
  11354. });
  11355. };
  11356. if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) {
  11357. const isEditing = mode !== AnnotationEditorType.NONE;
  11358. if (!isEditing) {
  11359. this.pdfDocument.annotationStorage.resetModifiedIds();
  11360. }
  11361. for (const pageView of this._pages) {
  11362. pageView.toggleEditingMode(isEditing);
  11363. }
  11364. const idsToRefresh = this.#switchToEditAnnotationMode();
  11365. if (isEditing && idsToRefresh) {
  11366. this.#cleanupSwitchAnnotationEditorMode();
  11367. this.#onPageRenderedCallback = ({
  11368. pageNumber
  11369. }) => {
  11370. idsToRefresh.delete(pageNumber);
  11371. if (idsToRefresh.size === 0) {
  11372. this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0);
  11373. }
  11374. };
  11375. const {
  11376. signal
  11377. } = this.#eventAbortController;
  11378. eventBus._on("pagerendered", this.#onPageRenderedCallback, {
  11379. signal
  11380. });
  11381. return;
  11382. }
  11383. }
  11384. updater();
  11385. }
  11386. set annotationEditorParams({
  11387. type,
  11388. value
  11389. }) {
  11390. if (!this.#annotationEditorUIManager) {
  11391. throw new Error(`The AnnotationEditor is not enabled.`);
  11392. }
  11393. this.#annotationEditorUIManager.updateParams(type, value);
  11394. }
  11395. refresh(noUpdate = false, updateArgs = Object.create(null)) {
  11396. if (!this.pdfDocument) {
  11397. return;
  11398. }
  11399. for (const pageView of this._pages) {
  11400. pageView.update(updateArgs);
  11401. }
  11402. if (this.#scaleTimeoutId !== null) {
  11403. clearTimeout(this.#scaleTimeoutId);
  11404. this.#scaleTimeoutId = null;
  11405. }
  11406. if (!noUpdate) {
  11407. this.update();
  11408. }
  11409. }
  11410. }
  11411. ;// CONCATENATED MODULE: ./web/secondary_toolbar.js
  11412. class SecondaryToolbar {
  11413. #opts;
  11414. constructor(options, eventBus) {
  11415. this.#opts = options;
  11416. const buttons = [{
  11417. element: options.presentationModeButton,
  11418. eventName: "presentationmode",
  11419. close: true
  11420. }, {
  11421. element: options.printButton,
  11422. eventName: "print",
  11423. close: true
  11424. }, {
  11425. element: options.downloadButton,
  11426. eventName: "download",
  11427. close: true
  11428. }, {
  11429. element: options.viewBookmarkButton,
  11430. eventName: null,
  11431. close: true
  11432. }, {
  11433. element: options.firstPageButton,
  11434. eventName: "firstpage",
  11435. close: true
  11436. }, {
  11437. element: options.lastPageButton,
  11438. eventName: "lastpage",
  11439. close: true
  11440. }, {
  11441. element: options.pageRotateCwButton,
  11442. eventName: "rotatecw",
  11443. close: false
  11444. }, {
  11445. element: options.pageRotateCcwButton,
  11446. eventName: "rotateccw",
  11447. close: false
  11448. }, {
  11449. element: options.cursorSelectToolButton,
  11450. eventName: "switchcursortool",
  11451. eventDetails: {
  11452. tool: CursorTool.SELECT
  11453. },
  11454. close: true
  11455. }, {
  11456. element: options.cursorHandToolButton,
  11457. eventName: "switchcursortool",
  11458. eventDetails: {
  11459. tool: CursorTool.HAND
  11460. },
  11461. close: true
  11462. }, {
  11463. element: options.scrollPageButton,
  11464. eventName: "switchscrollmode",
  11465. eventDetails: {
  11466. mode: ScrollMode.PAGE
  11467. },
  11468. close: true
  11469. }, {
  11470. element: options.scrollVerticalButton,
  11471. eventName: "switchscrollmode",
  11472. eventDetails: {
  11473. mode: ScrollMode.VERTICAL
  11474. },
  11475. close: true
  11476. }, {
  11477. element: options.scrollHorizontalButton,
  11478. eventName: "switchscrollmode",
  11479. eventDetails: {
  11480. mode: ScrollMode.HORIZONTAL
  11481. },
  11482. close: true
  11483. }, {
  11484. element: options.scrollWrappedButton,
  11485. eventName: "switchscrollmode",
  11486. eventDetails: {
  11487. mode: ScrollMode.WRAPPED
  11488. },
  11489. close: true
  11490. }, {
  11491. element: options.spreadNoneButton,
  11492. eventName: "switchspreadmode",
  11493. eventDetails: {
  11494. mode: SpreadMode.NONE
  11495. },
  11496. close: true
  11497. }, {
  11498. element: options.spreadOddButton,
  11499. eventName: "switchspreadmode",
  11500. eventDetails: {
  11501. mode: SpreadMode.ODD
  11502. },
  11503. close: true
  11504. }, {
  11505. element: options.spreadEvenButton,
  11506. eventName: "switchspreadmode",
  11507. eventDetails: {
  11508. mode: SpreadMode.EVEN
  11509. },
  11510. close: true
  11511. }, {
  11512. element: options.documentPropertiesButton,
  11513. eventName: "documentproperties",
  11514. close: true
  11515. }];
  11516. buttons.push({
  11517. element: options.openFileButton,
  11518. eventName: "openfile",
  11519. close: true
  11520. });
  11521. this.eventBus = eventBus;
  11522. this.opened = false;
  11523. this.#bindListeners(buttons);
  11524. this.reset();
  11525. }
  11526. get isOpen() {
  11527. return this.opened;
  11528. }
  11529. setPageNumber(pageNumber) {
  11530. this.pageNumber = pageNumber;
  11531. this.#updateUIState();
  11532. }
  11533. setPagesCount(pagesCount) {
  11534. this.pagesCount = pagesCount;
  11535. this.#updateUIState();
  11536. }
  11537. reset() {
  11538. this.pageNumber = 0;
  11539. this.pagesCount = 0;
  11540. this.#updateUIState();
  11541. this.eventBus.dispatch("switchcursortool", {
  11542. source: this,
  11543. reset: true
  11544. });
  11545. this.#scrollModeChanged({
  11546. mode: ScrollMode.VERTICAL
  11547. });
  11548. this.#spreadModeChanged({
  11549. mode: SpreadMode.NONE
  11550. });
  11551. }
  11552. #updateUIState() {
  11553. const {
  11554. firstPageButton,
  11555. lastPageButton,
  11556. pageRotateCwButton,
  11557. pageRotateCcwButton
  11558. } = this.#opts;
  11559. firstPageButton.disabled = this.pageNumber <= 1;
  11560. lastPageButton.disabled = this.pageNumber >= this.pagesCount;
  11561. pageRotateCwButton.disabled = this.pagesCount === 0;
  11562. pageRotateCcwButton.disabled = this.pagesCount === 0;
  11563. }
  11564. #bindListeners(buttons) {
  11565. const {
  11566. eventBus
  11567. } = this;
  11568. const {
  11569. toggleButton
  11570. } = this.#opts;
  11571. toggleButton.addEventListener("click", this.toggle.bind(this));
  11572. for (const {
  11573. element,
  11574. eventName,
  11575. close,
  11576. eventDetails
  11577. } of buttons) {
  11578. element.addEventListener("click", evt => {
  11579. if (eventName !== null) {
  11580. eventBus.dispatch(eventName, {
  11581. source: this,
  11582. ...eventDetails
  11583. });
  11584. }
  11585. if (close) {
  11586. this.close();
  11587. }
  11588. eventBus.dispatch("reporttelemetry", {
  11589. source: this,
  11590. details: {
  11591. type: "buttons",
  11592. data: {
  11593. id: element.id
  11594. }
  11595. }
  11596. });
  11597. });
  11598. }
  11599. eventBus._on("cursortoolchanged", this.#cursorToolChanged.bind(this));
  11600. eventBus._on("scrollmodechanged", this.#scrollModeChanged.bind(this));
  11601. eventBus._on("spreadmodechanged", this.#spreadModeChanged.bind(this));
  11602. }
  11603. #cursorToolChanged({
  11604. tool
  11605. }) {
  11606. const {
  11607. cursorSelectToolButton,
  11608. cursorHandToolButton
  11609. } = this.#opts;
  11610. toggleCheckedBtn(cursorSelectToolButton, tool === CursorTool.SELECT);
  11611. toggleCheckedBtn(cursorHandToolButton, tool === CursorTool.HAND);
  11612. }
  11613. #scrollModeChanged({
  11614. mode
  11615. }) {
  11616. const {
  11617. scrollPageButton,
  11618. scrollVerticalButton,
  11619. scrollHorizontalButton,
  11620. scrollWrappedButton,
  11621. spreadNoneButton,
  11622. spreadOddButton,
  11623. spreadEvenButton
  11624. } = this.#opts;
  11625. toggleCheckedBtn(scrollPageButton, mode === ScrollMode.PAGE);
  11626. toggleCheckedBtn(scrollVerticalButton, mode === ScrollMode.VERTICAL);
  11627. toggleCheckedBtn(scrollHorizontalButton, mode === ScrollMode.HORIZONTAL);
  11628. toggleCheckedBtn(scrollWrappedButton, mode === ScrollMode.WRAPPED);
  11629. const forceScrollModePage = this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE;
  11630. scrollPageButton.disabled = forceScrollModePage;
  11631. scrollVerticalButton.disabled = forceScrollModePage;
  11632. scrollHorizontalButton.disabled = forceScrollModePage;
  11633. scrollWrappedButton.disabled = forceScrollModePage;
  11634. const isHorizontal = mode === ScrollMode.HORIZONTAL;
  11635. spreadNoneButton.disabled = isHorizontal;
  11636. spreadOddButton.disabled = isHorizontal;
  11637. spreadEvenButton.disabled = isHorizontal;
  11638. }
  11639. #spreadModeChanged({
  11640. mode
  11641. }) {
  11642. const {
  11643. spreadNoneButton,
  11644. spreadOddButton,
  11645. spreadEvenButton
  11646. } = this.#opts;
  11647. toggleCheckedBtn(spreadNoneButton, mode === SpreadMode.NONE);
  11648. toggleCheckedBtn(spreadOddButton, mode === SpreadMode.ODD);
  11649. toggleCheckedBtn(spreadEvenButton, mode === SpreadMode.EVEN);
  11650. }
  11651. open() {
  11652. if (this.opened) {
  11653. return;
  11654. }
  11655. this.opened = true;
  11656. const {
  11657. toggleButton,
  11658. toolbar
  11659. } = this.#opts;
  11660. toggleExpandedBtn(toggleButton, true, toolbar);
  11661. }
  11662. close() {
  11663. if (!this.opened) {
  11664. return;
  11665. }
  11666. this.opened = false;
  11667. const {
  11668. toggleButton,
  11669. toolbar
  11670. } = this.#opts;
  11671. toggleExpandedBtn(toggleButton, false, toolbar);
  11672. }
  11673. toggle() {
  11674. if (this.opened) {
  11675. this.close();
  11676. } else {
  11677. this.open();
  11678. }
  11679. }
  11680. }
  11681. ;// CONCATENATED MODULE: ./web/toolbar.js
  11682. class Toolbar {
  11683. #opts;
  11684. constructor(options, eventBus, toolbarDensity = 0) {
  11685. this.#opts = options;
  11686. this.eventBus = eventBus;
  11687. const buttons = [{
  11688. element: options.previous,
  11689. eventName: "previouspage"
  11690. }, {
  11691. element: options.next,
  11692. eventName: "nextpage"
  11693. }, {
  11694. element: options.zoomIn,
  11695. eventName: "zoomin"
  11696. }, {
  11697. element: options.zoomOut,
  11698. eventName: "zoomout"
  11699. }, {
  11700. element: options.print,
  11701. eventName: "print"
  11702. }, {
  11703. element: options.download,
  11704. eventName: "download"
  11705. }, {
  11706. element: options.editorFreeTextButton,
  11707. eventName: "switchannotationeditormode",
  11708. eventDetails: {
  11709. get mode() {
  11710. const {
  11711. classList
  11712. } = options.editorFreeTextButton;
  11713. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.FREETEXT;
  11714. }
  11715. }
  11716. }, {
  11717. element: options.editorHighlightButton,
  11718. eventName: "switchannotationeditormode",
  11719. eventDetails: {
  11720. get mode() {
  11721. const {
  11722. classList
  11723. } = options.editorHighlightButton;
  11724. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.HIGHLIGHT;
  11725. }
  11726. }
  11727. }, {
  11728. element: options.editorInkButton,
  11729. eventName: "switchannotationeditormode",
  11730. eventDetails: {
  11731. get mode() {
  11732. const {
  11733. classList
  11734. } = options.editorInkButton;
  11735. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.INK;
  11736. }
  11737. }
  11738. }, {
  11739. element: options.editorStampButton,
  11740. eventName: "switchannotationeditormode",
  11741. eventDetails: {
  11742. get mode() {
  11743. const {
  11744. classList
  11745. } = options.editorStampButton;
  11746. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.STAMP;
  11747. }
  11748. }
  11749. }];
  11750. this.#bindListeners(buttons);
  11751. if (options.editorHighlightColorPicker) {
  11752. eventBus._on("annotationeditoruimanager", ({
  11753. uiManager
  11754. }) => {
  11755. this.#setAnnotationEditorUIManager(uiManager, options.editorHighlightColorPicker);
  11756. }, {
  11757. once: true
  11758. });
  11759. }
  11760. eventBus._on("showannotationeditorui", ({
  11761. mode
  11762. }) => {
  11763. switch (mode) {
  11764. case AnnotationEditorType.HIGHLIGHT:
  11765. options.editorHighlightButton.click();
  11766. break;
  11767. }
  11768. });
  11769. eventBus._on("toolbardensity", this.#updateToolbarDensity.bind(this));
  11770. this.#updateToolbarDensity({
  11771. value: toolbarDensity
  11772. });
  11773. this.reset();
  11774. }
  11775. #updateToolbarDensity() {}
  11776. #setAnnotationEditorUIManager(uiManager, parentContainer) {
  11777. const colorPicker = new ColorPicker({
  11778. uiManager
  11779. });
  11780. uiManager.setMainHighlightColorPicker(colorPicker);
  11781. parentContainer.append(colorPicker.renderMainDropdown());
  11782. }
  11783. setPageNumber(pageNumber, pageLabel) {
  11784. this.pageNumber = pageNumber;
  11785. this.pageLabel = pageLabel;
  11786. this.#updateUIState(false);
  11787. }
  11788. setPagesCount(pagesCount, hasPageLabels) {
  11789. this.pagesCount = pagesCount;
  11790. this.hasPageLabels = hasPageLabels;
  11791. this.#updateUIState(true);
  11792. }
  11793. setPageScale(pageScaleValue, pageScale) {
  11794. this.pageScaleValue = (pageScaleValue || pageScale).toString();
  11795. this.pageScale = pageScale;
  11796. this.#updateUIState(false);
  11797. }
  11798. reset() {
  11799. this.pageNumber = 0;
  11800. this.pageLabel = null;
  11801. this.hasPageLabels = false;
  11802. this.pagesCount = 0;
  11803. this.pageScaleValue = DEFAULT_SCALE_VALUE;
  11804. this.pageScale = DEFAULT_SCALE;
  11805. this.#updateUIState(true);
  11806. this.updateLoadingIndicatorState();
  11807. this.#editorModeChanged({
  11808. mode: AnnotationEditorType.DISABLE
  11809. });
  11810. }
  11811. #bindListeners(buttons) {
  11812. const {
  11813. eventBus
  11814. } = this;
  11815. const {
  11816. pageNumber,
  11817. scaleSelect
  11818. } = this.#opts;
  11819. const self = this;
  11820. for (const {
  11821. element,
  11822. eventName,
  11823. eventDetails
  11824. } of buttons) {
  11825. element.addEventListener("click", evt => {
  11826. if (eventName !== null) {
  11827. eventBus.dispatch(eventName, {
  11828. source: this,
  11829. ...eventDetails,
  11830. isFromKeyboard: evt.detail === 0
  11831. });
  11832. }
  11833. });
  11834. }
  11835. pageNumber.addEventListener("click", function () {
  11836. this.select();
  11837. });
  11838. pageNumber.addEventListener("change", function () {
  11839. eventBus.dispatch("pagenumberchanged", {
  11840. source: self,
  11841. value: this.value
  11842. });
  11843. });
  11844. scaleSelect.addEventListener("change", function () {
  11845. if (this.value === "custom") {
  11846. return;
  11847. }
  11848. eventBus.dispatch("scalechanged", {
  11849. source: self,
  11850. value: this.value
  11851. });
  11852. });
  11853. scaleSelect.addEventListener("click", function ({
  11854. target
  11855. }) {
  11856. if (this.value === self.pageScaleValue && target.tagName.toUpperCase() === "OPTION") {
  11857. this.blur();
  11858. }
  11859. });
  11860. scaleSelect.oncontextmenu = noContextMenu;
  11861. eventBus._on("annotationeditormodechanged", this.#editorModeChanged.bind(this));
  11862. }
  11863. #editorModeChanged({
  11864. mode
  11865. }) {
  11866. const {
  11867. editorFreeTextButton,
  11868. editorFreeTextParamsToolbar,
  11869. editorHighlightButton,
  11870. editorHighlightParamsToolbar,
  11871. editorInkButton,
  11872. editorInkParamsToolbar,
  11873. editorStampButton,
  11874. editorStampParamsToolbar
  11875. } = this.#opts;
  11876. toggleCheckedBtn(editorFreeTextButton, mode === AnnotationEditorType.FREETEXT, editorFreeTextParamsToolbar);
  11877. toggleCheckedBtn(editorHighlightButton, mode === AnnotationEditorType.HIGHLIGHT, editorHighlightParamsToolbar);
  11878. toggleCheckedBtn(editorInkButton, mode === AnnotationEditorType.INK, editorInkParamsToolbar);
  11879. toggleCheckedBtn(editorStampButton, mode === AnnotationEditorType.STAMP, editorStampParamsToolbar);
  11880. const isDisable = mode === AnnotationEditorType.DISABLE;
  11881. editorFreeTextButton.disabled = isDisable;
  11882. editorHighlightButton.disabled = isDisable;
  11883. editorInkButton.disabled = isDisable;
  11884. editorStampButton.disabled = isDisable;
  11885. }
  11886. #updateUIState(resetNumPages = false) {
  11887. const {
  11888. pageNumber,
  11889. pagesCount,
  11890. pageScaleValue,
  11891. pageScale
  11892. } = this;
  11893. const opts = this.#opts;
  11894. if (resetNumPages) {
  11895. if (this.hasPageLabels) {
  11896. opts.pageNumber.type = "text";
  11897. opts.numPages.setAttribute("data-l10n-id", "pdfjs-page-of-pages");
  11898. } else {
  11899. opts.pageNumber.type = "number";
  11900. opts.numPages.setAttribute("data-l10n-id", "pdfjs-of-pages");
  11901. opts.numPages.setAttribute("data-l10n-args", JSON.stringify({
  11902. pagesCount
  11903. }));
  11904. }
  11905. opts.pageNumber.max = pagesCount;
  11906. }
  11907. if (this.hasPageLabels) {
  11908. opts.pageNumber.value = this.pageLabel;
  11909. opts.numPages.setAttribute("data-l10n-args", JSON.stringify({
  11910. pageNumber,
  11911. pagesCount
  11912. }));
  11913. } else {
  11914. opts.pageNumber.value = pageNumber;
  11915. }
  11916. opts.previous.disabled = pageNumber <= 1;
  11917. opts.next.disabled = pageNumber >= pagesCount;
  11918. opts.zoomOut.disabled = pageScale <= MIN_SCALE;
  11919. opts.zoomIn.disabled = pageScale >= MAX_SCALE;
  11920. let predefinedValueFound = false;
  11921. for (const option of opts.scaleSelect.options) {
  11922. if (option.value !== pageScaleValue) {
  11923. option.selected = false;
  11924. continue;
  11925. }
  11926. option.selected = true;
  11927. predefinedValueFound = true;
  11928. }
  11929. if (!predefinedValueFound) {
  11930. opts.customScaleOption.selected = true;
  11931. opts.customScaleOption.setAttribute("data-l10n-args", JSON.stringify({
  11932. scale: Math.round(pageScale * 10000) / 100
  11933. }));
  11934. }
  11935. }
  11936. updateLoadingIndicatorState(loading = false) {
  11937. const {
  11938. pageNumber
  11939. } = this.#opts;
  11940. pageNumber.classList.toggle("loading", loading);
  11941. }
  11942. }
  11943. ;// CONCATENATED MODULE: ./web/view_history.js
  11944. const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;
  11945. class ViewHistory {
  11946. constructor(fingerprint, cacheSize = DEFAULT_VIEW_HISTORY_CACHE_SIZE) {
  11947. this.fingerprint = fingerprint;
  11948. this.cacheSize = cacheSize;
  11949. this._initializedPromise = this._readFromStorage().then(databaseStr => {
  11950. const database = JSON.parse(databaseStr || "{}");
  11951. let index = -1;
  11952. if (!Array.isArray(database.files)) {
  11953. database.files = [];
  11954. } else {
  11955. while (database.files.length >= this.cacheSize) {
  11956. database.files.shift();
  11957. }
  11958. for (let i = 0, ii = database.files.length; i < ii; i++) {
  11959. const branch = database.files[i];
  11960. if (branch.fingerprint === this.fingerprint) {
  11961. index = i;
  11962. break;
  11963. }
  11964. }
  11965. }
  11966. if (index === -1) {
  11967. index = database.files.push({
  11968. fingerprint: this.fingerprint
  11969. }) - 1;
  11970. }
  11971. this.file = database.files[index];
  11972. this.database = database;
  11973. });
  11974. }
  11975. async _writeToStorage() {
  11976. const databaseStr = JSON.stringify(this.database);
  11977. localStorage.setItem("pdfjs.history", databaseStr);
  11978. }
  11979. async _readFromStorage() {
  11980. return localStorage.getItem("pdfjs.history");
  11981. }
  11982. async set(name, val) {
  11983. await this._initializedPromise;
  11984. this.file[name] = val;
  11985. return this._writeToStorage();
  11986. }
  11987. async setMultiple(properties) {
  11988. await this._initializedPromise;
  11989. for (const name in properties) {
  11990. this.file[name] = properties[name];
  11991. }
  11992. return this._writeToStorage();
  11993. }
  11994. async get(name, defaultValue) {
  11995. await this._initializedPromise;
  11996. const val = this.file[name];
  11997. return val !== undefined ? val : defaultValue;
  11998. }
  11999. async getMultiple(properties) {
  12000. await this._initializedPromise;
  12001. const values = Object.create(null);
  12002. for (const name in properties) {
  12003. const val = this.file[name];
  12004. values[name] = val !== undefined ? val : properties[name];
  12005. }
  12006. return values;
  12007. }
  12008. }
  12009. ;// CONCATENATED MODULE: ./web/app.js
  12010. const FORCE_PAGES_LOADED_TIMEOUT = 10000;
  12011. const ViewOnLoad = {
  12012. UNKNOWN: -1,
  12013. PREVIOUS: 0,
  12014. INITIAL: 1
  12015. };
  12016. const PDFViewerApplication = {
  12017. initialBookmark: document.location.hash.substring(1),
  12018. _initializedCapability: {
  12019. ...Promise.withResolvers(),
  12020. settled: false
  12021. },
  12022. appConfig: null,
  12023. pdfDocument: null,
  12024. pdfLoadingTask: null,
  12025. printService: null,
  12026. pdfViewer: null,
  12027. pdfThumbnailViewer: null,
  12028. pdfRenderingQueue: null,
  12029. pdfPresentationMode: null,
  12030. pdfDocumentProperties: null,
  12031. pdfLinkService: null,
  12032. pdfHistory: null,
  12033. pdfSidebar: null,
  12034. pdfOutlineViewer: null,
  12035. pdfAttachmentViewer: null,
  12036. pdfLayerViewer: null,
  12037. pdfCursorTools: null,
  12038. pdfScriptingManager: null,
  12039. store: null,
  12040. downloadManager: null,
  12041. overlayManager: null,
  12042. preferences: new Preferences(),
  12043. toolbar: null,
  12044. secondaryToolbar: null,
  12045. eventBus: null,
  12046. l10n: null,
  12047. annotationEditorParams: null,
  12048. isInitialViewSet: false,
  12049. isViewerEmbedded: window.parent !== window,
  12050. url: "",
  12051. baseUrl: "",
  12052. mlManager: null,
  12053. _downloadUrl: "",
  12054. _eventBusAbortController: null,
  12055. _windowAbortController: null,
  12056. _globalAbortController: new AbortController(),
  12057. documentInfo: null,
  12058. metadata: null,
  12059. _contentDispositionFilename: null,
  12060. _contentLength: null,
  12061. _saveInProgress: false,
  12062. _wheelUnusedTicks: 0,
  12063. _wheelUnusedFactor: 1,
  12064. _touchUnusedTicks: 0,
  12065. _touchUnusedFactor: 1,
  12066. _PDFBug: null,
  12067. _hasAnnotationEditors: false,
  12068. _title: document.title,
  12069. _printAnnotationStoragePromise: null,
  12070. _touchInfo: null,
  12071. _isCtrlKeyDown: false,
  12072. _caretBrowsing: null,
  12073. _isScrolling: false,
  12074. async initialize(appConfig) {
  12075. this.appConfig = appConfig;
  12076. try {
  12077. await this.preferences.initializedPromise;
  12078. } catch (ex) {
  12079. console.error(`initialize: "${ex.message}".`);
  12080. }
  12081. if (AppOptions.get("pdfBugEnabled")) {
  12082. await this._parseHashParams();
  12083. }
  12084. let mode;
  12085. switch (AppOptions.get("viewerCssTheme")) {
  12086. case 1:
  12087. mode = "is-light";
  12088. break;
  12089. case 2:
  12090. mode = "is-dark";
  12091. break;
  12092. }
  12093. if (mode) {
  12094. document.documentElement.classList.add(mode);
  12095. }
  12096. this.l10n = await this.externalServices.createL10n();
  12097. document.getElementsByTagName("html")[0].dir = this.l10n.getDirection();
  12098. this.l10n.translate(appConfig.appContainer || document.documentElement);
  12099. if (this.isViewerEmbedded && AppOptions.get("externalLinkTarget") === LinkTarget.NONE) {
  12100. AppOptions.set("externalLinkTarget", LinkTarget.TOP);
  12101. }
  12102. await this._initializeViewerComponents();
  12103. this.bindEvents();
  12104. this.bindWindowEvents();
  12105. this._initializedCapability.settled = true;
  12106. this._initializedCapability.resolve();
  12107. },
  12108. async _parseHashParams() {
  12109. const hash = document.location.hash.substring(1);
  12110. if (!hash) {
  12111. return;
  12112. }
  12113. const {
  12114. mainContainer,
  12115. viewerContainer
  12116. } = this.appConfig,
  12117. params = parseQueryString(hash);
  12118. const loadPDFBug = async () => {
  12119. if (this._PDFBug) {
  12120. return;
  12121. }
  12122. const {
  12123. PDFBug
  12124. } = await import( /*webpackIgnore: true*/AppOptions.get("debuggerSrc"));
  12125. this._PDFBug = PDFBug;
  12126. };
  12127. if (params.get("disableworker") === "true") {
  12128. try {
  12129. GlobalWorkerOptions.workerSrc ||= AppOptions.get("workerSrc");
  12130. await import( /*webpackIgnore: true*/PDFWorker.workerSrc);
  12131. } catch (ex) {
  12132. console.error(`_parseHashParams: "${ex.message}".`);
  12133. }
  12134. }
  12135. if (params.has("disablerange")) {
  12136. AppOptions.set("disableRange", params.get("disablerange") === "true");
  12137. }
  12138. if (params.has("disablestream")) {
  12139. AppOptions.set("disableStream", params.get("disablestream") === "true");
  12140. }
  12141. if (params.has("disableautofetch")) {
  12142. AppOptions.set("disableAutoFetch", params.get("disableautofetch") === "true");
  12143. }
  12144. if (params.has("disablefontface")) {
  12145. AppOptions.set("disableFontFace", params.get("disablefontface") === "true");
  12146. }
  12147. if (params.has("disablehistory")) {
  12148. AppOptions.set("disableHistory", params.get("disablehistory") === "true");
  12149. }
  12150. if (params.has("verbosity")) {
  12151. AppOptions.set("verbosity", params.get("verbosity") | 0);
  12152. }
  12153. if (params.has("textlayer")) {
  12154. switch (params.get("textlayer")) {
  12155. case "off":
  12156. AppOptions.set("textLayerMode", TextLayerMode.DISABLE);
  12157. break;
  12158. case "visible":
  12159. case "shadow":
  12160. case "hover":
  12161. viewerContainer.classList.add(`textLayer-${params.get("textlayer")}`);
  12162. try {
  12163. await loadPDFBug();
  12164. this._PDFBug.loadCSS();
  12165. } catch (ex) {
  12166. console.error(`_parseHashParams: "${ex.message}".`);
  12167. }
  12168. break;
  12169. }
  12170. }
  12171. if (params.has("pdfbug")) {
  12172. AppOptions.setAll({
  12173. pdfBug: true,
  12174. fontExtraProperties: true
  12175. });
  12176. const enabled = params.get("pdfbug").split(",");
  12177. try {
  12178. await loadPDFBug();
  12179. this._PDFBug.init(mainContainer, enabled);
  12180. } catch (ex) {
  12181. console.error(`_parseHashParams: "${ex.message}".`);
  12182. }
  12183. }
  12184. if (params.has("locale")) {
  12185. AppOptions.set("localeProperties", {
  12186. lang: params.get("locale")
  12187. });
  12188. }
  12189. },
  12190. async _initializeViewerComponents() {
  12191. const {
  12192. appConfig,
  12193. externalServices,
  12194. l10n
  12195. } = this;
  12196. let eventBus;
  12197. eventBus = new EventBus();
  12198. this.eventBus = eventBus;
  12199. this.overlayManager = new OverlayManager();
  12200. const pdfRenderingQueue = new PDFRenderingQueue();
  12201. pdfRenderingQueue.onIdle = this._cleanup.bind(this);
  12202. this.pdfRenderingQueue = pdfRenderingQueue;
  12203. const pdfLinkService = new PDFLinkService({
  12204. eventBus,
  12205. externalLinkTarget: AppOptions.get("externalLinkTarget"),
  12206. externalLinkRel: AppOptions.get("externalLinkRel"),
  12207. ignoreDestinationZoom: AppOptions.get("ignoreDestinationZoom")
  12208. });
  12209. this.pdfLinkService = pdfLinkService;
  12210. const downloadManager = this.downloadManager = new DownloadManager();
  12211. const findController = new PDFFindController({
  12212. linkService: pdfLinkService,
  12213. eventBus,
  12214. updateMatchesCountOnProgress: true
  12215. });
  12216. this.findController = findController;
  12217. const pdfScriptingManager = new PDFScriptingManager({
  12218. eventBus,
  12219. externalServices,
  12220. docProperties: this._scriptingDocProperties.bind(this)
  12221. });
  12222. this.pdfScriptingManager = pdfScriptingManager;
  12223. const container = appConfig.mainContainer,
  12224. viewer = appConfig.viewerContainer;
  12225. const annotationEditorMode = AppOptions.get("annotationEditorMode");
  12226. const pageColors = AppOptions.get("forcePageColors") || window.matchMedia("(forced-colors: active)").matches ? {
  12227. background: AppOptions.get("pageColorsBackground"),
  12228. foreground: AppOptions.get("pageColorsForeground")
  12229. } : null;
  12230. const altTextManager = appConfig.altTextDialog ? new AltTextManager(appConfig.altTextDialog, container, this.overlayManager, eventBus) : null;
  12231. const enableHWA = AppOptions.get("enableHWA");
  12232. const pdfViewer = new PDFViewer({
  12233. container,
  12234. viewer,
  12235. eventBus,
  12236. renderingQueue: pdfRenderingQueue,
  12237. linkService: pdfLinkService,
  12238. downloadManager,
  12239. altTextManager,
  12240. findController,
  12241. scriptingManager: AppOptions.get("enableScripting") && pdfScriptingManager,
  12242. l10n,
  12243. textLayerMode: AppOptions.get("textLayerMode"),
  12244. annotationMode: AppOptions.get("annotationMode"),
  12245. annotationEditorMode,
  12246. annotationEditorHighlightColors: AppOptions.get("highlightEditorColors"),
  12247. enableHighlightFloatingButton: AppOptions.get("enableHighlightFloatingButton"),
  12248. enableUpdatedAddImage: AppOptions.get("enableUpdatedAddImage"),
  12249. imageResourcesPath: AppOptions.get("imageResourcesPath"),
  12250. enablePrintAutoRotate: AppOptions.get("enablePrintAutoRotate"),
  12251. maxCanvasPixels: AppOptions.get("maxCanvasPixels"),
  12252. enablePermissions: AppOptions.get("enablePermissions"),
  12253. pageColors,
  12254. mlManager: this.mlManager,
  12255. abortSignal: this._globalAbortController.signal,
  12256. enableHWA
  12257. });
  12258. this.pdfViewer = pdfViewer;
  12259. pdfRenderingQueue.setViewer(pdfViewer);
  12260. pdfLinkService.setViewer(pdfViewer);
  12261. pdfScriptingManager.setViewer(pdfViewer);
  12262. if (appConfig.sidebar?.thumbnailView) {
  12263. this.pdfThumbnailViewer = new PDFThumbnailViewer({
  12264. container: appConfig.sidebar.thumbnailView,
  12265. eventBus,
  12266. renderingQueue: pdfRenderingQueue,
  12267. linkService: pdfLinkService,
  12268. pageColors,
  12269. abortSignal: this._globalAbortController.signal,
  12270. enableHWA
  12271. });
  12272. pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
  12273. }
  12274. if (!this.isViewerEmbedded && !AppOptions.get("disableHistory")) {
  12275. this.pdfHistory = new PDFHistory({
  12276. linkService: pdfLinkService,
  12277. eventBus
  12278. });
  12279. pdfLinkService.setHistory(this.pdfHistory);
  12280. }
  12281. if (!this.supportsIntegratedFind && appConfig.findBar) {
  12282. this.findBar = new PDFFindBar(appConfig.findBar, eventBus);
  12283. }
  12284. if (appConfig.annotationEditorParams) {
  12285. if (annotationEditorMode !== AnnotationEditorType.DISABLE) {
  12286. const editorHighlightButton = appConfig.toolbar?.editorHighlightButton;
  12287. if (editorHighlightButton && AppOptions.get("enableHighlightEditor")) {
  12288. editorHighlightButton.hidden = false;
  12289. }
  12290. this.annotationEditorParams = new AnnotationEditorParams(appConfig.annotationEditorParams, eventBus);
  12291. } else {
  12292. for (const id of ["editorModeButtons", "editorModeSeparator"]) {
  12293. document.getElementById(id)?.classList.add("hidden");
  12294. }
  12295. }
  12296. }
  12297. if (appConfig.documentProperties) {
  12298. this.pdfDocumentProperties = new PDFDocumentProperties(appConfig.documentProperties, this.overlayManager, eventBus, l10n, () => this._docFilename);
  12299. }
  12300. if (appConfig.secondaryToolbar?.cursorHandToolButton) {
  12301. this.pdfCursorTools = new PDFCursorTools({
  12302. container,
  12303. eventBus,
  12304. cursorToolOnLoad: AppOptions.get("cursorToolOnLoad")
  12305. });
  12306. }
  12307. if (appConfig.toolbar) {
  12308. this.toolbar = new Toolbar(appConfig.toolbar, eventBus, AppOptions.get("toolbarDensity"));
  12309. }
  12310. if (appConfig.secondaryToolbar) {
  12311. this.secondaryToolbar = new SecondaryToolbar(appConfig.secondaryToolbar, eventBus);
  12312. }
  12313. if (this.supportsFullscreen && appConfig.secondaryToolbar?.presentationModeButton) {
  12314. this.pdfPresentationMode = new PDFPresentationMode({
  12315. container,
  12316. pdfViewer,
  12317. eventBus
  12318. });
  12319. }
  12320. if (appConfig.passwordOverlay) {
  12321. this.passwordPrompt = new PasswordPrompt(appConfig.passwordOverlay, this.overlayManager, this.isViewerEmbedded);
  12322. }
  12323. if (appConfig.sidebar?.outlineView) {
  12324. this.pdfOutlineViewer = new PDFOutlineViewer({
  12325. container: appConfig.sidebar.outlineView,
  12326. eventBus,
  12327. l10n,
  12328. linkService: pdfLinkService,
  12329. downloadManager
  12330. });
  12331. }
  12332. if (appConfig.sidebar?.attachmentsView) {
  12333. this.pdfAttachmentViewer = new PDFAttachmentViewer({
  12334. container: appConfig.sidebar.attachmentsView,
  12335. eventBus,
  12336. l10n,
  12337. downloadManager
  12338. });
  12339. }
  12340. if (appConfig.sidebar?.layersView) {
  12341. this.pdfLayerViewer = new PDFLayerViewer({
  12342. container: appConfig.sidebar.layersView,
  12343. eventBus,
  12344. l10n
  12345. });
  12346. }
  12347. if (appConfig.sidebar) {
  12348. this.pdfSidebar = new PDFSidebar({
  12349. elements: appConfig.sidebar,
  12350. eventBus,
  12351. l10n
  12352. });
  12353. this.pdfSidebar.onToggled = this.forceRendering.bind(this);
  12354. this.pdfSidebar.onUpdateThumbnails = () => {
  12355. for (const pageView of pdfViewer.getCachedPageViews()) {
  12356. if (pageView.renderingState === RenderingStates.FINISHED) {
  12357. this.pdfThumbnailViewer.getThumbnail(pageView.id - 1)?.setImage(pageView);
  12358. }
  12359. }
  12360. this.pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber);
  12361. };
  12362. }
  12363. },
  12364. async run(config) {
  12365. await this.initialize(config);
  12366. const {
  12367. appConfig,
  12368. eventBus
  12369. } = this;
  12370. let file;
  12371. const queryString = document.location.search.substring(1);
  12372. const params = parseQueryString(queryString);
  12373. file = params.get("file") ?? AppOptions.get("defaultUrl");
  12374. validateFileURL(file);
  12375. const fileInput = this._openFileInput = document.createElement("input");
  12376. fileInput.id = "fileInput";
  12377. fileInput.hidden = true;
  12378. fileInput.type = "file";
  12379. fileInput.value = null;
  12380. document.body.append(fileInput);
  12381. fileInput.addEventListener("change", function (evt) {
  12382. const {
  12383. files
  12384. } = evt.target;
  12385. if (!files || files.length === 0) {
  12386. return;
  12387. }
  12388. eventBus.dispatch("fileinputchange", {
  12389. source: this,
  12390. fileInput: evt.target
  12391. });
  12392. });
  12393. appConfig.mainContainer.addEventListener("dragover", function (evt) {
  12394. for (const item of evt.dataTransfer.items) {
  12395. if (item.type === "application/pdf") {
  12396. evt.dataTransfer.dropEffect = evt.dataTransfer.effectAllowed === "copy" ? "copy" : "move";
  12397. evt.preventDefault();
  12398. evt.stopPropagation();
  12399. return;
  12400. }
  12401. }
  12402. });
  12403. appConfig.mainContainer.addEventListener("drop", function (evt) {
  12404. if (evt.dataTransfer.files?.[0].type !== "application/pdf") {
  12405. return;
  12406. }
  12407. evt.preventDefault();
  12408. evt.stopPropagation();
  12409. eventBus.dispatch("fileinputchange", {
  12410. source: this,
  12411. fileInput: evt.dataTransfer
  12412. });
  12413. });
  12414. if (!AppOptions.get("supportsDocumentFonts")) {
  12415. AppOptions.set("disableFontFace", true);
  12416. this.l10n.get("pdfjs-web-fonts-disabled").then(msg => {
  12417. console.warn(msg);
  12418. });
  12419. }
  12420. if (!this.supportsPrinting) {
  12421. appConfig.toolbar?.print?.classList.add("hidden");
  12422. appConfig.secondaryToolbar?.printButton.classList.add("hidden");
  12423. }
  12424. if (!this.supportsFullscreen) {
  12425. appConfig.secondaryToolbar?.presentationModeButton.classList.add("hidden");
  12426. }
  12427. if (this.supportsIntegratedFind) {
  12428. appConfig.toolbar?.viewFind?.classList.add("hidden");
  12429. }
  12430. if (file) {
  12431. this.open({
  12432. url: file
  12433. });
  12434. } else {
  12435. this._hideViewBookmark();
  12436. }
  12437. },
  12438. get externalServices() {
  12439. return shadow(this, "externalServices", new ExternalServices());
  12440. },
  12441. get initialized() {
  12442. return this._initializedCapability.settled;
  12443. },
  12444. get initializedPromise() {
  12445. return this._initializedCapability.promise;
  12446. },
  12447. updateZoom(steps, scaleFactor, origin) {
  12448. if (this.pdfViewer.isInPresentationMode) {
  12449. return;
  12450. }
  12451. this.pdfViewer.updateScale({
  12452. drawingDelay: AppOptions.get("defaultZoomDelay"),
  12453. steps,
  12454. scaleFactor,
  12455. origin
  12456. });
  12457. },
  12458. zoomIn() {
  12459. this.updateZoom(1);
  12460. },
  12461. zoomOut() {
  12462. this.updateZoom(-1);
  12463. },
  12464. zoomReset() {
  12465. if (this.pdfViewer.isInPresentationMode) {
  12466. return;
  12467. }
  12468. this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  12469. },
  12470. get pagesCount() {
  12471. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  12472. },
  12473. get page() {
  12474. return this.pdfViewer.currentPageNumber;
  12475. },
  12476. set page(val) {
  12477. this.pdfViewer.currentPageNumber = val;
  12478. },
  12479. get supportsPrinting() {
  12480. return PDFPrintServiceFactory.supportsPrinting;
  12481. },
  12482. get supportsFullscreen() {
  12483. return shadow(this, "supportsFullscreen", document.fullscreenEnabled);
  12484. },
  12485. get supportsPinchToZoom() {
  12486. return shadow(this, "supportsPinchToZoom", AppOptions.get("supportsPinchToZoom"));
  12487. },
  12488. get supportsIntegratedFind() {
  12489. return shadow(this, "supportsIntegratedFind", AppOptions.get("supportsIntegratedFind"));
  12490. },
  12491. get loadingBar() {
  12492. const barElement = document.getElementById("loadingBar");
  12493. const bar = barElement ? new ProgressBar(barElement) : null;
  12494. return shadow(this, "loadingBar", bar);
  12495. },
  12496. get supportsMouseWheelZoomCtrlKey() {
  12497. return shadow(this, "supportsMouseWheelZoomCtrlKey", AppOptions.get("supportsMouseWheelZoomCtrlKey"));
  12498. },
  12499. get supportsMouseWheelZoomMetaKey() {
  12500. return shadow(this, "supportsMouseWheelZoomMetaKey", AppOptions.get("supportsMouseWheelZoomMetaKey"));
  12501. },
  12502. get supportsCaretBrowsingMode() {
  12503. return AppOptions.get("supportsCaretBrowsingMode");
  12504. },
  12505. moveCaret(isUp, select) {
  12506. this._caretBrowsing ||= new CaretBrowsingMode(this.appConfig.mainContainer, this.appConfig.viewerContainer, this.appConfig.toolbar?.container);
  12507. this._caretBrowsing.moveCaret(isUp, select);
  12508. },
  12509. setTitleUsingUrl(url = "", downloadUrl = null) {
  12510. this.url = url;
  12511. this.baseUrl = url.split("#", 1)[0];
  12512. if (downloadUrl) {
  12513. this._downloadUrl = downloadUrl === url ? this.baseUrl : downloadUrl.split("#", 1)[0];
  12514. }
  12515. if (isDataScheme(url)) {
  12516. this._hideViewBookmark();
  12517. }
  12518. let title = pdfjs_getPdfFilenameFromUrl(url, "");
  12519. if (!title) {
  12520. try {
  12521. title = decodeURIComponent(getFilenameFromUrl(url));
  12522. } catch {}
  12523. }
  12524. this.setTitle(title || url);
  12525. },
  12526. setTitle(title = this._title) {
  12527. this._title = title;
  12528. if (this.isViewerEmbedded) {
  12529. return;
  12530. }
  12531. const editorIndicator = this._hasAnnotationEditors && !this.pdfRenderingQueue.printing;
  12532. document.title = `${editorIndicator ? "* " : ""}${title}`;
  12533. },
  12534. get _docFilename() {
  12535. return this._contentDispositionFilename || pdfjs_getPdfFilenameFromUrl(this.url);
  12536. },
  12537. _hideViewBookmark() {
  12538. const {
  12539. secondaryToolbar
  12540. } = this.appConfig;
  12541. secondaryToolbar?.viewBookmarkButton.classList.add("hidden");
  12542. if (secondaryToolbar?.presentationModeButton.classList.contains("hidden")) {
  12543. document.getElementById("viewBookmarkSeparator")?.classList.add("hidden");
  12544. }
  12545. },
  12546. async close() {
  12547. this._unblockDocumentLoadEvent();
  12548. this._hideViewBookmark();
  12549. if (!this.pdfLoadingTask) {
  12550. return;
  12551. }
  12552. if (this.pdfDocument?.annotationStorage.size > 0 && this._annotationStorageModified) {
  12553. try {
  12554. await this.save();
  12555. } catch {}
  12556. }
  12557. const promises = [];
  12558. promises.push(this.pdfLoadingTask.destroy());
  12559. this.pdfLoadingTask = null;
  12560. if (this.pdfDocument) {
  12561. this.pdfDocument = null;
  12562. this.pdfThumbnailViewer?.setDocument(null);
  12563. this.pdfViewer.setDocument(null);
  12564. this.pdfLinkService.setDocument(null);
  12565. this.pdfDocumentProperties?.setDocument(null);
  12566. }
  12567. this.pdfLinkService.externalLinkEnabled = true;
  12568. this.store = null;
  12569. this.isInitialViewSet = false;
  12570. this.url = "";
  12571. this.baseUrl = "";
  12572. this._downloadUrl = "";
  12573. this.documentInfo = null;
  12574. this.metadata = null;
  12575. this._contentDispositionFilename = null;
  12576. this._contentLength = null;
  12577. this._saveInProgress = false;
  12578. this._hasAnnotationEditors = false;
  12579. promises.push(this.pdfScriptingManager.destroyPromise, this.passwordPrompt.close());
  12580. this.setTitle();
  12581. this.pdfSidebar?.reset();
  12582. this.pdfOutlineViewer?.reset();
  12583. this.pdfAttachmentViewer?.reset();
  12584. this.pdfLayerViewer?.reset();
  12585. this.pdfHistory?.reset();
  12586. this.findBar?.reset();
  12587. this.toolbar?.reset();
  12588. this.secondaryToolbar?.reset();
  12589. this._PDFBug?.cleanup();
  12590. await Promise.all(promises);
  12591. },
  12592. async open(args) {
  12593. if (this.pdfLoadingTask) {
  12594. await this.close();
  12595. }
  12596. const workerParams = AppOptions.getAll(OptionKind.WORKER);
  12597. Object.assign(GlobalWorkerOptions, workerParams);
  12598. if (args.url) {
  12599. this.setTitleUsingUrl(args.originalUrl || args.url, args.url);
  12600. }
  12601. const apiParams = AppOptions.getAll(OptionKind.API);
  12602. const loadingTask = getDocument({
  12603. ...apiParams,
  12604. ...args
  12605. });
  12606. this.pdfLoadingTask = loadingTask;
  12607. loadingTask.onPassword = (updateCallback, reason) => {
  12608. if (this.isViewerEmbedded) {
  12609. this._unblockDocumentLoadEvent();
  12610. }
  12611. this.pdfLinkService.externalLinkEnabled = false;
  12612. this.passwordPrompt.setUpdateCallback(updateCallback, reason);
  12613. this.passwordPrompt.open();
  12614. };
  12615. loadingTask.onProgress = ({
  12616. loaded,
  12617. total
  12618. }) => {
  12619. this.progress(loaded / total);
  12620. };
  12621. return loadingTask.promise.then(pdfDocument => {
  12622. this.load(pdfDocument);
  12623. }, reason => {
  12624. if (loadingTask !== this.pdfLoadingTask) {
  12625. return undefined;
  12626. }
  12627. let key = "pdfjs-loading-error";
  12628. if (reason instanceof InvalidPDFException) {
  12629. key = "pdfjs-invalid-file-error";
  12630. } else if (reason instanceof MissingPDFException) {
  12631. key = "pdfjs-missing-file-error";
  12632. } else if (reason instanceof UnexpectedResponseException) {
  12633. key = "pdfjs-unexpected-response-error";
  12634. }
  12635. return this._documentError(key, {
  12636. message: reason.message
  12637. }).then(() => {
  12638. throw reason;
  12639. });
  12640. });
  12641. },
  12642. async download(options = {}) {
  12643. let data;
  12644. try {
  12645. data = await this.pdfDocument.getData();
  12646. } catch {}
  12647. this.downloadManager.download(data, this._downloadUrl, this._docFilename, options);
  12648. },
  12649. async save(options = {}) {
  12650. if (this._saveInProgress) {
  12651. return;
  12652. }
  12653. this._saveInProgress = true;
  12654. await this.pdfScriptingManager.dispatchWillSave();
  12655. try {
  12656. const data = await this.pdfDocument.saveDocument();
  12657. this.downloadManager.download(data, this._downloadUrl, this._docFilename, options);
  12658. } catch (reason) {
  12659. console.error(`Error when saving the document: ${reason.message}`);
  12660. await this.download(options);
  12661. } finally {
  12662. await this.pdfScriptingManager.dispatchDidSave();
  12663. this._saveInProgress = false;
  12664. }
  12665. if (this._hasAnnotationEditors) {
  12666. this.externalServices.reportTelemetry({
  12667. type: "editing",
  12668. data: {
  12669. type: "save",
  12670. stats: this.pdfDocument?.annotationStorage.editorStats
  12671. }
  12672. });
  12673. }
  12674. },
  12675. async downloadOrSave(options = {}) {
  12676. const {
  12677. classList
  12678. } = this.appConfig.appContainer;
  12679. classList.add("wait");
  12680. await (this.pdfDocument?.annotationStorage.size > 0 ? this.save(options) : this.download(options));
  12681. classList.remove("wait");
  12682. },
  12683. async _documentError(key, moreInfo = null) {
  12684. this._unblockDocumentLoadEvent();
  12685. const message = await this._otherError(key || "pdfjs-loading-error", moreInfo);
  12686. this.eventBus.dispatch("documenterror", {
  12687. source: this,
  12688. message,
  12689. reason: moreInfo?.message ?? null
  12690. });
  12691. },
  12692. async _otherError(key, moreInfo = null) {
  12693. const message = await this.l10n.get(key);
  12694. const moreInfoText = [`PDF.js v${version || "?"} (build: ${build || "?"})`];
  12695. if (moreInfo) {
  12696. moreInfoText.push(`Message: ${moreInfo.message}`);
  12697. if (moreInfo.stack) {
  12698. moreInfoText.push(`Stack: ${moreInfo.stack}`);
  12699. } else {
  12700. if (moreInfo.filename) {
  12701. moreInfoText.push(`File: ${moreInfo.filename}`);
  12702. }
  12703. if (moreInfo.lineNumber) {
  12704. moreInfoText.push(`Line: ${moreInfo.lineNumber}`);
  12705. }
  12706. }
  12707. }
  12708. console.error(`${message}\n\n${moreInfoText.join("\n")}`);
  12709. return message;
  12710. },
  12711. progress(level) {
  12712. const percent = Math.round(level * 100);
  12713. if (!this.loadingBar || percent <= this.loadingBar.percent) {
  12714. return;
  12715. }
  12716. this.loadingBar.percent = percent;
  12717. if (this.pdfDocument?.loadingParams.disableAutoFetch ?? AppOptions.get("disableAutoFetch")) {
  12718. this.loadingBar.setDisableAutoFetch();
  12719. }
  12720. },
  12721. load(pdfDocument) {
  12722. this.pdfDocument = pdfDocument;
  12723. pdfDocument.getDownloadInfo().then(({
  12724. length
  12725. }) => {
  12726. this._contentLength = length;
  12727. this.loadingBar?.hide();
  12728. firstPagePromise.then(() => {
  12729. this.eventBus.dispatch("documentloaded", {
  12730. source: this
  12731. });
  12732. });
  12733. });
  12734. const pageLayoutPromise = pdfDocument.getPageLayout().catch(() => {});
  12735. const pageModePromise = pdfDocument.getPageMode().catch(() => {});
  12736. const openActionPromise = pdfDocument.getOpenAction().catch(() => {});
  12737. this.toolbar?.setPagesCount(pdfDocument.numPages, false);
  12738. this.secondaryToolbar?.setPagesCount(pdfDocument.numPages);
  12739. this.pdfLinkService.setDocument(pdfDocument);
  12740. this.pdfDocumentProperties?.setDocument(pdfDocument);
  12741. const pdfViewer = this.pdfViewer;
  12742. pdfViewer.setDocument(pdfDocument);
  12743. const {
  12744. firstPagePromise,
  12745. onePageRendered,
  12746. pagesPromise
  12747. } = pdfViewer;
  12748. this.pdfThumbnailViewer?.setDocument(pdfDocument);
  12749. const storedPromise = (this.store = new ViewHistory(pdfDocument.fingerprints[0])).getMultiple({
  12750. page: null,
  12751. zoom: DEFAULT_SCALE_VALUE,
  12752. scrollLeft: "0",
  12753. scrollTop: "0",
  12754. rotation: null,
  12755. sidebarView: SidebarView.UNKNOWN,
  12756. scrollMode: ScrollMode.UNKNOWN,
  12757. spreadMode: SpreadMode.UNKNOWN
  12758. }).catch(() => {});
  12759. firstPagePromise.then(pdfPage => {
  12760. this.loadingBar?.setWidth(this.appConfig.viewerContainer);
  12761. this._initializeAnnotationStorageCallbacks(pdfDocument);
  12762. Promise.all([animationStarted, storedPromise, pageLayoutPromise, pageModePromise, openActionPromise]).then(async ([timeStamp, stored, pageLayout, pageMode, openAction]) => {
  12763. const viewOnLoad = AppOptions.get("viewOnLoad");
  12764. this._initializePdfHistory({
  12765. fingerprint: pdfDocument.fingerprints[0],
  12766. viewOnLoad,
  12767. initialDest: openAction?.dest
  12768. });
  12769. const initialBookmark = this.initialBookmark;
  12770. const zoom = AppOptions.get("defaultZoomValue");
  12771. let hash = zoom ? `zoom=${zoom}` : null;
  12772. let rotation = null;
  12773. let sidebarView = AppOptions.get("sidebarViewOnLoad");
  12774. let scrollMode = AppOptions.get("scrollModeOnLoad");
  12775. let spreadMode = AppOptions.get("spreadModeOnLoad");
  12776. if (stored?.page && viewOnLoad !== ViewOnLoad.INITIAL) {
  12777. hash = `page=${stored.page}&zoom=${zoom || stored.zoom},` + `${stored.scrollLeft},${stored.scrollTop}`;
  12778. rotation = parseInt(stored.rotation, 10);
  12779. if (sidebarView === SidebarView.UNKNOWN) {
  12780. sidebarView = stored.sidebarView | 0;
  12781. }
  12782. if (scrollMode === ScrollMode.UNKNOWN) {
  12783. scrollMode = stored.scrollMode | 0;
  12784. }
  12785. if (spreadMode === SpreadMode.UNKNOWN) {
  12786. spreadMode = stored.spreadMode | 0;
  12787. }
  12788. }
  12789. if (pageMode && sidebarView === SidebarView.UNKNOWN) {
  12790. sidebarView = apiPageModeToSidebarView(pageMode);
  12791. }
  12792. if (pageLayout && scrollMode === ScrollMode.UNKNOWN && spreadMode === SpreadMode.UNKNOWN) {
  12793. const modes = apiPageLayoutToViewerModes(pageLayout);
  12794. spreadMode = modes.spreadMode;
  12795. }
  12796. this.setInitialView(hash, {
  12797. rotation,
  12798. sidebarView,
  12799. scrollMode,
  12800. spreadMode
  12801. });
  12802. this.eventBus.dispatch("documentinit", {
  12803. source: this
  12804. });
  12805. if (!this.isViewerEmbedded) {
  12806. pdfViewer.focus();
  12807. }
  12808. await Promise.race([pagesPromise, new Promise(resolve => {
  12809. setTimeout(resolve, FORCE_PAGES_LOADED_TIMEOUT);
  12810. })]);
  12811. if (!initialBookmark && !hash) {
  12812. return;
  12813. }
  12814. if (pdfViewer.hasEqualPageSizes) {
  12815. return;
  12816. }
  12817. this.initialBookmark = initialBookmark;
  12818. pdfViewer.currentScaleValue = pdfViewer.currentScaleValue;
  12819. this.setInitialView(hash);
  12820. }).catch(() => {
  12821. this.setInitialView();
  12822. }).then(function () {
  12823. pdfViewer.update();
  12824. });
  12825. });
  12826. pagesPromise.then(() => {
  12827. this._unblockDocumentLoadEvent();
  12828. this._initializeAutoPrint(pdfDocument, openActionPromise);
  12829. }, reason => {
  12830. this._documentError("pdfjs-loading-error", {
  12831. message: reason.message
  12832. });
  12833. });
  12834. onePageRendered.then(data => {
  12835. this.externalServices.reportTelemetry({
  12836. type: "pageInfo",
  12837. timestamp: data.timestamp
  12838. });
  12839. if (this.pdfOutlineViewer) {
  12840. pdfDocument.getOutline().then(outline => {
  12841. if (pdfDocument !== this.pdfDocument) {
  12842. return;
  12843. }
  12844. this.pdfOutlineViewer.render({
  12845. outline,
  12846. pdfDocument
  12847. });
  12848. });
  12849. }
  12850. if (this.pdfAttachmentViewer) {
  12851. pdfDocument.getAttachments().then(attachments => {
  12852. if (pdfDocument !== this.pdfDocument) {
  12853. return;
  12854. }
  12855. this.pdfAttachmentViewer.render({
  12856. attachments
  12857. });
  12858. });
  12859. }
  12860. if (this.pdfLayerViewer) {
  12861. pdfViewer.optionalContentConfigPromise.then(optionalContentConfig => {
  12862. if (pdfDocument !== this.pdfDocument) {
  12863. return;
  12864. }
  12865. this.pdfLayerViewer.render({
  12866. optionalContentConfig,
  12867. pdfDocument
  12868. });
  12869. });
  12870. }
  12871. });
  12872. this._initializePageLabels(pdfDocument);
  12873. this._initializeMetadata(pdfDocument);
  12874. },
  12875. async _scriptingDocProperties(pdfDocument) {
  12876. if (!this.documentInfo) {
  12877. await new Promise(resolve => {
  12878. this.eventBus._on("metadataloaded", resolve, {
  12879. once: true
  12880. });
  12881. });
  12882. if (pdfDocument !== this.pdfDocument) {
  12883. return null;
  12884. }
  12885. }
  12886. if (!this._contentLength) {
  12887. await new Promise(resolve => {
  12888. this.eventBus._on("documentloaded", resolve, {
  12889. once: true
  12890. });
  12891. });
  12892. if (pdfDocument !== this.pdfDocument) {
  12893. return null;
  12894. }
  12895. }
  12896. return {
  12897. ...this.documentInfo,
  12898. baseURL: this.baseUrl,
  12899. filesize: this._contentLength,
  12900. filename: this._docFilename,
  12901. metadata: this.metadata?.getRaw(),
  12902. authors: this.metadata?.get("dc:creator"),
  12903. numPages: this.pagesCount,
  12904. URL: this.url
  12905. };
  12906. },
  12907. async _initializeAutoPrint(pdfDocument, openActionPromise) {
  12908. const [openAction, jsActions] = await Promise.all([openActionPromise, this.pdfViewer.enableScripting ? null : pdfDocument.getJSActions()]);
  12909. if (pdfDocument !== this.pdfDocument) {
  12910. return;
  12911. }
  12912. let triggerAutoPrint = openAction?.action === "Print";
  12913. if (jsActions) {
  12914. console.warn("Warning: JavaScript support is not enabled");
  12915. for (const name in jsActions) {
  12916. if (triggerAutoPrint) {
  12917. break;
  12918. }
  12919. switch (name) {
  12920. case "WillClose":
  12921. case "WillSave":
  12922. case "DidSave":
  12923. case "WillPrint":
  12924. case "DidPrint":
  12925. continue;
  12926. }
  12927. triggerAutoPrint = jsActions[name].some(js => AutoPrintRegExp.test(js));
  12928. }
  12929. }
  12930. if (triggerAutoPrint) {
  12931. this.triggerPrinting();
  12932. }
  12933. },
  12934. async _initializeMetadata(pdfDocument) {
  12935. const {
  12936. info,
  12937. metadata,
  12938. contentDispositionFilename,
  12939. contentLength
  12940. } = await pdfDocument.getMetadata();
  12941. if (pdfDocument !== this.pdfDocument) {
  12942. return;
  12943. }
  12944. this.documentInfo = info;
  12945. this.metadata = metadata;
  12946. this._contentDispositionFilename ??= contentDispositionFilename;
  12947. this._contentLength ??= contentLength;
  12948. console.log(`PDF ${pdfDocument.fingerprints[0]} [${info.PDFFormatVersion} ` + `${(info.Producer || "-").trim()} / ${(info.Creator || "-").trim()}] ` + `(PDF.js: ${version || "?"} [${build || "?"}])`);
  12949. let pdfTitle = info.Title;
  12950. const metadataTitle = metadata?.get("dc:title");
  12951. if (metadataTitle) {
  12952. if (metadataTitle !== "Untitled" && !/[\uFFF0-\uFFFF]/g.test(metadataTitle)) {
  12953. pdfTitle = metadataTitle;
  12954. }
  12955. }
  12956. if (pdfTitle) {
  12957. this.setTitle(`${pdfTitle} - ${this._contentDispositionFilename || this._title}`);
  12958. } else if (this._contentDispositionFilename) {
  12959. this.setTitle(this._contentDispositionFilename);
  12960. }
  12961. if (info.IsXFAPresent && !info.IsAcroFormPresent && !pdfDocument.isPureXfa) {
  12962. if (pdfDocument.loadingParams.enableXfa) {
  12963. console.warn("Warning: XFA Foreground documents are not supported");
  12964. } else {
  12965. console.warn("Warning: XFA support is not enabled");
  12966. }
  12967. } else if ((info.IsAcroFormPresent || info.IsXFAPresent) && !this.pdfViewer.renderForms) {
  12968. console.warn("Warning: Interactive form support is not enabled");
  12969. }
  12970. if (info.IsSignaturesPresent) {
  12971. console.warn("Warning: Digital signatures validation is not supported");
  12972. }
  12973. this.eventBus.dispatch("metadataloaded", {
  12974. source: this
  12975. });
  12976. },
  12977. async _initializePageLabels(pdfDocument) {
  12978. const labels = await pdfDocument.getPageLabels();
  12979. if (pdfDocument !== this.pdfDocument) {
  12980. return;
  12981. }
  12982. if (!labels || AppOptions.get("disablePageLabels")) {
  12983. return;
  12984. }
  12985. const numLabels = labels.length;
  12986. let standardLabels = 0,
  12987. emptyLabels = 0;
  12988. for (let i = 0; i < numLabels; i++) {
  12989. const label = labels[i];
  12990. if (label === (i + 1).toString()) {
  12991. standardLabels++;
  12992. } else if (label === "") {
  12993. emptyLabels++;
  12994. } else {
  12995. break;
  12996. }
  12997. }
  12998. if (standardLabels >= numLabels || emptyLabels >= numLabels) {
  12999. return;
  13000. }
  13001. const {
  13002. pdfViewer,
  13003. pdfThumbnailViewer,
  13004. toolbar
  13005. } = this;
  13006. pdfViewer.setPageLabels(labels);
  13007. pdfThumbnailViewer?.setPageLabels(labels);
  13008. toolbar?.setPagesCount(numLabels, true);
  13009. toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  13010. },
  13011. _initializePdfHistory({
  13012. fingerprint,
  13013. viewOnLoad,
  13014. initialDest = null
  13015. }) {
  13016. if (!this.pdfHistory) {
  13017. return;
  13018. }
  13019. this.pdfHistory.initialize({
  13020. fingerprint,
  13021. resetHistory: viewOnLoad === ViewOnLoad.INITIAL,
  13022. updateUrl: AppOptions.get("historyUpdateUrl")
  13023. });
  13024. if (this.pdfHistory.initialBookmark) {
  13025. this.initialBookmark = this.pdfHistory.initialBookmark;
  13026. this.initialRotation = this.pdfHistory.initialRotation;
  13027. }
  13028. if (initialDest && !this.initialBookmark && viewOnLoad === ViewOnLoad.UNKNOWN) {
  13029. this.initialBookmark = JSON.stringify(initialDest);
  13030. this.pdfHistory.push({
  13031. explicitDest: initialDest,
  13032. pageNumber: null
  13033. });
  13034. }
  13035. },
  13036. _initializeAnnotationStorageCallbacks(pdfDocument) {
  13037. if (pdfDocument !== this.pdfDocument) {
  13038. return;
  13039. }
  13040. const {
  13041. annotationStorage
  13042. } = pdfDocument;
  13043. annotationStorage.onSetModified = () => {
  13044. window.addEventListener("beforeunload", beforeUnload);
  13045. this._annotationStorageModified = true;
  13046. };
  13047. annotationStorage.onResetModified = () => {
  13048. window.removeEventListener("beforeunload", beforeUnload);
  13049. delete this._annotationStorageModified;
  13050. };
  13051. annotationStorage.onAnnotationEditor = typeStr => {
  13052. this._hasAnnotationEditors = !!typeStr;
  13053. this.setTitle();
  13054. };
  13055. },
  13056. setInitialView(storedHash, {
  13057. rotation,
  13058. sidebarView,
  13059. scrollMode,
  13060. spreadMode
  13061. } = {}) {
  13062. const setRotation = angle => {
  13063. if (isValidRotation(angle)) {
  13064. this.pdfViewer.pagesRotation = angle;
  13065. }
  13066. };
  13067. const setViewerModes = (scroll, spread) => {
  13068. if (isValidScrollMode(scroll)) {
  13069. this.pdfViewer.scrollMode = scroll;
  13070. }
  13071. if (isValidSpreadMode(spread)) {
  13072. this.pdfViewer.spreadMode = spread;
  13073. }
  13074. };
  13075. this.isInitialViewSet = true;
  13076. this.pdfSidebar?.setInitialView(sidebarView);
  13077. setViewerModes(scrollMode, spreadMode);
  13078. if (this.initialBookmark) {
  13079. setRotation(this.initialRotation);
  13080. delete this.initialRotation;
  13081. this.pdfLinkService.setHash(this.initialBookmark);
  13082. this.initialBookmark = null;
  13083. } else if (storedHash) {
  13084. setRotation(rotation);
  13085. this.pdfLinkService.setHash(storedHash);
  13086. }
  13087. this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber, this.pdfViewer.currentPageLabel);
  13088. this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber);
  13089. if (!this.pdfViewer.currentScaleValue) {
  13090. this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  13091. }
  13092. },
  13093. _cleanup() {
  13094. if (!this.pdfDocument) {
  13095. return;
  13096. }
  13097. this.pdfViewer.cleanup();
  13098. this.pdfThumbnailViewer?.cleanup();
  13099. this.pdfDocument.cleanup(AppOptions.get("fontExtraProperties"));
  13100. },
  13101. forceRendering() {
  13102. this.pdfRenderingQueue.printing = !!this.printService;
  13103. this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar?.visibleView === SidebarView.THUMBS;
  13104. this.pdfRenderingQueue.renderHighestPriority();
  13105. },
  13106. beforePrint() {
  13107. this._printAnnotationStoragePromise = this.pdfScriptingManager.dispatchWillPrint().catch(() => {}).then(() => this.pdfDocument?.annotationStorage.print);
  13108. if (this.printService) {
  13109. return;
  13110. }
  13111. if (!this.supportsPrinting) {
  13112. this._otherError("pdfjs-printing-not-supported");
  13113. return;
  13114. }
  13115. if (!this.pdfViewer.pageViewsReady) {
  13116. this.l10n.get("pdfjs-printing-not-ready").then(msg => {
  13117. window.alert(msg);
  13118. });
  13119. return;
  13120. }
  13121. this.printService = PDFPrintServiceFactory.createPrintService({
  13122. pdfDocument: this.pdfDocument,
  13123. pagesOverview: this.pdfViewer.getPagesOverview(),
  13124. printContainer: this.appConfig.printContainer,
  13125. printResolution: AppOptions.get("printResolution"),
  13126. printAnnotationStoragePromise: this._printAnnotationStoragePromise
  13127. });
  13128. this.forceRendering();
  13129. this.setTitle();
  13130. this.printService.layout();
  13131. if (this._hasAnnotationEditors) {
  13132. this.externalServices.reportTelemetry({
  13133. type: "editing",
  13134. data: {
  13135. type: "print",
  13136. stats: this.pdfDocument?.annotationStorage.editorStats
  13137. }
  13138. });
  13139. }
  13140. },
  13141. afterPrint() {
  13142. if (this._printAnnotationStoragePromise) {
  13143. this._printAnnotationStoragePromise.then(() => {
  13144. this.pdfScriptingManager.dispatchDidPrint();
  13145. });
  13146. this._printAnnotationStoragePromise = null;
  13147. }
  13148. if (this.printService) {
  13149. this.printService.destroy();
  13150. this.printService = null;
  13151. this.pdfDocument?.annotationStorage.resetModified();
  13152. }
  13153. this.forceRendering();
  13154. this.setTitle();
  13155. },
  13156. rotatePages(delta) {
  13157. this.pdfViewer.pagesRotation += delta;
  13158. },
  13159. requestPresentationMode() {
  13160. this.pdfPresentationMode?.request();
  13161. },
  13162. triggerPrinting() {
  13163. if (!this.supportsPrinting) {
  13164. return;
  13165. }
  13166. window.print();
  13167. },
  13168. bindEvents() {
  13169. if (this._eventBusAbortController) {
  13170. return;
  13171. }
  13172. this._eventBusAbortController = new AbortController();
  13173. const {
  13174. eventBus,
  13175. _eventBusAbortController: {
  13176. signal
  13177. }
  13178. } = this;
  13179. eventBus._on("resize", webViewerResize, {
  13180. signal
  13181. });
  13182. eventBus._on("hashchange", webViewerHashchange, {
  13183. signal
  13184. });
  13185. eventBus._on("beforeprint", this.beforePrint.bind(this), {
  13186. signal
  13187. });
  13188. eventBus._on("afterprint", this.afterPrint.bind(this), {
  13189. signal
  13190. });
  13191. eventBus._on("pagerender", webViewerPageRender, {
  13192. signal
  13193. });
  13194. eventBus._on("pagerendered", webViewerPageRendered, {
  13195. signal
  13196. });
  13197. eventBus._on("updateviewarea", webViewerUpdateViewarea, {
  13198. signal
  13199. });
  13200. eventBus._on("pagechanging", webViewerPageChanging, {
  13201. signal
  13202. });
  13203. eventBus._on("scalechanging", webViewerScaleChanging, {
  13204. signal
  13205. });
  13206. eventBus._on("rotationchanging", webViewerRotationChanging, {
  13207. signal
  13208. });
  13209. eventBus._on("sidebarviewchanged", webViewerSidebarViewChanged, {
  13210. signal
  13211. });
  13212. eventBus._on("pagemode", webViewerPageMode, {
  13213. signal
  13214. });
  13215. eventBus._on("namedaction", webViewerNamedAction, {
  13216. signal
  13217. });
  13218. eventBus._on("presentationmodechanged", webViewerPresentationModeChanged, {
  13219. signal
  13220. });
  13221. eventBus._on("presentationmode", webViewerPresentationMode, {
  13222. signal
  13223. });
  13224. eventBus._on("switchannotationeditormode", webViewerSwitchAnnotationEditorMode, {
  13225. signal
  13226. });
  13227. eventBus._on("switchannotationeditorparams", webViewerSwitchAnnotationEditorParams, {
  13228. signal
  13229. });
  13230. eventBus._on("print", webViewerPrint, {
  13231. signal
  13232. });
  13233. eventBus._on("download", webViewerDownload, {
  13234. signal
  13235. });
  13236. eventBus._on("firstpage", webViewerFirstPage, {
  13237. signal
  13238. });
  13239. eventBus._on("lastpage", webViewerLastPage, {
  13240. signal
  13241. });
  13242. eventBus._on("nextpage", webViewerNextPage, {
  13243. signal
  13244. });
  13245. eventBus._on("previouspage", webViewerPreviousPage, {
  13246. signal
  13247. });
  13248. eventBus._on("zoomin", webViewerZoomIn, {
  13249. signal
  13250. });
  13251. eventBus._on("zoomout", webViewerZoomOut, {
  13252. signal
  13253. });
  13254. eventBus._on("zoomreset", webViewerZoomReset, {
  13255. signal
  13256. });
  13257. eventBus._on("pagenumberchanged", webViewerPageNumberChanged, {
  13258. signal
  13259. });
  13260. eventBus._on("scalechanged", webViewerScaleChanged, {
  13261. signal
  13262. });
  13263. eventBus._on("rotatecw", webViewerRotateCw, {
  13264. signal
  13265. });
  13266. eventBus._on("rotateccw", webViewerRotateCcw, {
  13267. signal
  13268. });
  13269. eventBus._on("optionalcontentconfig", webViewerOptionalContentConfig, {
  13270. signal
  13271. });
  13272. eventBus._on("switchscrollmode", webViewerSwitchScrollMode, {
  13273. signal
  13274. });
  13275. eventBus._on("scrollmodechanged", webViewerScrollModeChanged, {
  13276. signal
  13277. });
  13278. eventBus._on("switchspreadmode", webViewerSwitchSpreadMode, {
  13279. signal
  13280. });
  13281. eventBus._on("spreadmodechanged", webViewerSpreadModeChanged, {
  13282. signal
  13283. });
  13284. eventBus._on("documentproperties", webViewerDocumentProperties, {
  13285. signal
  13286. });
  13287. eventBus._on("findfromurlhash", webViewerFindFromUrlHash, {
  13288. signal
  13289. });
  13290. eventBus._on("updatefindmatchescount", webViewerUpdateFindMatchesCount, {
  13291. signal
  13292. });
  13293. eventBus._on("updatefindcontrolstate", webViewerUpdateFindControlState, {
  13294. signal
  13295. });
  13296. eventBus._on("fileinputchange", webViewerFileInputChange, {
  13297. signal
  13298. });
  13299. eventBus._on("openfile", webViewerOpenFile, {
  13300. signal
  13301. });
  13302. },
  13303. bindWindowEvents() {
  13304. if (this._windowAbortController) {
  13305. return;
  13306. }
  13307. this._windowAbortController = new AbortController();
  13308. const {
  13309. eventBus,
  13310. appConfig: {
  13311. mainContainer
  13312. },
  13313. _windowAbortController: {
  13314. signal
  13315. }
  13316. } = this;
  13317. function addWindowResolutionChange(evt = null) {
  13318. if (evt) {
  13319. webViewerResolutionChange(evt);
  13320. }
  13321. const mediaQueryList = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`);
  13322. mediaQueryList.addEventListener("change", addWindowResolutionChange, {
  13323. once: true,
  13324. signal
  13325. });
  13326. }
  13327. addWindowResolutionChange();
  13328. window.addEventListener("wheel", webViewerWheel, {
  13329. passive: false,
  13330. signal
  13331. });
  13332. window.addEventListener("touchstart", webViewerTouchStart, {
  13333. passive: false,
  13334. signal
  13335. });
  13336. window.addEventListener("touchmove", webViewerTouchMove, {
  13337. passive: false,
  13338. signal
  13339. });
  13340. window.addEventListener("touchend", webViewerTouchEnd, {
  13341. passive: false,
  13342. signal
  13343. });
  13344. window.addEventListener("click", webViewerClick, {
  13345. signal
  13346. });
  13347. window.addEventListener("keydown", webViewerKeyDown, {
  13348. signal
  13349. });
  13350. window.addEventListener("keyup", webViewerKeyUp, {
  13351. signal
  13352. });
  13353. window.addEventListener("resize", () => {
  13354. eventBus.dispatch("resize", {
  13355. source: window
  13356. });
  13357. }, {
  13358. signal
  13359. });
  13360. window.addEventListener("hashchange", () => {
  13361. eventBus.dispatch("hashchange", {
  13362. source: window,
  13363. hash: document.location.hash.substring(1)
  13364. });
  13365. }, {
  13366. signal
  13367. });
  13368. window.addEventListener("beforeprint", () => {
  13369. eventBus.dispatch("beforeprint", {
  13370. source: window
  13371. });
  13372. }, {
  13373. signal
  13374. });
  13375. window.addEventListener("afterprint", () => {
  13376. eventBus.dispatch("afterprint", {
  13377. source: window
  13378. });
  13379. }, {
  13380. signal
  13381. });
  13382. window.addEventListener("updatefromsandbox", event => {
  13383. eventBus.dispatch("updatefromsandbox", {
  13384. source: window,
  13385. detail: event.detail
  13386. });
  13387. }, {
  13388. signal
  13389. });
  13390. if (!("onscrollend" in document.documentElement)) {
  13391. return;
  13392. }
  13393. ({
  13394. scrollTop: this._lastScrollTop,
  13395. scrollLeft: this._lastScrollLeft
  13396. } = mainContainer);
  13397. const scrollend = () => {
  13398. ({
  13399. scrollTop: this._lastScrollTop,
  13400. scrollLeft: this._lastScrollLeft
  13401. } = mainContainer);
  13402. this._isScrolling = false;
  13403. mainContainer.addEventListener("scroll", scroll, {
  13404. passive: true,
  13405. signal
  13406. });
  13407. mainContainer.removeEventListener("scrollend", scrollend);
  13408. mainContainer.removeEventListener("blur", scrollend);
  13409. };
  13410. const scroll = () => {
  13411. if (this._isCtrlKeyDown) {
  13412. return;
  13413. }
  13414. if (this._lastScrollTop === mainContainer.scrollTop && this._lastScrollLeft === mainContainer.scrollLeft) {
  13415. return;
  13416. }
  13417. mainContainer.removeEventListener("scroll", scroll, {
  13418. passive: true
  13419. });
  13420. this._isScrolling = true;
  13421. mainContainer.addEventListener("scrollend", scrollend, {
  13422. signal
  13423. });
  13424. mainContainer.addEventListener("blur", scrollend, {
  13425. signal
  13426. });
  13427. };
  13428. mainContainer.addEventListener("scroll", scroll, {
  13429. passive: true,
  13430. signal
  13431. });
  13432. },
  13433. unbindEvents() {
  13434. this._eventBusAbortController?.abort();
  13435. this._eventBusAbortController = null;
  13436. },
  13437. unbindWindowEvents() {
  13438. this._windowAbortController?.abort();
  13439. this._windowAbortController = null;
  13440. },
  13441. async testingClose() {
  13442. this.unbindEvents();
  13443. this.unbindWindowEvents();
  13444. this._globalAbortController?.abort();
  13445. this._globalAbortController = null;
  13446. this.findBar?.close();
  13447. await Promise.all([this.l10n?.destroy(), this.close()]);
  13448. },
  13449. _accumulateTicks(ticks, prop) {
  13450. if (this[prop] > 0 && ticks < 0 || this[prop] < 0 && ticks > 0) {
  13451. this[prop] = 0;
  13452. }
  13453. this[prop] += ticks;
  13454. const wholeTicks = Math.trunc(this[prop]);
  13455. this[prop] -= wholeTicks;
  13456. return wholeTicks;
  13457. },
  13458. _accumulateFactor(previousScale, factor, prop) {
  13459. if (factor === 1) {
  13460. return 1;
  13461. }
  13462. if (this[prop] > 1 && factor < 1 || this[prop] < 1 && factor > 1) {
  13463. this[prop] = 1;
  13464. }
  13465. const newFactor = Math.floor(previousScale * factor * this[prop] * 100) / (100 * previousScale);
  13466. this[prop] = factor / newFactor;
  13467. return newFactor;
  13468. },
  13469. _unblockDocumentLoadEvent() {
  13470. document.blockUnblockOnload?.(false);
  13471. this._unblockDocumentLoadEvent = () => {};
  13472. },
  13473. get scriptingReady() {
  13474. return this.pdfScriptingManager.ready;
  13475. }
  13476. };
  13477. initCom(PDFViewerApplication);
  13478. {
  13479. PDFPrintServiceFactory.initGlobals(PDFViewerApplication);
  13480. }
  13481. {
  13482. const HOSTED_VIEWER_ORIGINS = ["null", "http://mozilla.github.io", "https://mozilla.github.io"];
  13483. var validateFileURL = function (file) {
  13484. if (!file) {
  13485. return;
  13486. }
  13487. try {
  13488. const viewerOrigin = new URL(window.location.href).origin || "null";
  13489. if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) {
  13490. return;
  13491. }
  13492. const fileOrigin = new URL(file, window.location.href).origin;
  13493. if (fileOrigin !== viewerOrigin) {
  13494. // throw new Error("file origin does not match viewer's");
  13495. }
  13496. } catch (ex) {
  13497. PDFViewerApplication._documentError("pdfjs-loading-error", {
  13498. message: ex.message
  13499. });
  13500. throw ex;
  13501. }
  13502. };
  13503. }
  13504. function webViewerPageRender({
  13505. pageNumber
  13506. }) {
  13507. if (pageNumber === PDFViewerApplication.page) {
  13508. PDFViewerApplication.toolbar?.updateLoadingIndicatorState(true);
  13509. }
  13510. }
  13511. function webViewerPageRendered({
  13512. pageNumber,
  13513. error
  13514. }) {
  13515. if (pageNumber === PDFViewerApplication.page) {
  13516. PDFViewerApplication.toolbar?.updateLoadingIndicatorState(false);
  13517. }
  13518. if (PDFViewerApplication.pdfSidebar?.visibleView === SidebarView.THUMBS) {
  13519. const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1);
  13520. const thumbnailView = PDFViewerApplication.pdfThumbnailViewer?.getThumbnail(pageNumber - 1);
  13521. if (pageView) {
  13522. thumbnailView?.setImage(pageView);
  13523. }
  13524. }
  13525. if (error) {
  13526. PDFViewerApplication._otherError("pdfjs-rendering-error", error);
  13527. }
  13528. }
  13529. function webViewerPageMode({
  13530. mode
  13531. }) {
  13532. let view;
  13533. switch (mode) {
  13534. case "thumbs":
  13535. view = SidebarView.THUMBS;
  13536. break;
  13537. case "bookmarks":
  13538. case "outline":
  13539. view = SidebarView.OUTLINE;
  13540. break;
  13541. case "attachments":
  13542. view = SidebarView.ATTACHMENTS;
  13543. break;
  13544. case "layers":
  13545. view = SidebarView.LAYERS;
  13546. break;
  13547. case "none":
  13548. view = SidebarView.NONE;
  13549. break;
  13550. default:
  13551. console.error('Invalid "pagemode" hash parameter: ' + mode);
  13552. return;
  13553. }
  13554. PDFViewerApplication.pdfSidebar?.switchView(view, true);
  13555. }
  13556. function webViewerNamedAction(evt) {
  13557. switch (evt.action) {
  13558. case "GoToPage":
  13559. PDFViewerApplication.appConfig.toolbar?.pageNumber.select();
  13560. break;
  13561. case "Find":
  13562. if (!PDFViewerApplication.supportsIntegratedFind) {
  13563. PDFViewerApplication.findBar?.toggle();
  13564. }
  13565. break;
  13566. case "Print":
  13567. PDFViewerApplication.triggerPrinting();
  13568. break;
  13569. case "SaveAs":
  13570. PDFViewerApplication.downloadOrSave();
  13571. break;
  13572. }
  13573. }
  13574. function webViewerPresentationModeChanged(evt) {
  13575. PDFViewerApplication.pdfViewer.presentationModeState = evt.state;
  13576. }
  13577. function webViewerSidebarViewChanged({
  13578. view
  13579. }) {
  13580. PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = view === SidebarView.THUMBS;
  13581. if (PDFViewerApplication.isInitialViewSet) {
  13582. PDFViewerApplication.store?.set("sidebarView", view).catch(() => {});
  13583. }
  13584. }
  13585. function webViewerUpdateViewarea({
  13586. location
  13587. }) {
  13588. if (PDFViewerApplication.isInitialViewSet) {
  13589. PDFViewerApplication.store?.setMultiple({
  13590. page: location.pageNumber,
  13591. zoom: location.scale,
  13592. scrollLeft: location.left,
  13593. scrollTop: location.top,
  13594. rotation: location.rotation
  13595. }).catch(() => {});
  13596. }
  13597. if (PDFViewerApplication.appConfig.secondaryToolbar) {
  13598. const href = PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
  13599. PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href;
  13600. }
  13601. }
  13602. function webViewerScrollModeChanged(evt) {
  13603. if (PDFViewerApplication.isInitialViewSet && !PDFViewerApplication.pdfViewer.isInPresentationMode) {
  13604. PDFViewerApplication.store?.set("scrollMode", evt.mode).catch(() => {});
  13605. }
  13606. }
  13607. function webViewerSpreadModeChanged(evt) {
  13608. if (PDFViewerApplication.isInitialViewSet && !PDFViewerApplication.pdfViewer.isInPresentationMode) {
  13609. PDFViewerApplication.store?.set("spreadMode", evt.mode).catch(() => {});
  13610. }
  13611. }
  13612. function webViewerResize() {
  13613. const {
  13614. pdfDocument,
  13615. pdfViewer,
  13616. pdfRenderingQueue
  13617. } = PDFViewerApplication;
  13618. if (pdfRenderingQueue.printing && window.matchMedia("print").matches) {
  13619. return;
  13620. }
  13621. if (!pdfDocument) {
  13622. return;
  13623. }
  13624. const currentScaleValue = pdfViewer.currentScaleValue;
  13625. if (currentScaleValue === "auto" || currentScaleValue === "page-fit" || currentScaleValue === "page-width") {
  13626. pdfViewer.currentScaleValue = currentScaleValue;
  13627. }
  13628. pdfViewer.update();
  13629. }
  13630. function webViewerHashchange(evt) {
  13631. const hash = evt.hash;
  13632. if (!hash) {
  13633. return;
  13634. }
  13635. if (!PDFViewerApplication.isInitialViewSet) {
  13636. PDFViewerApplication.initialBookmark = hash;
  13637. } else if (!PDFViewerApplication.pdfHistory?.popStateInProgress) {
  13638. PDFViewerApplication.pdfLinkService.setHash(hash);
  13639. }
  13640. }
  13641. {
  13642. var webViewerFileInputChange = function (evt) {
  13643. if (PDFViewerApplication.pdfViewer?.isInPresentationMode) {
  13644. return;
  13645. }
  13646. const file = evt.fileInput.files[0];
  13647. PDFViewerApplication.open({
  13648. url: URL.createObjectURL(file),
  13649. originalUrl: file.name
  13650. });
  13651. };
  13652. var webViewerOpenFile = function (evt) {
  13653. PDFViewerApplication._openFileInput?.click();
  13654. };
  13655. }
  13656. function webViewerPresentationMode() {
  13657. PDFViewerApplication.requestPresentationMode();
  13658. }
  13659. function webViewerSwitchAnnotationEditorMode(evt) {
  13660. PDFViewerApplication.pdfViewer.annotationEditorMode = evt;
  13661. }
  13662. function webViewerSwitchAnnotationEditorParams(evt) {
  13663. PDFViewerApplication.pdfViewer.annotationEditorParams = evt;
  13664. }
  13665. function webViewerPrint() {
  13666. PDFViewerApplication.triggerPrinting();
  13667. }
  13668. function webViewerDownload() {
  13669. PDFViewerApplication.downloadOrSave();
  13670. }
  13671. function webViewerFirstPage() {
  13672. PDFViewerApplication.page = 1;
  13673. }
  13674. function webViewerLastPage() {
  13675. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  13676. }
  13677. function webViewerNextPage() {
  13678. PDFViewerApplication.pdfViewer.nextPage();
  13679. }
  13680. function webViewerPreviousPage() {
  13681. PDFViewerApplication.pdfViewer.previousPage();
  13682. }
  13683. function webViewerZoomIn() {
  13684. PDFViewerApplication.zoomIn();
  13685. }
  13686. function webViewerZoomOut() {
  13687. PDFViewerApplication.zoomOut();
  13688. }
  13689. function webViewerZoomReset() {
  13690. PDFViewerApplication.zoomReset();
  13691. }
  13692. function webViewerPageNumberChanged(evt) {
  13693. const pdfViewer = PDFViewerApplication.pdfViewer;
  13694. if (evt.value !== "") {
  13695. PDFViewerApplication.pdfLinkService.goToPage(evt.value);
  13696. }
  13697. if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) {
  13698. PDFViewerApplication.toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  13699. }
  13700. }
  13701. function webViewerScaleChanged(evt) {
  13702. PDFViewerApplication.pdfViewer.currentScaleValue = evt.value;
  13703. }
  13704. function webViewerRotateCw() {
  13705. PDFViewerApplication.rotatePages(90);
  13706. }
  13707. function webViewerRotateCcw() {
  13708. PDFViewerApplication.rotatePages(-90);
  13709. }
  13710. function webViewerOptionalContentConfig(evt) {
  13711. PDFViewerApplication.pdfViewer.optionalContentConfigPromise = evt.promise;
  13712. }
  13713. function webViewerSwitchScrollMode(evt) {
  13714. PDFViewerApplication.pdfViewer.scrollMode = evt.mode;
  13715. }
  13716. function webViewerSwitchSpreadMode(evt) {
  13717. PDFViewerApplication.pdfViewer.spreadMode = evt.mode;
  13718. }
  13719. function webViewerDocumentProperties() {
  13720. PDFViewerApplication.pdfDocumentProperties?.open();
  13721. }
  13722. function webViewerFindFromUrlHash(evt) {
  13723. PDFViewerApplication.eventBus.dispatch("find", {
  13724. source: evt.source,
  13725. type: "",
  13726. query: evt.query,
  13727. caseSensitive: false,
  13728. entireWord: false,
  13729. highlightAll: true,
  13730. findPrevious: false,
  13731. matchDiacritics: true
  13732. });
  13733. }
  13734. function webViewerUpdateFindMatchesCount({
  13735. matchesCount
  13736. }) {
  13737. if (PDFViewerApplication.supportsIntegratedFind) {
  13738. PDFViewerApplication.externalServices.updateFindMatchesCount(matchesCount);
  13739. } else {
  13740. PDFViewerApplication.findBar?.updateResultsCount(matchesCount);
  13741. }
  13742. }
  13743. function webViewerUpdateFindControlState({
  13744. state,
  13745. previous,
  13746. entireWord,
  13747. matchesCount,
  13748. rawQuery
  13749. }) {
  13750. if (PDFViewerApplication.supportsIntegratedFind) {
  13751. PDFViewerApplication.externalServices.updateFindControlState({
  13752. result: state,
  13753. findPrevious: previous,
  13754. entireWord,
  13755. matchesCount,
  13756. rawQuery
  13757. });
  13758. } else {
  13759. PDFViewerApplication.findBar?.updateUIState(state, previous, matchesCount);
  13760. }
  13761. }
  13762. function webViewerScaleChanging(evt) {
  13763. PDFViewerApplication.toolbar?.setPageScale(evt.presetValue, evt.scale);
  13764. PDFViewerApplication.pdfViewer.update();
  13765. }
  13766. function webViewerRotationChanging(evt) {
  13767. if (PDFViewerApplication.pdfThumbnailViewer) {
  13768. PDFViewerApplication.pdfThumbnailViewer.pagesRotation = evt.pagesRotation;
  13769. }
  13770. PDFViewerApplication.forceRendering();
  13771. PDFViewerApplication.pdfViewer.currentPageNumber = evt.pageNumber;
  13772. }
  13773. function webViewerPageChanging({
  13774. pageNumber,
  13775. pageLabel
  13776. }) {
  13777. PDFViewerApplication.toolbar?.setPageNumber(pageNumber, pageLabel);
  13778. PDFViewerApplication.secondaryToolbar?.setPageNumber(pageNumber);
  13779. if (PDFViewerApplication.pdfSidebar?.visibleView === SidebarView.THUMBS) {
  13780. PDFViewerApplication.pdfThumbnailViewer?.scrollThumbnailIntoView(pageNumber);
  13781. }
  13782. const currentPage = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1);
  13783. PDFViewerApplication.toolbar?.updateLoadingIndicatorState(currentPage?.renderingState === RenderingStates.RUNNING);
  13784. }
  13785. function webViewerResolutionChange(evt) {
  13786. PDFViewerApplication.pdfViewer.refresh();
  13787. }
  13788. function webViewerWheel(evt) {
  13789. const {
  13790. pdfViewer,
  13791. supportsMouseWheelZoomCtrlKey,
  13792. supportsMouseWheelZoomMetaKey,
  13793. supportsPinchToZoom
  13794. } = PDFViewerApplication;
  13795. if (pdfViewer.isInPresentationMode) {
  13796. return;
  13797. }
  13798. const deltaMode = evt.deltaMode;
  13799. let scaleFactor = Math.exp(-evt.deltaY / 100);
  13800. const isBuiltInMac = false;
  13801. const isPinchToZoom = evt.ctrlKey && !PDFViewerApplication._isCtrlKeyDown && deltaMode === WheelEvent.DOM_DELTA_PIXEL && evt.deltaX === 0 && (Math.abs(scaleFactor - 1) < 0.05 || isBuiltInMac) && evt.deltaZ === 0;
  13802. const origin = [evt.clientX, evt.clientY];
  13803. if (isPinchToZoom || evt.ctrlKey && supportsMouseWheelZoomCtrlKey || evt.metaKey && supportsMouseWheelZoomMetaKey) {
  13804. evt.preventDefault();
  13805. if (PDFViewerApplication._isScrolling || document.visibilityState === "hidden" || PDFViewerApplication.overlayManager.active) {
  13806. return;
  13807. }
  13808. if (isPinchToZoom && supportsPinchToZoom) {
  13809. scaleFactor = PDFViewerApplication._accumulateFactor(pdfViewer.currentScale, scaleFactor, "_wheelUnusedFactor");
  13810. PDFViewerApplication.updateZoom(null, scaleFactor, origin);
  13811. } else {
  13812. const delta = normalizeWheelEventDirection(evt);
  13813. let ticks = 0;
  13814. if (deltaMode === WheelEvent.DOM_DELTA_LINE || deltaMode === WheelEvent.DOM_DELTA_PAGE) {
  13815. if (Math.abs(delta) >= 1) {
  13816. ticks = Math.sign(delta);
  13817. } else {
  13818. ticks = PDFViewerApplication._accumulateTicks(delta, "_wheelUnusedTicks");
  13819. }
  13820. } else {
  13821. const PIXELS_PER_LINE_SCALE = 30;
  13822. ticks = PDFViewerApplication._accumulateTicks(delta / PIXELS_PER_LINE_SCALE, "_wheelUnusedTicks");
  13823. }
  13824. PDFViewerApplication.updateZoom(ticks, null, origin);
  13825. }
  13826. }
  13827. }
  13828. function webViewerTouchStart(evt) {
  13829. if (PDFViewerApplication.pdfViewer.isInPresentationMode || evt.touches.length < 2) {
  13830. return;
  13831. }
  13832. evt.preventDefault();
  13833. if (evt.touches.length !== 2 || PDFViewerApplication.overlayManager.active) {
  13834. PDFViewerApplication._touchInfo = null;
  13835. return;
  13836. }
  13837. let [touch0, touch1] = evt.touches;
  13838. if (touch0.identifier > touch1.identifier) {
  13839. [touch0, touch1] = [touch1, touch0];
  13840. }
  13841. PDFViewerApplication._touchInfo = {
  13842. touch0X: touch0.pageX,
  13843. touch0Y: touch0.pageY,
  13844. touch1X: touch1.pageX,
  13845. touch1Y: touch1.pageY
  13846. };
  13847. }
  13848. function webViewerTouchMove(evt) {
  13849. if (!PDFViewerApplication._touchInfo || evt.touches.length !== 2) {
  13850. return;
  13851. }
  13852. const {
  13853. pdfViewer,
  13854. _touchInfo,
  13855. supportsPinchToZoom
  13856. } = PDFViewerApplication;
  13857. let [touch0, touch1] = evt.touches;
  13858. if (touch0.identifier > touch1.identifier) {
  13859. [touch0, touch1] = [touch1, touch0];
  13860. }
  13861. const {
  13862. pageX: page0X,
  13863. pageY: page0Y
  13864. } = touch0;
  13865. const {
  13866. pageX: page1X,
  13867. pageY: page1Y
  13868. } = touch1;
  13869. const {
  13870. touch0X: pTouch0X,
  13871. touch0Y: pTouch0Y,
  13872. touch1X: pTouch1X,
  13873. touch1Y: pTouch1Y
  13874. } = _touchInfo;
  13875. if (Math.abs(pTouch0X - page0X) <= 1 && Math.abs(pTouch0Y - page0Y) <= 1 && Math.abs(pTouch1X - page1X) <= 1 && Math.abs(pTouch1Y - page1Y) <= 1) {
  13876. return;
  13877. }
  13878. _touchInfo.touch0X = page0X;
  13879. _touchInfo.touch0Y = page0Y;
  13880. _touchInfo.touch1X = page1X;
  13881. _touchInfo.touch1Y = page1Y;
  13882. if (pTouch0X === page0X && pTouch0Y === page0Y) {
  13883. const v1X = pTouch1X - page0X;
  13884. const v1Y = pTouch1Y - page0Y;
  13885. const v2X = page1X - page0X;
  13886. const v2Y = page1Y - page0Y;
  13887. const det = v1X * v2Y - v1Y * v2X;
  13888. if (Math.abs(det) > 0.02 * Math.hypot(v1X, v1Y) * Math.hypot(v2X, v2Y)) {
  13889. return;
  13890. }
  13891. } else if (pTouch1X === page1X && pTouch1Y === page1Y) {
  13892. const v1X = pTouch0X - page1X;
  13893. const v1Y = pTouch0Y - page1Y;
  13894. const v2X = page0X - page1X;
  13895. const v2Y = page0Y - page1Y;
  13896. const det = v1X * v2Y - v1Y * v2X;
  13897. if (Math.abs(det) > 0.02 * Math.hypot(v1X, v1Y) * Math.hypot(v2X, v2Y)) {
  13898. return;
  13899. }
  13900. } else {
  13901. const diff0X = page0X - pTouch0X;
  13902. const diff1X = page1X - pTouch1X;
  13903. const diff0Y = page0Y - pTouch0Y;
  13904. const diff1Y = page1Y - pTouch1Y;
  13905. const dotProduct = diff0X * diff1X + diff0Y * diff1Y;
  13906. if (dotProduct >= 0) {
  13907. return;
  13908. }
  13909. }
  13910. evt.preventDefault();
  13911. const origin = [(page0X + page1X) / 2, (page0Y + page1Y) / 2];
  13912. const distance = Math.hypot(page0X - page1X, page0Y - page1Y) || 1;
  13913. const pDistance = Math.hypot(pTouch0X - pTouch1X, pTouch0Y - pTouch1Y) || 1;
  13914. if (supportsPinchToZoom) {
  13915. const newScaleFactor = PDFViewerApplication._accumulateFactor(pdfViewer.currentScale, distance / pDistance, "_touchUnusedFactor");
  13916. PDFViewerApplication.updateZoom(null, newScaleFactor, origin);
  13917. } else {
  13918. const PIXELS_PER_LINE_SCALE = 30;
  13919. const ticks = PDFViewerApplication._accumulateTicks((distance - pDistance) / PIXELS_PER_LINE_SCALE, "_touchUnusedTicks");
  13920. PDFViewerApplication.updateZoom(ticks, null, origin);
  13921. }
  13922. }
  13923. function webViewerTouchEnd(evt) {
  13924. if (!PDFViewerApplication._touchInfo) {
  13925. return;
  13926. }
  13927. evt.preventDefault();
  13928. PDFViewerApplication._touchInfo = null;
  13929. PDFViewerApplication._touchUnusedTicks = 0;
  13930. PDFViewerApplication._touchUnusedFactor = 1;
  13931. }
  13932. function webViewerClick(evt) {
  13933. if (!PDFViewerApplication.secondaryToolbar?.isOpen) {
  13934. return;
  13935. }
  13936. const appConfig = PDFViewerApplication.appConfig;
  13937. if (PDFViewerApplication.pdfViewer.containsElement(evt.target) || appConfig.toolbar?.container.contains(evt.target) && evt.target !== appConfig.secondaryToolbar?.toggleButton) {
  13938. PDFViewerApplication.secondaryToolbar.close();
  13939. }
  13940. }
  13941. function webViewerKeyUp(evt) {
  13942. if (evt.key === "Control") {
  13943. PDFViewerApplication._isCtrlKeyDown = false;
  13944. }
  13945. }
  13946. function webViewerKeyDown(evt) {
  13947. PDFViewerApplication._isCtrlKeyDown = evt.key === "Control";
  13948. if (PDFViewerApplication.overlayManager.active) {
  13949. return;
  13950. }
  13951. const {
  13952. eventBus,
  13953. pdfViewer
  13954. } = PDFViewerApplication;
  13955. const isViewerInPresentationMode = pdfViewer.isInPresentationMode;
  13956. let handled = false,
  13957. ensureViewerFocused = false;
  13958. const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0);
  13959. if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
  13960. switch (evt.keyCode) {
  13961. case 70:
  13962. if (!PDFViewerApplication.supportsIntegratedFind && !evt.shiftKey) {
  13963. PDFViewerApplication.findBar?.open();
  13964. handled = true;
  13965. }
  13966. break;
  13967. case 71:
  13968. if (!PDFViewerApplication.supportsIntegratedFind) {
  13969. const {
  13970. state
  13971. } = PDFViewerApplication.findController;
  13972. if (state) {
  13973. const newState = {
  13974. source: window,
  13975. type: "again",
  13976. findPrevious: cmd === 5 || cmd === 12
  13977. };
  13978. eventBus.dispatch("find", {
  13979. ...state,
  13980. ...newState
  13981. });
  13982. }
  13983. handled = true;
  13984. }
  13985. break;
  13986. case 61:
  13987. case 107:
  13988. case 187:
  13989. case 171:
  13990. PDFViewerApplication.zoomIn();
  13991. handled = true;
  13992. break;
  13993. case 173:
  13994. case 109:
  13995. case 189:
  13996. PDFViewerApplication.zoomOut();
  13997. handled = true;
  13998. break;
  13999. case 48:
  14000. case 96:
  14001. if (!isViewerInPresentationMode) {
  14002. setTimeout(function () {
  14003. PDFViewerApplication.zoomReset();
  14004. });
  14005. handled = false;
  14006. }
  14007. break;
  14008. case 38:
  14009. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  14010. PDFViewerApplication.page = 1;
  14011. handled = true;
  14012. ensureViewerFocused = true;
  14013. }
  14014. break;
  14015. case 40:
  14016. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  14017. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  14018. handled = true;
  14019. ensureViewerFocused = true;
  14020. }
  14021. break;
  14022. }
  14023. }
  14024. if (cmd === 1 || cmd === 8) {
  14025. switch (evt.keyCode) {
  14026. case 83:
  14027. eventBus.dispatch("download", {
  14028. source: window
  14029. });
  14030. handled = true;
  14031. break;
  14032. case 79:
  14033. {
  14034. eventBus.dispatch("openfile", {
  14035. source: window
  14036. });
  14037. handled = true;
  14038. }
  14039. break;
  14040. }
  14041. }
  14042. if (cmd === 3 || cmd === 10) {
  14043. switch (evt.keyCode) {
  14044. case 80:
  14045. PDFViewerApplication.requestPresentationMode();
  14046. handled = true;
  14047. PDFViewerApplication.externalServices.reportTelemetry({
  14048. type: "buttons",
  14049. data: {
  14050. id: "presentationModeKeyboard"
  14051. }
  14052. });
  14053. break;
  14054. case 71:
  14055. if (PDFViewerApplication.appConfig.toolbar) {
  14056. PDFViewerApplication.appConfig.toolbar.pageNumber.select();
  14057. handled = true;
  14058. }
  14059. break;
  14060. }
  14061. }
  14062. if (handled) {
  14063. if (ensureViewerFocused && !isViewerInPresentationMode) {
  14064. pdfViewer.focus();
  14065. }
  14066. evt.preventDefault();
  14067. return;
  14068. }
  14069. const curElement = getActiveOrFocusedElement();
  14070. const curElementTagName = curElement?.tagName.toUpperCase();
  14071. if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElementTagName === "BUTTON" && (evt.keyCode === 13 || evt.keyCode === 32) || curElement?.isContentEditable) {
  14072. if (evt.keyCode !== 27) {
  14073. return;
  14074. }
  14075. }
  14076. if (cmd === 0) {
  14077. let turnPage = 0,
  14078. turnOnlyIfPageFit = false;
  14079. switch (evt.keyCode) {
  14080. case 38:
  14081. if (PDFViewerApplication.supportsCaretBrowsingMode) {
  14082. PDFViewerApplication.moveCaret(true, false);
  14083. handled = true;
  14084. break;
  14085. }
  14086. case 33:
  14087. if (pdfViewer.isVerticalScrollbarEnabled) {
  14088. turnOnlyIfPageFit = true;
  14089. }
  14090. turnPage = -1;
  14091. break;
  14092. case 8:
  14093. if (!isViewerInPresentationMode) {
  14094. turnOnlyIfPageFit = true;
  14095. }
  14096. turnPage = -1;
  14097. break;
  14098. case 37:
  14099. if (PDFViewerApplication.supportsCaretBrowsingMode) {
  14100. return;
  14101. }
  14102. if (pdfViewer.isHorizontalScrollbarEnabled) {
  14103. turnOnlyIfPageFit = true;
  14104. }
  14105. case 75:
  14106. case 80:
  14107. turnPage = -1;
  14108. break;
  14109. case 27:
  14110. if (PDFViewerApplication.secondaryToolbar?.isOpen) {
  14111. PDFViewerApplication.secondaryToolbar.close();
  14112. handled = true;
  14113. }
  14114. if (!PDFViewerApplication.supportsIntegratedFind && PDFViewerApplication.findBar?.opened) {
  14115. PDFViewerApplication.findBar.close();
  14116. handled = true;
  14117. }
  14118. break;
  14119. case 40:
  14120. if (PDFViewerApplication.supportsCaretBrowsingMode) {
  14121. PDFViewerApplication.moveCaret(false, false);
  14122. handled = true;
  14123. break;
  14124. }
  14125. case 34:
  14126. if (pdfViewer.isVerticalScrollbarEnabled) {
  14127. turnOnlyIfPageFit = true;
  14128. }
  14129. turnPage = 1;
  14130. break;
  14131. case 13:
  14132. case 32:
  14133. if (!isViewerInPresentationMode) {
  14134. turnOnlyIfPageFit = true;
  14135. }
  14136. turnPage = 1;
  14137. break;
  14138. case 39:
  14139. if (PDFViewerApplication.supportsCaretBrowsingMode) {
  14140. return;
  14141. }
  14142. if (pdfViewer.isHorizontalScrollbarEnabled) {
  14143. turnOnlyIfPageFit = true;
  14144. }
  14145. case 74:
  14146. case 78:
  14147. turnPage = 1;
  14148. break;
  14149. case 36:
  14150. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  14151. PDFViewerApplication.page = 1;
  14152. handled = true;
  14153. ensureViewerFocused = true;
  14154. }
  14155. break;
  14156. case 35:
  14157. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  14158. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  14159. handled = true;
  14160. ensureViewerFocused = true;
  14161. }
  14162. break;
  14163. case 83:
  14164. PDFViewerApplication.pdfCursorTools?.switchTool(CursorTool.SELECT);
  14165. break;
  14166. case 72:
  14167. PDFViewerApplication.pdfCursorTools?.switchTool(CursorTool.HAND);
  14168. break;
  14169. case 82:
  14170. PDFViewerApplication.rotatePages(90);
  14171. break;
  14172. case 115:
  14173. PDFViewerApplication.pdfSidebar?.toggle();
  14174. break;
  14175. }
  14176. if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === "page-fit")) {
  14177. if (turnPage > 0) {
  14178. pdfViewer.nextPage();
  14179. } else {
  14180. pdfViewer.previousPage();
  14181. }
  14182. handled = true;
  14183. }
  14184. }
  14185. if (cmd === 4) {
  14186. switch (evt.keyCode) {
  14187. case 13:
  14188. case 32:
  14189. if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== "page-fit") {
  14190. break;
  14191. }
  14192. pdfViewer.previousPage();
  14193. handled = true;
  14194. break;
  14195. case 38:
  14196. PDFViewerApplication.moveCaret(true, true);
  14197. handled = true;
  14198. break;
  14199. case 40:
  14200. PDFViewerApplication.moveCaret(false, true);
  14201. handled = true;
  14202. break;
  14203. case 82:
  14204. PDFViewerApplication.rotatePages(-90);
  14205. break;
  14206. }
  14207. }
  14208. if (!handled && !isViewerInPresentationMode) {
  14209. if (evt.keyCode >= 33 && evt.keyCode <= 40 || evt.keyCode === 32 && curElementTagName !== "BUTTON") {
  14210. ensureViewerFocused = true;
  14211. }
  14212. }
  14213. if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) {
  14214. pdfViewer.focus();
  14215. }
  14216. if (handled) {
  14217. evt.preventDefault();
  14218. }
  14219. }
  14220. function beforeUnload(evt) {
  14221. evt.preventDefault();
  14222. evt.returnValue = "";
  14223. return false;
  14224. }
  14225. function webViewerAnnotationEditorStatesChanged(data) {
  14226. PDFViewerApplication.externalServices.updateEditorStates(data);
  14227. }
  14228. function webViewerReportTelemetry({
  14229. details
  14230. }) {
  14231. PDFViewerApplication.externalServices.reportTelemetry(details);
  14232. }
  14233. function webViewerSetPreference({
  14234. name,
  14235. value
  14236. }) {
  14237. PDFViewerApplication.preferences.set(name, value);
  14238. }
  14239. ;// CONCATENATED MODULE: ./web/viewer.js
  14240. const pdfjsVersion = "4.5.136";
  14241. const pdfjsBuild = "3a21f03b0";
  14242. const AppConstants = {
  14243. LinkTarget: LinkTarget,
  14244. RenderingStates: RenderingStates,
  14245. ScrollMode: ScrollMode,
  14246. SpreadMode: SpreadMode
  14247. };
  14248. window.PDFViewerApplication = PDFViewerApplication;
  14249. window.PDFViewerApplicationConstants = AppConstants;
  14250. window.PDFViewerApplicationOptions = AppOptions;
  14251. function getViewerConfiguration() {
  14252. return {
  14253. appContainer: document.body,
  14254. mainContainer: document.getElementById("viewerContainer"),
  14255. viewerContainer: document.getElementById("viewer"),
  14256. toolbar: {
  14257. container: document.getElementById("toolbarViewer"),
  14258. numPages: document.getElementById("numPages"),
  14259. pageNumber: document.getElementById("pageNumber"),
  14260. scaleSelect: document.getElementById("scaleSelect"),
  14261. customScaleOption: document.getElementById("customScaleOption"),
  14262. previous: document.getElementById("previous"),
  14263. next: document.getElementById("next"),
  14264. zoomIn: document.getElementById("zoomIn"),
  14265. zoomOut: document.getElementById("zoomOut"),
  14266. viewFind: document.getElementById("viewFind"),
  14267. print: document.getElementById("print"),
  14268. editorFreeTextButton: document.getElementById("editorFreeText"),
  14269. editorFreeTextParamsToolbar: document.getElementById("editorFreeTextParamsToolbar"),
  14270. editorHighlightButton: document.getElementById("editorHighlight"),
  14271. editorHighlightParamsToolbar: document.getElementById("editorHighlightParamsToolbar"),
  14272. editorHighlightColorPicker: document.getElementById("editorHighlightColorPicker"),
  14273. editorInkButton: document.getElementById("editorInk"),
  14274. editorInkParamsToolbar: document.getElementById("editorInkParamsToolbar"),
  14275. editorStampButton: document.getElementById("editorStamp"),
  14276. editorStampParamsToolbar: document.getElementById("editorStampParamsToolbar"),
  14277. download: document.getElementById("download")
  14278. },
  14279. secondaryToolbar: {
  14280. toolbar: document.getElementById("secondaryToolbar"),
  14281. toggleButton: document.getElementById("secondaryToolbarToggle"),
  14282. presentationModeButton: document.getElementById("presentationMode"),
  14283. openFileButton: document.getElementById("secondaryOpenFile"),
  14284. printButton: document.getElementById("secondaryPrint"),
  14285. downloadButton: document.getElementById("secondaryDownload"),
  14286. viewBookmarkButton: document.getElementById("viewBookmark"),
  14287. firstPageButton: document.getElementById("firstPage"),
  14288. lastPageButton: document.getElementById("lastPage"),
  14289. pageRotateCwButton: document.getElementById("pageRotateCw"),
  14290. pageRotateCcwButton: document.getElementById("pageRotateCcw"),
  14291. cursorSelectToolButton: document.getElementById("cursorSelectTool"),
  14292. cursorHandToolButton: document.getElementById("cursorHandTool"),
  14293. scrollPageButton: document.getElementById("scrollPage"),
  14294. scrollVerticalButton: document.getElementById("scrollVertical"),
  14295. scrollHorizontalButton: document.getElementById("scrollHorizontal"),
  14296. scrollWrappedButton: document.getElementById("scrollWrapped"),
  14297. spreadNoneButton: document.getElementById("spreadNone"),
  14298. spreadOddButton: document.getElementById("spreadOdd"),
  14299. spreadEvenButton: document.getElementById("spreadEven"),
  14300. documentPropertiesButton: document.getElementById("documentProperties")
  14301. },
  14302. sidebar: {
  14303. outerContainer: document.getElementById("outerContainer"),
  14304. sidebarContainer: document.getElementById("sidebarContainer"),
  14305. toggleButton: document.getElementById("sidebarToggle"),
  14306. resizer: document.getElementById("sidebarResizer"),
  14307. thumbnailButton: document.getElementById("viewThumbnail"),
  14308. outlineButton: document.getElementById("viewOutline"),
  14309. attachmentsButton: document.getElementById("viewAttachments"),
  14310. layersButton: document.getElementById("viewLayers"),
  14311. thumbnailView: document.getElementById("thumbnailView"),
  14312. outlineView: document.getElementById("outlineView"),
  14313. attachmentsView: document.getElementById("attachmentsView"),
  14314. layersView: document.getElementById("layersView"),
  14315. currentOutlineItemButton: document.getElementById("currentOutlineItem")
  14316. },
  14317. findBar: {
  14318. bar: document.getElementById("findbar"),
  14319. toggleButton: document.getElementById("viewFind"),
  14320. findField: document.getElementById("findInput"),
  14321. highlightAllCheckbox: document.getElementById("findHighlightAll"),
  14322. caseSensitiveCheckbox: document.getElementById("findMatchCase"),
  14323. matchDiacriticsCheckbox: document.getElementById("findMatchDiacritics"),
  14324. entireWordCheckbox: document.getElementById("findEntireWord"),
  14325. findMsg: document.getElementById("findMsg"),
  14326. findResultsCount: document.getElementById("findResultsCount"),
  14327. findPreviousButton: document.getElementById("findPrevious"),
  14328. findNextButton: document.getElementById("findNext")
  14329. },
  14330. passwordOverlay: {
  14331. dialog: document.getElementById("passwordDialog"),
  14332. label: document.getElementById("passwordText"),
  14333. input: document.getElementById("password"),
  14334. submitButton: document.getElementById("passwordSubmit"),
  14335. cancelButton: document.getElementById("passwordCancel")
  14336. },
  14337. documentProperties: {
  14338. dialog: document.getElementById("documentPropertiesDialog"),
  14339. closeButton: document.getElementById("documentPropertiesClose"),
  14340. fields: {
  14341. fileName: document.getElementById("fileNameField"),
  14342. fileSize: document.getElementById("fileSizeField"),
  14343. title: document.getElementById("titleField"),
  14344. author: document.getElementById("authorField"),
  14345. subject: document.getElementById("subjectField"),
  14346. keywords: document.getElementById("keywordsField"),
  14347. creationDate: document.getElementById("creationDateField"),
  14348. modificationDate: document.getElementById("modificationDateField"),
  14349. creator: document.getElementById("creatorField"),
  14350. producer: document.getElementById("producerField"),
  14351. version: document.getElementById("versionField"),
  14352. pageCount: document.getElementById("pageCountField"),
  14353. pageSize: document.getElementById("pageSizeField"),
  14354. linearized: document.getElementById("linearizedField")
  14355. }
  14356. },
  14357. altTextDialog: {
  14358. dialog: document.getElementById("altTextDialog"),
  14359. optionDescription: document.getElementById("descriptionButton"),
  14360. optionDecorative: document.getElementById("decorativeButton"),
  14361. textarea: document.getElementById("descriptionTextarea"),
  14362. cancelButton: document.getElementById("altTextCancel"),
  14363. saveButton: document.getElementById("altTextSave")
  14364. },
  14365. annotationEditorParams: {
  14366. editorFreeTextFontSize: document.getElementById("editorFreeTextFontSize"),
  14367. editorFreeTextColor: document.getElementById("editorFreeTextColor"),
  14368. editorInkColor: document.getElementById("editorInkColor"),
  14369. editorInkThickness: document.getElementById("editorInkThickness"),
  14370. editorInkOpacity: document.getElementById("editorInkOpacity"),
  14371. editorStampAddImage: document.getElementById("editorStampAddImage"),
  14372. editorFreeHighlightThickness: document.getElementById("editorFreeHighlightThickness"),
  14373. editorHighlightShowAll: document.getElementById("editorHighlightShowAll")
  14374. },
  14375. printContainer: document.getElementById("printContainer")
  14376. };
  14377. }
  14378. function webViewerLoad() {
  14379. const config = getViewerConfiguration();
  14380. const event = new CustomEvent("webviewerloaded", {
  14381. bubbles: true,
  14382. cancelable: true,
  14383. detail: {
  14384. source: window
  14385. }
  14386. });
  14387. try {
  14388. parent.document.dispatchEvent(event);
  14389. } catch (ex) {
  14390. console.error(`webviewerloaded: ${ex}`);
  14391. document.dispatchEvent(event);
  14392. }
  14393. PDFViewerApplication.run(config);
  14394. }
  14395. document.blockUnblockOnload?.(true);
  14396. if (document.readyState === "interactive" || document.readyState === "complete") {
  14397. webViewerLoad();
  14398. } else {
  14399. document.addEventListener("DOMContentLoaded", webViewerLoad, true);
  14400. }
  14401. var __webpack_exports__PDFViewerApplication = __webpack_exports__.PDFViewerApplication;
  14402. var __webpack_exports__PDFViewerApplicationConstants = __webpack_exports__.PDFViewerApplicationConstants;
  14403. var __webpack_exports__PDFViewerApplicationOptions = __webpack_exports__.PDFViewerApplicationOptions;
  14404. export { __webpack_exports__PDFViewerApplication as PDFViewerApplication, __webpack_exports__PDFViewerApplicationConstants as PDFViewerApplicationConstants, __webpack_exports__PDFViewerApplicationOptions as PDFViewerApplicationOptions };
  14405. //# sourceMappingURL=viewer.mjs.map