viewer.mjs 518 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974
  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. ;// ./web/pdfjs.js
  23. const {
  24. AbortException,
  25. AnnotationEditorLayer,
  26. AnnotationEditorParamsType,
  27. AnnotationEditorType,
  28. AnnotationEditorUIManager,
  29. AnnotationLayer,
  30. AnnotationMode,
  31. AnnotationType,
  32. build,
  33. ColorPicker,
  34. createValidAbsoluteUrl,
  35. DOMSVGFactory,
  36. DrawLayer,
  37. FeatureTest,
  38. fetchData,
  39. getDocument,
  40. getFilenameFromUrl,
  41. getPdfFilenameFromUrl: pdfjs_getPdfFilenameFromUrl,
  42. getUuid,
  43. getXfaPageViewport,
  44. GlobalWorkerOptions,
  45. ImageKind,
  46. InvalidPDFException,
  47. isDataScheme,
  48. isPdfFile,
  49. isValidExplicitDest,
  50. MathClamp,
  51. noContextMenu,
  52. normalizeUnicode,
  53. OPS,
  54. OutputScale,
  55. PasswordResponses,
  56. PDFDataRangeTransport,
  57. PDFDateString,
  58. PDFWorker,
  59. PermissionFlag,
  60. PixelsPerInch,
  61. RenderingCancelledException,
  62. ResponseException,
  63. setLayerDimensions,
  64. shadow,
  65. SignatureExtractor,
  66. stopEvent,
  67. SupportedImageMimeTypes,
  68. TextLayer,
  69. TouchManager,
  70. updateUrlHash,
  71. Util,
  72. VerbosityLevel,
  73. version,
  74. XfaLayer
  75. } = globalThis.pdfjsLib;
  76. ;// ./web/ui_utils.js
  77. const DEFAULT_SCALE_VALUE = "auto";
  78. const DEFAULT_SCALE = 1.0;
  79. const DEFAULT_SCALE_DELTA = 1.1;
  80. const MIN_SCALE = 0.1;
  81. const MAX_SCALE = 10.0;
  82. const UNKNOWN_SCALE = 0;
  83. const MAX_AUTO_SCALE = 1.25;
  84. const SCROLLBAR_PADDING = 40;
  85. const VERTICAL_PADDING = 5;
  86. const RenderingStates = {
  87. INITIAL: 0,
  88. RUNNING: 1,
  89. PAUSED: 2,
  90. FINISHED: 3
  91. };
  92. const PresentationModeState = {
  93. UNKNOWN: 0,
  94. NORMAL: 1,
  95. CHANGING: 2,
  96. FULLSCREEN: 3
  97. };
  98. const SidebarView = {
  99. UNKNOWN: -1,
  100. NONE: 0,
  101. THUMBS: 1,
  102. OUTLINE: 2,
  103. ATTACHMENTS: 3,
  104. LAYERS: 4
  105. };
  106. const TextLayerMode = {
  107. DISABLE: 0,
  108. ENABLE: 1,
  109. ENABLE_PERMISSIONS: 2
  110. };
  111. const ScrollMode = {
  112. UNKNOWN: -1,
  113. VERTICAL: 0,
  114. HORIZONTAL: 1,
  115. WRAPPED: 2,
  116. PAGE: 3
  117. };
  118. const SpreadMode = {
  119. UNKNOWN: -1,
  120. NONE: 0,
  121. ODD: 1,
  122. EVEN: 2
  123. };
  124. const CursorTool = {
  125. SELECT: 0,
  126. HAND: 1,
  127. ZOOM: 2
  128. };
  129. const AutoPrintRegExp = /\bprint\s*\(/;
  130. function scrollIntoView(element, spot, scrollMatches = false) {
  131. let parent = element.offsetParent;
  132. if (!parent) {
  133. console.error("offsetParent is not set -- cannot scroll");
  134. return;
  135. }
  136. let offsetY = element.offsetTop + element.clientTop;
  137. let offsetX = element.offsetLeft + element.clientLeft;
  138. while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) {
  139. offsetY += parent.offsetTop;
  140. offsetX += parent.offsetLeft;
  141. parent = parent.offsetParent;
  142. if (!parent) {
  143. return;
  144. }
  145. }
  146. if (spot) {
  147. if (spot.top !== undefined) {
  148. offsetY += spot.top;
  149. }
  150. if (spot.left !== undefined) {
  151. offsetX += spot.left;
  152. parent.scrollLeft = offsetX;
  153. }
  154. }
  155. parent.scrollTop = offsetY;
  156. }
  157. function watchScroll(viewAreaElement, callback, abortSignal = undefined) {
  158. const debounceScroll = function (evt) {
  159. if (rAF) {
  160. return;
  161. }
  162. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  163. rAF = null;
  164. const currentX = viewAreaElement.scrollLeft;
  165. const lastX = state.lastX;
  166. if (currentX !== lastX) {
  167. state.right = currentX > lastX;
  168. }
  169. state.lastX = currentX;
  170. const currentY = viewAreaElement.scrollTop;
  171. const lastY = state.lastY;
  172. if (currentY !== lastY) {
  173. state.down = currentY > lastY;
  174. }
  175. state.lastY = currentY;
  176. callback(state);
  177. });
  178. };
  179. const state = {
  180. right: true,
  181. down: true,
  182. lastX: viewAreaElement.scrollLeft,
  183. lastY: viewAreaElement.scrollTop,
  184. _eventHandler: debounceScroll
  185. };
  186. let rAF = null;
  187. viewAreaElement.addEventListener("scroll", debounceScroll, {
  188. useCapture: true,
  189. signal: abortSignal
  190. });
  191. abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), {
  192. once: true
  193. });
  194. return state;
  195. }
  196. function parseQueryString(query) {
  197. const params = new Map();
  198. for (const [key, value] of new URLSearchParams(query)) {
  199. params.set(key.toLowerCase(), value);
  200. }
  201. return params;
  202. }
  203. const InvisibleCharsRegExp = /[\x00-\x1F]/g;
  204. function removeNullCharacters(str, replaceInvisible = false) {
  205. if (!InvisibleCharsRegExp.test(str)) {
  206. return str;
  207. }
  208. if (replaceInvisible) {
  209. return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " ");
  210. }
  211. return str.replaceAll("\x00", "");
  212. }
  213. function binarySearchFirstItem(items, condition, start = 0) {
  214. let minIndex = start;
  215. let maxIndex = items.length - 1;
  216. if (maxIndex < 0 || !condition(items[maxIndex])) {
  217. return items.length;
  218. }
  219. if (condition(items[minIndex])) {
  220. return minIndex;
  221. }
  222. while (minIndex < maxIndex) {
  223. const currentIndex = minIndex + maxIndex >> 1;
  224. const currentItem = items[currentIndex];
  225. if (condition(currentItem)) {
  226. maxIndex = currentIndex;
  227. } else {
  228. minIndex = currentIndex + 1;
  229. }
  230. }
  231. return minIndex;
  232. }
  233. function approximateFraction(x) {
  234. if (Math.floor(x) === x) {
  235. return [x, 1];
  236. }
  237. const xinv = 1 / x;
  238. const limit = 8;
  239. if (xinv > limit) {
  240. return [1, limit];
  241. } else if (Math.floor(xinv) === xinv) {
  242. return [1, xinv];
  243. }
  244. const x_ = x > 1 ? xinv : x;
  245. let a = 0,
  246. b = 1,
  247. c = 1,
  248. d = 1;
  249. while (true) {
  250. const p = a + c,
  251. q = b + d;
  252. if (q > limit) {
  253. break;
  254. }
  255. if (x_ <= p / q) {
  256. c = p;
  257. d = q;
  258. } else {
  259. a = p;
  260. b = q;
  261. }
  262. }
  263. let result;
  264. if (x_ - a / b < c / d - x_) {
  265. result = x_ === x ? [a, b] : [b, a];
  266. } else {
  267. result = x_ === x ? [c, d] : [d, c];
  268. }
  269. return result;
  270. }
  271. function floorToDivide(x, div) {
  272. return x - x % div;
  273. }
  274. function getPageSizeInches({
  275. view,
  276. userUnit,
  277. rotate
  278. }) {
  279. const [x1, y1, x2, y2] = view;
  280. const changeOrientation = rotate % 180 !== 0;
  281. const width = (x2 - x1) / 72 * userUnit;
  282. const height = (y2 - y1) / 72 * userUnit;
  283. return {
  284. width: changeOrientation ? height : width,
  285. height: changeOrientation ? width : height
  286. };
  287. }
  288. function backtrackBeforeAllVisibleElements(index, views, top) {
  289. if (index < 2) {
  290. return index;
  291. }
  292. let elt = views[index].div;
  293. let pageTop = elt.offsetTop + elt.clientTop;
  294. if (pageTop >= top) {
  295. elt = views[index - 1].div;
  296. pageTop = elt.offsetTop + elt.clientTop;
  297. }
  298. for (let i = index - 2; i >= 0; --i) {
  299. elt = views[i].div;
  300. if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) {
  301. break;
  302. }
  303. index = i;
  304. }
  305. return index;
  306. }
  307. function getVisibleElements({
  308. scrollEl,
  309. views,
  310. sortByVisibility = false,
  311. horizontal = false,
  312. rtl = false
  313. }) {
  314. const top = scrollEl.scrollTop,
  315. bottom = top + scrollEl.clientHeight;
  316. const left = scrollEl.scrollLeft,
  317. right = left + scrollEl.clientWidth;
  318. function isElementBottomAfterViewTop(view) {
  319. const element = view.div;
  320. const elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  321. return elementBottom > top;
  322. }
  323. function isElementNextAfterViewHorizontally(view) {
  324. const element = view.div;
  325. const elementLeft = element.offsetLeft + element.clientLeft;
  326. const elementRight = elementLeft + element.clientWidth;
  327. return rtl ? elementLeft < right : elementRight > left;
  328. }
  329. const visible = [],
  330. ids = new Set(),
  331. numViews = views.length;
  332. let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop);
  333. if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) {
  334. firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top);
  335. }
  336. let lastEdge = horizontal ? right : -1;
  337. for (let i = firstVisibleElementInd; i < numViews; i++) {
  338. const view = views[i],
  339. element = view.div;
  340. const currentWidth = element.offsetLeft + element.clientLeft;
  341. const currentHeight = element.offsetTop + element.clientTop;
  342. const viewWidth = element.clientWidth,
  343. viewHeight = element.clientHeight;
  344. const viewRight = currentWidth + viewWidth;
  345. const viewBottom = currentHeight + viewHeight;
  346. if (lastEdge === -1) {
  347. if (viewBottom >= bottom) {
  348. lastEdge = viewBottom;
  349. }
  350. } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) {
  351. break;
  352. }
  353. if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) {
  354. continue;
  355. }
  356. const minY = Math.max(0, top - currentHeight);
  357. const minX = Math.max(0, left - currentWidth);
  358. const hiddenHeight = minY + Math.max(0, viewBottom - bottom);
  359. const hiddenWidth = minX + Math.max(0, viewRight - right);
  360. const fractionHeight = (viewHeight - hiddenHeight) / viewHeight,
  361. fractionWidth = (viewWidth - hiddenWidth) / viewWidth;
  362. const percent = fractionHeight * fractionWidth * 100 | 0;
  363. visible.push({
  364. id: view.id,
  365. x: currentWidth,
  366. y: currentHeight,
  367. visibleArea: percent === 100 ? null : {
  368. minX,
  369. minY,
  370. maxX: Math.min(viewRight, right) - currentWidth,
  371. maxY: Math.min(viewBottom, bottom) - currentHeight
  372. },
  373. view,
  374. percent,
  375. widthPercent: fractionWidth * 100 | 0
  376. });
  377. ids.add(view.id);
  378. }
  379. const first = visible[0],
  380. last = visible.at(-1);
  381. if (sortByVisibility) {
  382. visible.sort(function (a, b) {
  383. const pc = a.percent - b.percent;
  384. if (Math.abs(pc) > 0.001) {
  385. return -pc;
  386. }
  387. return a.id - b.id;
  388. });
  389. }
  390. return {
  391. first,
  392. last,
  393. views: visible,
  394. ids
  395. };
  396. }
  397. function normalizeWheelEventDirection(evt) {
  398. let delta = Math.hypot(evt.deltaX, evt.deltaY);
  399. const angle = Math.atan2(evt.deltaY, evt.deltaX);
  400. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  401. delta = -delta;
  402. }
  403. return delta;
  404. }
  405. function normalizeWheelEventDelta(evt) {
  406. const deltaMode = evt.deltaMode;
  407. let delta = normalizeWheelEventDirection(evt);
  408. const MOUSE_PIXELS_PER_LINE = 30;
  409. const MOUSE_LINES_PER_PAGE = 30;
  410. if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
  411. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  412. } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) {
  413. delta /= MOUSE_LINES_PER_PAGE;
  414. }
  415. return delta;
  416. }
  417. function isValidRotation(angle) {
  418. return Number.isInteger(angle) && angle % 90 === 0;
  419. }
  420. function isValidScrollMode(mode) {
  421. return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN;
  422. }
  423. function isValidSpreadMode(mode) {
  424. return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN;
  425. }
  426. function isPortraitOrientation(size) {
  427. return size.width <= size.height;
  428. }
  429. const animationStarted = new Promise(function (resolve) {
  430. window.requestAnimationFrame(resolve);
  431. });
  432. const docStyle = document.documentElement.style;
  433. class ProgressBar {
  434. #classList = null;
  435. #disableAutoFetchTimeout = null;
  436. #percent = 0;
  437. #style = null;
  438. #visible = true;
  439. constructor(bar) {
  440. this.#classList = bar.classList;
  441. this.#style = bar.style;
  442. }
  443. get percent() {
  444. return this.#percent;
  445. }
  446. set percent(val) {
  447. this.#percent = MathClamp(val, 0, 100);
  448. if (isNaN(val)) {
  449. this.#classList.add("indeterminate");
  450. return;
  451. }
  452. this.#classList.remove("indeterminate");
  453. this.#style.setProperty("--progressBar-percent", `${this.#percent}%`);
  454. }
  455. setWidth(viewer) {
  456. if (!viewer) {
  457. return;
  458. }
  459. const container = viewer.parentNode;
  460. const scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  461. if (scrollbarWidth > 0) {
  462. this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`);
  463. }
  464. }
  465. setDisableAutoFetch(delay = 5000) {
  466. if (this.#percent === 100 || isNaN(this.#percent)) {
  467. return;
  468. }
  469. if (this.#disableAutoFetchTimeout) {
  470. clearTimeout(this.#disableAutoFetchTimeout);
  471. }
  472. this.show();
  473. this.#disableAutoFetchTimeout = setTimeout(() => {
  474. this.#disableAutoFetchTimeout = null;
  475. this.hide();
  476. }, delay);
  477. }
  478. hide() {
  479. if (!this.#visible) {
  480. return;
  481. }
  482. this.#visible = false;
  483. this.#classList.add("hidden");
  484. }
  485. show() {
  486. if (this.#visible) {
  487. return;
  488. }
  489. this.#visible = true;
  490. this.#classList.remove("hidden");
  491. }
  492. }
  493. function getActiveOrFocusedElement() {
  494. let curRoot = document;
  495. let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus");
  496. while (curActiveOrFocused?.shadowRoot) {
  497. curRoot = curActiveOrFocused.shadowRoot;
  498. curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus");
  499. }
  500. return curActiveOrFocused;
  501. }
  502. function apiPageLayoutToViewerModes(layout) {
  503. let scrollMode = ScrollMode.VERTICAL,
  504. spreadMode = SpreadMode.NONE;
  505. switch (layout) {
  506. case "SinglePage":
  507. scrollMode = ScrollMode.PAGE;
  508. break;
  509. case "OneColumn":
  510. break;
  511. case "TwoPageLeft":
  512. scrollMode = ScrollMode.PAGE;
  513. case "TwoColumnLeft":
  514. spreadMode = SpreadMode.ODD;
  515. break;
  516. case "TwoPageRight":
  517. scrollMode = ScrollMode.PAGE;
  518. case "TwoColumnRight":
  519. spreadMode = SpreadMode.EVEN;
  520. break;
  521. }
  522. return {
  523. scrollMode,
  524. spreadMode
  525. };
  526. }
  527. function apiPageModeToSidebarView(mode) {
  528. switch (mode) {
  529. case "UseNone":
  530. return SidebarView.NONE;
  531. case "UseThumbs":
  532. return SidebarView.THUMBS;
  533. case "UseOutlines":
  534. return SidebarView.OUTLINE;
  535. case "UseAttachments":
  536. return SidebarView.ATTACHMENTS;
  537. case "UseOC":
  538. return SidebarView.LAYERS;
  539. }
  540. return SidebarView.NONE;
  541. }
  542. function toggleCheckedBtn(button, toggle, view = null) {
  543. button.classList.toggle("toggled", toggle);
  544. button.setAttribute("aria-checked", toggle);
  545. view?.classList.toggle("hidden", !toggle);
  546. }
  547. function toggleExpandedBtn(button, toggle, view = null) {
  548. button.classList.toggle("toggled", toggle);
  549. button.setAttribute("aria-expanded", toggle);
  550. view?.classList.toggle("hidden", !toggle);
  551. }
  552. const calcRound = function () {
  553. const e = document.createElement("div");
  554. e.style.width = "round(down, calc(1.6666666666666665 * 792px), 1px)";
  555. return e.style.width === "calc(1320px)" ? Math.fround : x => x;
  556. }();
  557. ;// ./web/app_options.js
  558. {
  559. var compatParams = new Map();
  560. const userAgent = navigator.userAgent || "";
  561. const platform = navigator.platform || "";
  562. const maxTouchPoints = navigator.maxTouchPoints || 1;
  563. const isAndroid = /Android/.test(userAgent);
  564. const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1;
  565. (function () {
  566. if (isIOS || isAndroid) {
  567. compatParams.set("maxCanvasPixels", 5242880);
  568. }
  569. })();
  570. (function () {
  571. if (isAndroid) {
  572. compatParams.set("useSystemFonts", false);
  573. }
  574. })();
  575. }
  576. const OptionKind = {
  577. BROWSER: 0x01,
  578. VIEWER: 0x02,
  579. API: 0x04,
  580. WORKER: 0x08,
  581. EVENT_DISPATCH: 0x10,
  582. PREFERENCE: 0x80
  583. };
  584. const Type = {
  585. BOOLEAN: 0x01,
  586. NUMBER: 0x02,
  587. OBJECT: 0x04,
  588. STRING: 0x08,
  589. UNDEFINED: 0x10
  590. };
  591. const defaultOptions = {
  592. allowedGlobalEvents: {
  593. value: null,
  594. kind: OptionKind.BROWSER
  595. },
  596. canvasMaxAreaInBytes: {
  597. value: -1,
  598. kind: OptionKind.BROWSER + OptionKind.API
  599. },
  600. isInAutomation: {
  601. value: false,
  602. kind: OptionKind.BROWSER
  603. },
  604. localeProperties: {
  605. value: {
  606. lang: navigator.language || "en-US"
  607. },
  608. kind: OptionKind.BROWSER
  609. },
  610. maxCanvasDim: {
  611. value: 32767,
  612. kind: OptionKind.BROWSER + OptionKind.VIEWER
  613. },
  614. nimbusDataStr: {
  615. value: "",
  616. kind: OptionKind.BROWSER
  617. },
  618. supportsCaretBrowsingMode: {
  619. value: false,
  620. kind: OptionKind.BROWSER
  621. },
  622. supportsDocumentFonts: {
  623. value: true,
  624. kind: OptionKind.BROWSER
  625. },
  626. supportsIntegratedFind: {
  627. value: false,
  628. kind: OptionKind.BROWSER
  629. },
  630. supportsMouseWheelZoomCtrlKey: {
  631. value: true,
  632. kind: OptionKind.BROWSER
  633. },
  634. supportsMouseWheelZoomMetaKey: {
  635. value: true,
  636. kind: OptionKind.BROWSER
  637. },
  638. supportsPinchToZoom: {
  639. value: true,
  640. kind: OptionKind.BROWSER
  641. },
  642. supportsPrinting: {
  643. value: true,
  644. kind: OptionKind.BROWSER
  645. },
  646. toolbarDensity: {
  647. value: 0,
  648. kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH
  649. },
  650. altTextLearnMoreUrl: {
  651. value: "",
  652. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  653. },
  654. annotationEditorMode: {
  655. value: 0,
  656. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  657. },
  658. annotationMode: {
  659. value: 2,
  660. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  661. },
  662. cursorToolOnLoad: {
  663. value: 0,
  664. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  665. },
  666. debuggerSrc: {
  667. value: "./debugger.mjs",
  668. kind: OptionKind.VIEWER
  669. },
  670. defaultZoomDelay: {
  671. value: 400,
  672. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  673. },
  674. defaultZoomValue: {
  675. value: "",
  676. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  677. },
  678. disableHistory: {
  679. value: false,
  680. kind: OptionKind.VIEWER
  681. },
  682. disablePageLabels: {
  683. value: false,
  684. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  685. },
  686. enableAltText: {
  687. value: false,
  688. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  689. },
  690. enableAltTextModelDownload: {
  691. value: true,
  692. kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH
  693. },
  694. enableAutoLinking: {
  695. value: true,
  696. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  697. },
  698. enableDetailCanvas: {
  699. value: true,
  700. kind: OptionKind.VIEWER
  701. },
  702. enableGuessAltText: {
  703. value: true,
  704. kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH
  705. },
  706. enableHighlightFloatingButton: {
  707. value: false,
  708. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  709. },
  710. enableNewAltTextWhenAddingImage: {
  711. value: true,
  712. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  713. },
  714. enablePermissions: {
  715. value: false,
  716. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  717. },
  718. enablePrintAutoRotate: {
  719. value: true,
  720. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  721. },
  722. enableScripting: {
  723. value: true,
  724. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  725. },
  726. enableSignatureEditor: {
  727. value: false,
  728. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  729. },
  730. enableUpdatedAddImage: {
  731. value: false,
  732. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  733. },
  734. externalLinkRel: {
  735. value: "noopener noreferrer nofollow",
  736. kind: OptionKind.VIEWER
  737. },
  738. externalLinkTarget: {
  739. value: 0,
  740. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  741. },
  742. highlightEditorColors: {
  743. value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F",
  744. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  745. },
  746. historyUpdateUrl: {
  747. value: false,
  748. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  749. },
  750. ignoreDestinationZoom: {
  751. value: false,
  752. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  753. },
  754. imageResourcesPath: {
  755. value: "./images/",
  756. kind: OptionKind.VIEWER
  757. },
  758. maxCanvasPixels: {
  759. value: 2 ** 25,
  760. kind: OptionKind.VIEWER
  761. },
  762. forcePageColors: {
  763. value: false,
  764. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  765. },
  766. pageColorsBackground: {
  767. value: "Canvas",
  768. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  769. },
  770. pageColorsForeground: {
  771. value: "CanvasText",
  772. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  773. },
  774. pdfBugEnabled: {
  775. value: false,
  776. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  777. },
  778. printResolution: {
  779. value: 150,
  780. kind: OptionKind.VIEWER
  781. },
  782. sidebarViewOnLoad: {
  783. value: -1,
  784. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  785. },
  786. scrollModeOnLoad: {
  787. value: -1,
  788. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  789. },
  790. spreadModeOnLoad: {
  791. value: -1,
  792. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  793. },
  794. textLayerMode: {
  795. value: 1,
  796. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  797. },
  798. viewerCssTheme: {
  799. value: 0,
  800. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  801. },
  802. viewOnLoad: {
  803. value: 0,
  804. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  805. },
  806. cMapPacked: {
  807. value: true,
  808. kind: OptionKind.API
  809. },
  810. cMapUrl: {
  811. value: "../web/cmaps/",
  812. kind: OptionKind.API
  813. },
  814. disableAutoFetch: {
  815. value: false,
  816. kind: OptionKind.API + OptionKind.PREFERENCE
  817. },
  818. disableFontFace: {
  819. value: false,
  820. kind: OptionKind.API + OptionKind.PREFERENCE
  821. },
  822. disableRange: {
  823. value: false,
  824. kind: OptionKind.API + OptionKind.PREFERENCE
  825. },
  826. disableStream: {
  827. value: false,
  828. kind: OptionKind.API + OptionKind.PREFERENCE
  829. },
  830. docBaseUrl: {
  831. value: "",
  832. kind: OptionKind.API
  833. },
  834. enableHWA: {
  835. value: true,
  836. kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE
  837. },
  838. enableXfa: {
  839. value: true,
  840. kind: OptionKind.API + OptionKind.PREFERENCE
  841. },
  842. fontExtraProperties: {
  843. value: false,
  844. kind: OptionKind.API
  845. },
  846. iccUrl: {
  847. value: "../web/iccs/",
  848. kind: OptionKind.API
  849. },
  850. isEvalSupported: {
  851. value: true,
  852. kind: OptionKind.API
  853. },
  854. isOffscreenCanvasSupported: {
  855. value: true,
  856. kind: OptionKind.API
  857. },
  858. maxImageSize: {
  859. value: -1,
  860. kind: OptionKind.API
  861. },
  862. pdfBug: {
  863. value: false,
  864. kind: OptionKind.API
  865. },
  866. standardFontDataUrl: {
  867. value: "../web/standard_fonts/",
  868. kind: OptionKind.API
  869. },
  870. useSystemFonts: {
  871. value: undefined,
  872. kind: OptionKind.API,
  873. type: Type.BOOLEAN + Type.UNDEFINED
  874. },
  875. verbosity: {
  876. value: 1,
  877. kind: OptionKind.API
  878. },
  879. wasmUrl: {
  880. value: "../web/wasm/",
  881. kind: OptionKind.API
  882. },
  883. workerPort: {
  884. value: null,
  885. kind: OptionKind.WORKER
  886. },
  887. workerSrc: {
  888. value: "../build/pdf.worker.mjs",
  889. kind: OptionKind.WORKER
  890. }
  891. };
  892. {
  893. defaultOptions.defaultUrl = {
  894. value: "compressed.tracemonkey-pldi-09.pdf",
  895. kind: OptionKind.VIEWER
  896. };
  897. defaultOptions.sandboxBundleSrc = {
  898. value: "../build/pdf.sandbox.mjs",
  899. kind: OptionKind.VIEWER
  900. };
  901. defaultOptions.enableFakeMLManager = {
  902. value: true,
  903. kind: OptionKind.VIEWER
  904. };
  905. }
  906. {
  907. defaultOptions.disablePreferences = {
  908. value: false,
  909. kind: OptionKind.VIEWER
  910. };
  911. }
  912. class AppOptions {
  913. static eventBus;
  914. static #opts = new Map();
  915. static {
  916. for (const name in defaultOptions) {
  917. this.#opts.set(name, defaultOptions[name].value);
  918. }
  919. for (const [name, value] of compatParams) {
  920. this.#opts.set(name, value);
  921. }
  922. this._hasInvokedSet = false;
  923. this._checkDisablePreferences = () => {
  924. if (this.get("disablePreferences")) {
  925. return true;
  926. }
  927. if (this._hasInvokedSet) {
  928. console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.');
  929. }
  930. return false;
  931. };
  932. }
  933. static get(name) {
  934. return this.#opts.get(name);
  935. }
  936. static getAll(kind = null, defaultOnly = false) {
  937. const options = Object.create(null);
  938. for (const name in defaultOptions) {
  939. const defaultOpt = defaultOptions[name];
  940. if (kind && !(kind & defaultOpt.kind)) {
  941. continue;
  942. }
  943. options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value;
  944. }
  945. return options;
  946. }
  947. static set(name, value) {
  948. this.setAll({
  949. [name]: value
  950. });
  951. }
  952. static setAll(options, prefs = false) {
  953. this._hasInvokedSet ||= true;
  954. let events;
  955. for (const name in options) {
  956. const defaultOpt = defaultOptions[name],
  957. userOpt = options[name];
  958. if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) {
  959. continue;
  960. }
  961. const {
  962. kind
  963. } = defaultOpt;
  964. if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) {
  965. continue;
  966. }
  967. if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) {
  968. (events ||= new Map()).set(name, userOpt);
  969. }
  970. this.#opts.set(name, userOpt);
  971. }
  972. if (events) {
  973. for (const [name, value] of events) {
  974. this.eventBus.dispatch(name.toLowerCase(), {
  975. source: this,
  976. value
  977. });
  978. }
  979. }
  980. }
  981. }
  982. ;// ./web/pdf_link_service.js
  983. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  984. const LinkTarget = {
  985. NONE: 0,
  986. SELF: 1,
  987. BLANK: 2,
  988. PARENT: 3,
  989. TOP: 4
  990. };
  991. class PDFLinkService {
  992. externalLinkEnabled = true;
  993. constructor({
  994. eventBus,
  995. externalLinkTarget = null,
  996. externalLinkRel = null,
  997. ignoreDestinationZoom = false
  998. } = {}) {
  999. this.eventBus = eventBus;
  1000. this.externalLinkTarget = externalLinkTarget;
  1001. this.externalLinkRel = externalLinkRel;
  1002. this._ignoreDestinationZoom = ignoreDestinationZoom;
  1003. this.baseUrl = null;
  1004. this.pdfDocument = null;
  1005. this.pdfViewer = null;
  1006. this.pdfHistory = null;
  1007. }
  1008. setDocument(pdfDocument, baseUrl = null) {
  1009. this.baseUrl = baseUrl;
  1010. this.pdfDocument = pdfDocument;
  1011. }
  1012. setViewer(pdfViewer) {
  1013. this.pdfViewer = pdfViewer;
  1014. }
  1015. setHistory(pdfHistory) {
  1016. this.pdfHistory = pdfHistory;
  1017. }
  1018. get pagesCount() {
  1019. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  1020. }
  1021. get page() {
  1022. return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1;
  1023. }
  1024. set page(value) {
  1025. if (this.pdfDocument) {
  1026. this.pdfViewer.currentPageNumber = value;
  1027. }
  1028. }
  1029. get rotation() {
  1030. return this.pdfDocument ? this.pdfViewer.pagesRotation : 0;
  1031. }
  1032. set rotation(value) {
  1033. if (this.pdfDocument) {
  1034. this.pdfViewer.pagesRotation = value;
  1035. }
  1036. }
  1037. get isInPresentationMode() {
  1038. return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false;
  1039. }
  1040. async goToDestination(dest) {
  1041. if (!this.pdfDocument) {
  1042. return;
  1043. }
  1044. let namedDest, explicitDest, pageNumber;
  1045. if (typeof dest === "string") {
  1046. namedDest = dest;
  1047. explicitDest = await this.pdfDocument.getDestination(dest);
  1048. } else {
  1049. namedDest = null;
  1050. explicitDest = await dest;
  1051. }
  1052. if (!Array.isArray(explicitDest)) {
  1053. console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`);
  1054. return;
  1055. }
  1056. const [destRef] = explicitDest;
  1057. if (destRef && typeof destRef === "object") {
  1058. pageNumber = this.pdfDocument.cachedPageNumber(destRef);
  1059. if (!pageNumber) {
  1060. try {
  1061. pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1;
  1062. } catch {
  1063. console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`);
  1064. return;
  1065. }
  1066. }
  1067. } else if (Number.isInteger(destRef)) {
  1068. pageNumber = destRef + 1;
  1069. }
  1070. if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
  1071. console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`);
  1072. return;
  1073. }
  1074. if (this.pdfHistory) {
  1075. this.pdfHistory.pushCurrentPosition();
  1076. this.pdfHistory.push({
  1077. namedDest,
  1078. explicitDest,
  1079. pageNumber
  1080. });
  1081. }
  1082. this.pdfViewer.scrollPageIntoView({
  1083. pageNumber,
  1084. destArray: explicitDest,
  1085. ignoreDestinationZoom: this._ignoreDestinationZoom
  1086. });
  1087. }
  1088. goToPage(val) {
  1089. if (!this.pdfDocument) {
  1090. return;
  1091. }
  1092. const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0;
  1093. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  1094. console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`);
  1095. return;
  1096. }
  1097. if (this.pdfHistory) {
  1098. this.pdfHistory.pushCurrentPosition();
  1099. this.pdfHistory.pushPage(pageNumber);
  1100. }
  1101. this.pdfViewer.scrollPageIntoView({
  1102. pageNumber
  1103. });
  1104. }
  1105. addLinkAttributes(link, url, newWindow = false) {
  1106. if (!url || typeof url !== "string") {
  1107. throw new Error('A valid "url" parameter must provided.');
  1108. }
  1109. const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget,
  1110. rel = this.externalLinkRel;
  1111. if (this.externalLinkEnabled) {
  1112. link.href = link.title = url;
  1113. } else {
  1114. link.href = "";
  1115. link.title = `Disabled: ${url}`;
  1116. link.onclick = () => false;
  1117. }
  1118. let targetStr = "";
  1119. switch (target) {
  1120. case LinkTarget.NONE:
  1121. break;
  1122. case LinkTarget.SELF:
  1123. targetStr = "_self";
  1124. break;
  1125. case LinkTarget.BLANK:
  1126. targetStr = "_blank";
  1127. break;
  1128. case LinkTarget.PARENT:
  1129. targetStr = "_parent";
  1130. break;
  1131. case LinkTarget.TOP:
  1132. targetStr = "_top";
  1133. break;
  1134. }
  1135. link.target = targetStr;
  1136. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  1137. }
  1138. getDestinationHash(dest) {
  1139. if (typeof dest === "string") {
  1140. if (dest.length > 0) {
  1141. return this.getAnchorUrl("#" + escape(dest));
  1142. }
  1143. } else if (Array.isArray(dest)) {
  1144. const str = JSON.stringify(dest);
  1145. if (str.length > 0) {
  1146. return this.getAnchorUrl("#" + escape(str));
  1147. }
  1148. }
  1149. return this.getAnchorUrl("");
  1150. }
  1151. getAnchorUrl(anchor) {
  1152. return this.baseUrl ? this.baseUrl + anchor : anchor;
  1153. }
  1154. setHash(hash) {
  1155. if (!this.pdfDocument) {
  1156. return;
  1157. }
  1158. let pageNumber, dest;
  1159. if (hash.includes("=")) {
  1160. const params = parseQueryString(hash);
  1161. if (params.has("search")) {
  1162. const query = params.get("search").replaceAll('"', ""),
  1163. phrase = params.get("phrase") === "true";
  1164. this.eventBus.dispatch("findfromurlhash", {
  1165. source: this,
  1166. query: phrase ? query : query.match(/\S+/g)
  1167. });
  1168. }
  1169. if (params.has("page")) {
  1170. pageNumber = params.get("page") | 0 || 1;
  1171. }
  1172. if (params.has("zoom")) {
  1173. const zoomArgs = params.get("zoom").split(",");
  1174. const zoomArg = zoomArgs[0];
  1175. const zoomArgNumber = parseFloat(zoomArg);
  1176. if (!zoomArg.includes("Fit")) {
  1177. dest = [null, {
  1178. name: "XYZ"
  1179. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg];
  1180. } else if (zoomArg === "Fit" || zoomArg === "FitB") {
  1181. dest = [null, {
  1182. name: zoomArg
  1183. }];
  1184. } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") {
  1185. dest = [null, {
  1186. name: zoomArg
  1187. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null];
  1188. } else if (zoomArg === "FitR") {
  1189. if (zoomArgs.length !== 5) {
  1190. console.error('PDFLinkService.setHash: Not enough parameters for "FitR".');
  1191. } else {
  1192. dest = [null, {
  1193. name: zoomArg
  1194. }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0];
  1195. }
  1196. } else {
  1197. console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`);
  1198. }
  1199. }
  1200. if (dest) {
  1201. this.pdfViewer.scrollPageIntoView({
  1202. pageNumber: pageNumber || this.page,
  1203. destArray: dest,
  1204. allowNegativeOffset: true
  1205. });
  1206. } else if (pageNumber) {
  1207. this.page = pageNumber;
  1208. }
  1209. if (params.has("pagemode")) {
  1210. this.eventBus.dispatch("pagemode", {
  1211. source: this,
  1212. mode: params.get("pagemode")
  1213. });
  1214. }
  1215. if (params.has("nameddest")) {
  1216. this.goToDestination(params.get("nameddest"));
  1217. }
  1218. return;
  1219. }
  1220. dest = unescape(hash);
  1221. try {
  1222. dest = JSON.parse(dest);
  1223. if (!Array.isArray(dest)) {
  1224. dest = dest.toString();
  1225. }
  1226. } catch {}
  1227. if (typeof dest === "string" || isValidExplicitDest(dest)) {
  1228. this.goToDestination(dest);
  1229. return;
  1230. }
  1231. console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`);
  1232. }
  1233. executeNamedAction(action) {
  1234. if (!this.pdfDocument) {
  1235. return;
  1236. }
  1237. switch (action) {
  1238. case "GoBack":
  1239. this.pdfHistory?.back();
  1240. break;
  1241. case "GoForward":
  1242. this.pdfHistory?.forward();
  1243. break;
  1244. case "NextPage":
  1245. this.pdfViewer.nextPage();
  1246. break;
  1247. case "PrevPage":
  1248. this.pdfViewer.previousPage();
  1249. break;
  1250. case "LastPage":
  1251. this.page = this.pagesCount;
  1252. break;
  1253. case "FirstPage":
  1254. this.page = 1;
  1255. break;
  1256. default:
  1257. break;
  1258. }
  1259. this.eventBus.dispatch("namedaction", {
  1260. source: this,
  1261. action
  1262. });
  1263. }
  1264. async executeSetOCGState(action) {
  1265. if (!this.pdfDocument) {
  1266. return;
  1267. }
  1268. const pdfDocument = this.pdfDocument,
  1269. optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;
  1270. if (pdfDocument !== this.pdfDocument) {
  1271. return;
  1272. }
  1273. optionalContentConfig.setOCGState(action);
  1274. this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig);
  1275. }
  1276. }
  1277. class SimpleLinkService extends PDFLinkService {
  1278. setDocument(pdfDocument, baseUrl = null) {}
  1279. }
  1280. ;// ./web/event_utils.js
  1281. const WaitOnType = {
  1282. EVENT: "event",
  1283. TIMEOUT: "timeout"
  1284. };
  1285. async function waitOnEventOrTimeout({
  1286. target,
  1287. name,
  1288. delay = 0
  1289. }) {
  1290. if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) {
  1291. throw new Error("waitOnEventOrTimeout - invalid parameters.");
  1292. }
  1293. const {
  1294. promise,
  1295. resolve
  1296. } = Promise.withResolvers();
  1297. const ac = new AbortController();
  1298. function handler(type) {
  1299. ac.abort();
  1300. clearTimeout(timeout);
  1301. resolve(type);
  1302. }
  1303. const evtMethod = target instanceof EventBus ? "_on" : "addEventListener";
  1304. target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), {
  1305. signal: ac.signal
  1306. });
  1307. const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay);
  1308. return promise;
  1309. }
  1310. class EventBus {
  1311. #listeners = Object.create(null);
  1312. on(eventName, listener, options = null) {
  1313. this._on(eventName, listener, {
  1314. external: true,
  1315. once: options?.once,
  1316. signal: options?.signal
  1317. });
  1318. }
  1319. off(eventName, listener, options = null) {
  1320. this._off(eventName, listener);
  1321. }
  1322. dispatch(eventName, data) {
  1323. const eventListeners = this.#listeners[eventName];
  1324. if (!eventListeners || eventListeners.length === 0) {
  1325. return;
  1326. }
  1327. let externalListeners;
  1328. for (const {
  1329. listener,
  1330. external,
  1331. once
  1332. } of eventListeners.slice(0)) {
  1333. if (once) {
  1334. this._off(eventName, listener);
  1335. }
  1336. if (external) {
  1337. (externalListeners ||= []).push(listener);
  1338. continue;
  1339. }
  1340. listener(data);
  1341. }
  1342. if (externalListeners) {
  1343. for (const listener of externalListeners) {
  1344. listener(data);
  1345. }
  1346. externalListeners = null;
  1347. }
  1348. }
  1349. _on(eventName, listener, options = null) {
  1350. let rmAbort = null;
  1351. if (options?.signal instanceof AbortSignal) {
  1352. const {
  1353. signal
  1354. } = options;
  1355. if (signal.aborted) {
  1356. console.error("Cannot use an `aborted` signal.");
  1357. return;
  1358. }
  1359. const onAbort = () => this._off(eventName, listener);
  1360. rmAbort = () => signal.removeEventListener("abort", onAbort);
  1361. signal.addEventListener("abort", onAbort);
  1362. }
  1363. const eventListeners = this.#listeners[eventName] ||= [];
  1364. eventListeners.push({
  1365. listener,
  1366. external: options?.external === true,
  1367. once: options?.once === true,
  1368. rmAbort
  1369. });
  1370. }
  1371. _off(eventName, listener, options = null) {
  1372. const eventListeners = this.#listeners[eventName];
  1373. if (!eventListeners) {
  1374. return;
  1375. }
  1376. for (let i = 0, ii = eventListeners.length; i < ii; i++) {
  1377. const evt = eventListeners[i];
  1378. if (evt.listener === listener) {
  1379. evt.rmAbort?.();
  1380. eventListeners.splice(i, 1);
  1381. return;
  1382. }
  1383. }
  1384. }
  1385. }
  1386. class FirefoxEventBus extends EventBus {
  1387. #externalServices;
  1388. #globalEventNames;
  1389. #isInAutomation;
  1390. constructor(globalEventNames, externalServices, isInAutomation) {
  1391. super();
  1392. this.#globalEventNames = globalEventNames;
  1393. this.#externalServices = externalServices;
  1394. this.#isInAutomation = isInAutomation;
  1395. }
  1396. dispatch(eventName, data) {
  1397. throw new Error("Not implemented: FirefoxEventBus.dispatch");
  1398. }
  1399. }
  1400. ;// ./web/external_services.js
  1401. class BaseExternalServices {
  1402. updateFindControlState(data) {}
  1403. updateFindMatchesCount(data) {}
  1404. initPassiveLoading() {}
  1405. reportTelemetry(data) {}
  1406. async createL10n() {
  1407. throw new Error("Not implemented: createL10n");
  1408. }
  1409. createScripting() {
  1410. throw new Error("Not implemented: createScripting");
  1411. }
  1412. createSignatureStorage() {
  1413. throw new Error("Not implemented: createSignatureStorage");
  1414. }
  1415. updateEditorStates(data) {
  1416. throw new Error("Not implemented: updateEditorStates");
  1417. }
  1418. dispatchGlobalEvent(_event) {}
  1419. }
  1420. ;// ./web/preferences.js
  1421. class BasePreferences {
  1422. #defaults = Object.freeze({
  1423. altTextLearnMoreUrl: "",
  1424. annotationEditorMode: 0,
  1425. annotationMode: 2,
  1426. cursorToolOnLoad: 0,
  1427. defaultZoomDelay: 400,
  1428. defaultZoomValue: "",
  1429. disablePageLabels: false,
  1430. enableAltText: false,
  1431. enableAltTextModelDownload: true,
  1432. enableAutoLinking: true,
  1433. enableGuessAltText: true,
  1434. enableHighlightFloatingButton: false,
  1435. enableNewAltTextWhenAddingImage: true,
  1436. enablePermissions: false,
  1437. enablePrintAutoRotate: true,
  1438. enableScripting: true,
  1439. enableSignatureEditor: false,
  1440. enableUpdatedAddImage: false,
  1441. externalLinkTarget: 0,
  1442. highlightEditorColors: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F",
  1443. historyUpdateUrl: false,
  1444. ignoreDestinationZoom: false,
  1445. forcePageColors: false,
  1446. pageColorsBackground: "Canvas",
  1447. pageColorsForeground: "CanvasText",
  1448. pdfBugEnabled: false,
  1449. sidebarViewOnLoad: -1,
  1450. scrollModeOnLoad: -1,
  1451. spreadModeOnLoad: -1,
  1452. textLayerMode: 1,
  1453. viewerCssTheme: 0,
  1454. viewOnLoad: 0,
  1455. disableAutoFetch: false,
  1456. disableFontFace: false,
  1457. disableRange: false,
  1458. disableStream: false,
  1459. enableHWA: true,
  1460. enableXfa: true
  1461. });
  1462. #initializedPromise = null;
  1463. constructor() {
  1464. this.#initializedPromise = this._readFromStorage(this.#defaults).then(({
  1465. browserPrefs,
  1466. prefs
  1467. }) => {
  1468. if (AppOptions._checkDisablePreferences()) {
  1469. return;
  1470. }
  1471. AppOptions.setAll({
  1472. ...browserPrefs,
  1473. ...prefs
  1474. }, true);
  1475. });
  1476. }
  1477. async _writeToStorage(prefObj) {
  1478. throw new Error("Not implemented: _writeToStorage");
  1479. }
  1480. async _readFromStorage(prefObj) {
  1481. throw new Error("Not implemented: _readFromStorage");
  1482. }
  1483. async reset() {
  1484. await this.#initializedPromise;
  1485. AppOptions.setAll(this.#defaults, true);
  1486. await this._writeToStorage(this.#defaults);
  1487. }
  1488. async set(name, value) {
  1489. await this.#initializedPromise;
  1490. AppOptions.setAll({
  1491. [name]: value
  1492. }, true);
  1493. await this._writeToStorage(AppOptions.getAll(OptionKind.PREFERENCE));
  1494. }
  1495. async get(name) {
  1496. await this.#initializedPromise;
  1497. return AppOptions.get(name);
  1498. }
  1499. get initializedPromise() {
  1500. return this.#initializedPromise;
  1501. }
  1502. }
  1503. ;// ./node_modules/@fluent/bundle/esm/types.js
  1504. class FluentType {
  1505. constructor(value) {
  1506. this.value = value;
  1507. }
  1508. valueOf() {
  1509. return this.value;
  1510. }
  1511. }
  1512. class FluentNone extends FluentType {
  1513. constructor(value = "???") {
  1514. super(value);
  1515. }
  1516. toString(scope) {
  1517. return `{${this.value}}`;
  1518. }
  1519. }
  1520. class FluentNumber extends FluentType {
  1521. constructor(value, opts = {}) {
  1522. super(value);
  1523. this.opts = opts;
  1524. }
  1525. toString(scope) {
  1526. if (scope) {
  1527. try {
  1528. const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts);
  1529. return nf.format(this.value);
  1530. } catch (err) {
  1531. scope.reportError(err);
  1532. }
  1533. }
  1534. return this.value.toString(10);
  1535. }
  1536. }
  1537. class FluentDateTime extends FluentType {
  1538. static supportsValue(value) {
  1539. if (typeof value === "number") return true;
  1540. if (value instanceof Date) return true;
  1541. if (value instanceof FluentType) return FluentDateTime.supportsValue(value.valueOf());
  1542. if ("Temporal" in globalThis) {
  1543. const _Temporal = globalThis.Temporal;
  1544. if (value instanceof _Temporal.Instant || value instanceof _Temporal.PlainDateTime || value instanceof _Temporal.PlainDate || value instanceof _Temporal.PlainMonthDay || value instanceof _Temporal.PlainTime || value instanceof _Temporal.PlainYearMonth) {
  1545. return true;
  1546. }
  1547. }
  1548. return false;
  1549. }
  1550. constructor(value, opts = {}) {
  1551. if (value instanceof FluentDateTime) {
  1552. opts = {
  1553. ...value.opts,
  1554. ...opts
  1555. };
  1556. value = value.value;
  1557. } else if (value instanceof FluentType) {
  1558. value = value.valueOf();
  1559. }
  1560. if (typeof value === "object" && "calendarId" in value && opts.calendar === undefined) {
  1561. opts = {
  1562. ...opts,
  1563. calendar: value.calendarId
  1564. };
  1565. }
  1566. super(value);
  1567. this.opts = opts;
  1568. }
  1569. [Symbol.toPrimitive](hint) {
  1570. return hint === "string" ? this.toString() : this.toNumber();
  1571. }
  1572. toNumber() {
  1573. const value = this.value;
  1574. if (typeof value === "number") return value;
  1575. if (value instanceof Date) return value.getTime();
  1576. if ("epochMilliseconds" in value) {
  1577. return value.epochMilliseconds;
  1578. }
  1579. if ("toZonedDateTime" in value) {
  1580. return value.toZonedDateTime("UTC").epochMilliseconds;
  1581. }
  1582. throw new TypeError("Unwrapping a non-number value as a number");
  1583. }
  1584. toString(scope) {
  1585. if (scope) {
  1586. try {
  1587. const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts);
  1588. return dtf.format(this.value);
  1589. } catch (err) {
  1590. scope.reportError(err);
  1591. }
  1592. }
  1593. if (typeof this.value === "number" || this.value instanceof Date) {
  1594. return new Date(this.value).toISOString();
  1595. }
  1596. return this.value.toString();
  1597. }
  1598. }
  1599. ;// ./node_modules/@fluent/bundle/esm/resolver.js
  1600. const MAX_PLACEABLES = 100;
  1601. const FSI = "\u2068";
  1602. const PDI = "\u2069";
  1603. function match(scope, selector, key) {
  1604. if (key === selector) {
  1605. return true;
  1606. }
  1607. if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) {
  1608. return true;
  1609. }
  1610. if (selector instanceof FluentNumber && typeof key === "string") {
  1611. let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value);
  1612. if (key === category) {
  1613. return true;
  1614. }
  1615. }
  1616. return false;
  1617. }
  1618. function getDefault(scope, variants, star) {
  1619. if (variants[star]) {
  1620. return resolvePattern(scope, variants[star].value);
  1621. }
  1622. scope.reportError(new RangeError("No default"));
  1623. return new FluentNone();
  1624. }
  1625. function getArguments(scope, args) {
  1626. const positional = [];
  1627. const named = Object.create(null);
  1628. for (const arg of args) {
  1629. if (arg.type === "narg") {
  1630. named[arg.name] = resolveExpression(scope, arg.value);
  1631. } else {
  1632. positional.push(resolveExpression(scope, arg));
  1633. }
  1634. }
  1635. return {
  1636. positional,
  1637. named
  1638. };
  1639. }
  1640. function resolveExpression(scope, expr) {
  1641. switch (expr.type) {
  1642. case "str":
  1643. return expr.value;
  1644. case "num":
  1645. return new FluentNumber(expr.value, {
  1646. minimumFractionDigits: expr.precision
  1647. });
  1648. case "var":
  1649. return resolveVariableReference(scope, expr);
  1650. case "mesg":
  1651. return resolveMessageReference(scope, expr);
  1652. case "term":
  1653. return resolveTermReference(scope, expr);
  1654. case "func":
  1655. return resolveFunctionReference(scope, expr);
  1656. case "select":
  1657. return resolveSelectExpression(scope, expr);
  1658. default:
  1659. return new FluentNone();
  1660. }
  1661. }
  1662. function resolveVariableReference(scope, {
  1663. name
  1664. }) {
  1665. let arg;
  1666. if (scope.params) {
  1667. if (Object.prototype.hasOwnProperty.call(scope.params, name)) {
  1668. arg = scope.params[name];
  1669. } else {
  1670. return new FluentNone(`$${name}`);
  1671. }
  1672. } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) {
  1673. arg = scope.args[name];
  1674. } else {
  1675. scope.reportError(new ReferenceError(`Unknown variable: $${name}`));
  1676. return new FluentNone(`$${name}`);
  1677. }
  1678. if (arg instanceof FluentType) {
  1679. return arg;
  1680. }
  1681. switch (typeof arg) {
  1682. case "string":
  1683. return arg;
  1684. case "number":
  1685. return new FluentNumber(arg);
  1686. case "object":
  1687. if (FluentDateTime.supportsValue(arg)) {
  1688. return new FluentDateTime(arg);
  1689. }
  1690. default:
  1691. scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`));
  1692. return new FluentNone(`$${name}`);
  1693. }
  1694. }
  1695. function resolveMessageReference(scope, {
  1696. name,
  1697. attr
  1698. }) {
  1699. const message = scope.bundle._messages.get(name);
  1700. if (!message) {
  1701. scope.reportError(new ReferenceError(`Unknown message: ${name}`));
  1702. return new FluentNone(name);
  1703. }
  1704. if (attr) {
  1705. const attribute = message.attributes[attr];
  1706. if (attribute) {
  1707. return resolvePattern(scope, attribute);
  1708. }
  1709. scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
  1710. return new FluentNone(`${name}.${attr}`);
  1711. }
  1712. if (message.value) {
  1713. return resolvePattern(scope, message.value);
  1714. }
  1715. scope.reportError(new ReferenceError(`No value: ${name}`));
  1716. return new FluentNone(name);
  1717. }
  1718. function resolveTermReference(scope, {
  1719. name,
  1720. attr,
  1721. args
  1722. }) {
  1723. const id = `-${name}`;
  1724. const term = scope.bundle._terms.get(id);
  1725. if (!term) {
  1726. scope.reportError(new ReferenceError(`Unknown term: ${id}`));
  1727. return new FluentNone(id);
  1728. }
  1729. if (attr) {
  1730. const attribute = term.attributes[attr];
  1731. if (attribute) {
  1732. scope.params = getArguments(scope, args).named;
  1733. const resolved = resolvePattern(scope, attribute);
  1734. scope.params = null;
  1735. return resolved;
  1736. }
  1737. scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
  1738. return new FluentNone(`${id}.${attr}`);
  1739. }
  1740. scope.params = getArguments(scope, args).named;
  1741. const resolved = resolvePattern(scope, term.value);
  1742. scope.params = null;
  1743. return resolved;
  1744. }
  1745. function resolveFunctionReference(scope, {
  1746. name,
  1747. args
  1748. }) {
  1749. let func = scope.bundle._functions[name];
  1750. if (!func) {
  1751. scope.reportError(new ReferenceError(`Unknown function: ${name}()`));
  1752. return new FluentNone(`${name}()`);
  1753. }
  1754. if (typeof func !== "function") {
  1755. scope.reportError(new TypeError(`Function ${name}() is not callable`));
  1756. return new FluentNone(`${name}()`);
  1757. }
  1758. try {
  1759. let resolved = getArguments(scope, args);
  1760. return func(resolved.positional, resolved.named);
  1761. } catch (err) {
  1762. scope.reportError(err);
  1763. return new FluentNone(`${name}()`);
  1764. }
  1765. }
  1766. function resolveSelectExpression(scope, {
  1767. selector,
  1768. variants,
  1769. star
  1770. }) {
  1771. let sel = resolveExpression(scope, selector);
  1772. if (sel instanceof FluentNone) {
  1773. return getDefault(scope, variants, star);
  1774. }
  1775. for (const variant of variants) {
  1776. const key = resolveExpression(scope, variant.key);
  1777. if (match(scope, sel, key)) {
  1778. return resolvePattern(scope, variant.value);
  1779. }
  1780. }
  1781. return getDefault(scope, variants, star);
  1782. }
  1783. function resolveComplexPattern(scope, ptn) {
  1784. if (scope.dirty.has(ptn)) {
  1785. scope.reportError(new RangeError("Cyclic reference"));
  1786. return new FluentNone();
  1787. }
  1788. scope.dirty.add(ptn);
  1789. const result = [];
  1790. const useIsolating = scope.bundle._useIsolating && ptn.length > 1;
  1791. for (const elem of ptn) {
  1792. if (typeof elem === "string") {
  1793. result.push(scope.bundle._transform(elem));
  1794. continue;
  1795. }
  1796. scope.placeables++;
  1797. if (scope.placeables > MAX_PLACEABLES) {
  1798. scope.dirty.delete(ptn);
  1799. throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`);
  1800. }
  1801. if (useIsolating) {
  1802. result.push(FSI);
  1803. }
  1804. result.push(resolveExpression(scope, elem).toString(scope));
  1805. if (useIsolating) {
  1806. result.push(PDI);
  1807. }
  1808. }
  1809. scope.dirty.delete(ptn);
  1810. return result.join("");
  1811. }
  1812. function resolvePattern(scope, value) {
  1813. if (typeof value === "string") {
  1814. return scope.bundle._transform(value);
  1815. }
  1816. return resolveComplexPattern(scope, value);
  1817. }
  1818. ;// ./node_modules/@fluent/bundle/esm/scope.js
  1819. class Scope {
  1820. constructor(bundle, errors, args) {
  1821. this.dirty = new WeakSet();
  1822. this.params = null;
  1823. this.placeables = 0;
  1824. this.bundle = bundle;
  1825. this.errors = errors;
  1826. this.args = args;
  1827. }
  1828. reportError(error) {
  1829. if (!this.errors || !(error instanceof Error)) {
  1830. throw error;
  1831. }
  1832. this.errors.push(error);
  1833. }
  1834. memoizeIntlObject(ctor, opts) {
  1835. let cache = this.bundle._intls.get(ctor);
  1836. if (!cache) {
  1837. cache = {};
  1838. this.bundle._intls.set(ctor, cache);
  1839. }
  1840. let id = JSON.stringify(opts);
  1841. if (!cache[id]) {
  1842. cache[id] = new ctor(this.bundle.locales, opts);
  1843. }
  1844. return cache[id];
  1845. }
  1846. }
  1847. ;// ./node_modules/@fluent/bundle/esm/builtins.js
  1848. function values(opts, allowed) {
  1849. const unwrapped = Object.create(null);
  1850. for (const [name, opt] of Object.entries(opts)) {
  1851. if (allowed.includes(name)) {
  1852. unwrapped[name] = opt.valueOf();
  1853. }
  1854. }
  1855. return unwrapped;
  1856. }
  1857. const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"];
  1858. function NUMBER(args, opts) {
  1859. let arg = args[0];
  1860. if (arg instanceof FluentNone) {
  1861. return new FluentNone(`NUMBER(${arg.valueOf()})`);
  1862. }
  1863. if (arg instanceof FluentNumber) {
  1864. return new FluentNumber(arg.valueOf(), {
  1865. ...arg.opts,
  1866. ...values(opts, NUMBER_ALLOWED)
  1867. });
  1868. }
  1869. if (arg instanceof FluentDateTime) {
  1870. return new FluentNumber(arg.toNumber(), {
  1871. ...values(opts, NUMBER_ALLOWED)
  1872. });
  1873. }
  1874. throw new TypeError("Invalid argument to NUMBER");
  1875. }
  1876. const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"];
  1877. function DATETIME(args, opts) {
  1878. let arg = args[0];
  1879. if (arg instanceof FluentNone) {
  1880. return new FluentNone(`DATETIME(${arg.valueOf()})`);
  1881. }
  1882. if (arg instanceof FluentDateTime || arg instanceof FluentNumber) {
  1883. return new FluentDateTime(arg, values(opts, DATETIME_ALLOWED));
  1884. }
  1885. throw new TypeError("Invalid argument to DATETIME");
  1886. }
  1887. ;// ./node_modules/@fluent/bundle/esm/memoizer.js
  1888. const cache = new Map();
  1889. function getMemoizerForLocale(locales) {
  1890. const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales;
  1891. let memoizer = cache.get(stringLocale);
  1892. if (memoizer === undefined) {
  1893. memoizer = new Map();
  1894. cache.set(stringLocale, memoizer);
  1895. }
  1896. return memoizer;
  1897. }
  1898. ;// ./node_modules/@fluent/bundle/esm/bundle.js
  1899. class FluentBundle {
  1900. constructor(locales, {
  1901. functions,
  1902. useIsolating = true,
  1903. transform = v => v
  1904. } = {}) {
  1905. this._terms = new Map();
  1906. this._messages = new Map();
  1907. this.locales = Array.isArray(locales) ? locales : [locales];
  1908. this._functions = {
  1909. NUMBER: NUMBER,
  1910. DATETIME: DATETIME,
  1911. ...functions
  1912. };
  1913. this._useIsolating = useIsolating;
  1914. this._transform = transform;
  1915. this._intls = getMemoizerForLocale(locales);
  1916. }
  1917. hasMessage(id) {
  1918. return this._messages.has(id);
  1919. }
  1920. getMessage(id) {
  1921. return this._messages.get(id);
  1922. }
  1923. addResource(res, {
  1924. allowOverrides = false
  1925. } = {}) {
  1926. const errors = [];
  1927. for (let i = 0; i < res.body.length; i++) {
  1928. let entry = res.body[i];
  1929. if (entry.id.startsWith("-")) {
  1930. if (allowOverrides === false && this._terms.has(entry.id)) {
  1931. errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`));
  1932. continue;
  1933. }
  1934. this._terms.set(entry.id, entry);
  1935. } else {
  1936. if (allowOverrides === false && this._messages.has(entry.id)) {
  1937. errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`));
  1938. continue;
  1939. }
  1940. this._messages.set(entry.id, entry);
  1941. }
  1942. }
  1943. return errors;
  1944. }
  1945. formatPattern(pattern, args = null, errors = null) {
  1946. if (typeof pattern === "string") {
  1947. return this._transform(pattern);
  1948. }
  1949. let scope = new Scope(this, errors, args);
  1950. try {
  1951. let value = resolveComplexPattern(scope, pattern);
  1952. return value.toString(scope);
  1953. } catch (err) {
  1954. if (scope.errors && err instanceof Error) {
  1955. scope.errors.push(err);
  1956. return new FluentNone().toString(scope);
  1957. }
  1958. throw err;
  1959. }
  1960. }
  1961. }
  1962. ;// ./node_modules/@fluent/bundle/esm/resource.js
  1963. const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm;
  1964. const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y;
  1965. const RE_VARIANT_START = /\*?\[/y;
  1966. const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y;
  1967. const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y;
  1968. const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y;
  1969. const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/;
  1970. const RE_TEXT_RUN = /([^{}\n\r]+)/y;
  1971. const RE_STRING_RUN = /([^\\"\n\r]*)/y;
  1972. const RE_STRING_ESCAPE = /\\([\\"])/y;
  1973. const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y;
  1974. const RE_LEADING_NEWLINES = /^\n+/;
  1975. const RE_TRAILING_SPACES = / +$/;
  1976. const RE_BLANK_LINES = / *\r?\n/g;
  1977. const RE_INDENT = /( *)$/;
  1978. const TOKEN_BRACE_OPEN = /{\s*/y;
  1979. const TOKEN_BRACE_CLOSE = /\s*}/y;
  1980. const TOKEN_BRACKET_OPEN = /\[\s*/y;
  1981. const TOKEN_BRACKET_CLOSE = /\s*] */y;
  1982. const TOKEN_PAREN_OPEN = /\s*\(\s*/y;
  1983. const TOKEN_ARROW = /\s*->\s*/y;
  1984. const TOKEN_COLON = /\s*:\s*/y;
  1985. const TOKEN_COMMA = /\s*,?\s*/y;
  1986. const TOKEN_BLANK = /\s+/y;
  1987. class FluentResource {
  1988. constructor(source) {
  1989. this.body = [];
  1990. RE_MESSAGE_START.lastIndex = 0;
  1991. let cursor = 0;
  1992. while (true) {
  1993. let next = RE_MESSAGE_START.exec(source);
  1994. if (next === null) {
  1995. break;
  1996. }
  1997. cursor = RE_MESSAGE_START.lastIndex;
  1998. try {
  1999. this.body.push(parseMessage(next[1]));
  2000. } catch (err) {
  2001. if (err instanceof SyntaxError) {
  2002. continue;
  2003. }
  2004. throw err;
  2005. }
  2006. }
  2007. function test(re) {
  2008. re.lastIndex = cursor;
  2009. return re.test(source);
  2010. }
  2011. function consumeChar(char, errorClass) {
  2012. if (source[cursor] === char) {
  2013. cursor++;
  2014. return true;
  2015. }
  2016. if (errorClass) {
  2017. throw new errorClass(`Expected ${char}`);
  2018. }
  2019. return false;
  2020. }
  2021. function consumeToken(re, errorClass) {
  2022. if (test(re)) {
  2023. cursor = re.lastIndex;
  2024. return true;
  2025. }
  2026. if (errorClass) {
  2027. throw new errorClass(`Expected ${re.toString()}`);
  2028. }
  2029. return false;
  2030. }
  2031. function match(re) {
  2032. re.lastIndex = cursor;
  2033. let result = re.exec(source);
  2034. if (result === null) {
  2035. throw new SyntaxError(`Expected ${re.toString()}`);
  2036. }
  2037. cursor = re.lastIndex;
  2038. return result;
  2039. }
  2040. function match1(re) {
  2041. return match(re)[1];
  2042. }
  2043. function parseMessage(id) {
  2044. let value = parsePattern();
  2045. let attributes = parseAttributes();
  2046. if (value === null && Object.keys(attributes).length === 0) {
  2047. throw new SyntaxError("Expected message value or attributes");
  2048. }
  2049. return {
  2050. id,
  2051. value,
  2052. attributes
  2053. };
  2054. }
  2055. function parseAttributes() {
  2056. let attrs = Object.create(null);
  2057. while (test(RE_ATTRIBUTE_START)) {
  2058. let name = match1(RE_ATTRIBUTE_START);
  2059. let value = parsePattern();
  2060. if (value === null) {
  2061. throw new SyntaxError("Expected attribute value");
  2062. }
  2063. attrs[name] = value;
  2064. }
  2065. return attrs;
  2066. }
  2067. function parsePattern() {
  2068. let first;
  2069. if (test(RE_TEXT_RUN)) {
  2070. first = match1(RE_TEXT_RUN);
  2071. }
  2072. if (source[cursor] === "{" || source[cursor] === "}") {
  2073. return parsePatternElements(first ? [first] : [], Infinity);
  2074. }
  2075. let indent = parseIndent();
  2076. if (indent) {
  2077. if (first) {
  2078. return parsePatternElements([first, indent], indent.length);
  2079. }
  2080. indent.value = trim(indent.value, RE_LEADING_NEWLINES);
  2081. return parsePatternElements([indent], indent.length);
  2082. }
  2083. if (first) {
  2084. return trim(first, RE_TRAILING_SPACES);
  2085. }
  2086. return null;
  2087. }
  2088. function parsePatternElements(elements = [], commonIndent) {
  2089. while (true) {
  2090. if (test(RE_TEXT_RUN)) {
  2091. elements.push(match1(RE_TEXT_RUN));
  2092. continue;
  2093. }
  2094. if (source[cursor] === "{") {
  2095. elements.push(parsePlaceable());
  2096. continue;
  2097. }
  2098. if (source[cursor] === "}") {
  2099. throw new SyntaxError("Unbalanced closing brace");
  2100. }
  2101. let indent = parseIndent();
  2102. if (indent) {
  2103. elements.push(indent);
  2104. commonIndent = Math.min(commonIndent, indent.length);
  2105. continue;
  2106. }
  2107. break;
  2108. }
  2109. let lastIndex = elements.length - 1;
  2110. let lastElement = elements[lastIndex];
  2111. if (typeof lastElement === "string") {
  2112. elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES);
  2113. }
  2114. let baked = [];
  2115. for (let element of elements) {
  2116. if (element instanceof Indent) {
  2117. element = element.value.slice(0, element.value.length - commonIndent);
  2118. }
  2119. if (element) {
  2120. baked.push(element);
  2121. }
  2122. }
  2123. return baked;
  2124. }
  2125. function parsePlaceable() {
  2126. consumeToken(TOKEN_BRACE_OPEN, SyntaxError);
  2127. let selector = parseInlineExpression();
  2128. if (consumeToken(TOKEN_BRACE_CLOSE)) {
  2129. return selector;
  2130. }
  2131. if (consumeToken(TOKEN_ARROW)) {
  2132. let variants = parseVariants();
  2133. consumeToken(TOKEN_BRACE_CLOSE, SyntaxError);
  2134. return {
  2135. type: "select",
  2136. selector,
  2137. ...variants
  2138. };
  2139. }
  2140. throw new SyntaxError("Unclosed placeable");
  2141. }
  2142. function parseInlineExpression() {
  2143. if (source[cursor] === "{") {
  2144. return parsePlaceable();
  2145. }
  2146. if (test(RE_REFERENCE)) {
  2147. let [, sigil, name, attr = null] = match(RE_REFERENCE);
  2148. if (sigil === "$") {
  2149. return {
  2150. type: "var",
  2151. name
  2152. };
  2153. }
  2154. if (consumeToken(TOKEN_PAREN_OPEN)) {
  2155. let args = parseArguments();
  2156. if (sigil === "-") {
  2157. return {
  2158. type: "term",
  2159. name,
  2160. attr,
  2161. args
  2162. };
  2163. }
  2164. if (RE_FUNCTION_NAME.test(name)) {
  2165. return {
  2166. type: "func",
  2167. name,
  2168. args
  2169. };
  2170. }
  2171. throw new SyntaxError("Function names must be all upper-case");
  2172. }
  2173. if (sigil === "-") {
  2174. return {
  2175. type: "term",
  2176. name,
  2177. attr,
  2178. args: []
  2179. };
  2180. }
  2181. return {
  2182. type: "mesg",
  2183. name,
  2184. attr
  2185. };
  2186. }
  2187. return parseLiteral();
  2188. }
  2189. function parseArguments() {
  2190. let args = [];
  2191. while (true) {
  2192. switch (source[cursor]) {
  2193. case ")":
  2194. cursor++;
  2195. return args;
  2196. case undefined:
  2197. throw new SyntaxError("Unclosed argument list");
  2198. }
  2199. args.push(parseArgument());
  2200. consumeToken(TOKEN_COMMA);
  2201. }
  2202. }
  2203. function parseArgument() {
  2204. let expr = parseInlineExpression();
  2205. if (expr.type !== "mesg") {
  2206. return expr;
  2207. }
  2208. if (consumeToken(TOKEN_COLON)) {
  2209. return {
  2210. type: "narg",
  2211. name: expr.name,
  2212. value: parseLiteral()
  2213. };
  2214. }
  2215. return expr;
  2216. }
  2217. function parseVariants() {
  2218. let variants = [];
  2219. let count = 0;
  2220. let star;
  2221. while (test(RE_VARIANT_START)) {
  2222. if (consumeChar("*")) {
  2223. star = count;
  2224. }
  2225. let key = parseVariantKey();
  2226. let value = parsePattern();
  2227. if (value === null) {
  2228. throw new SyntaxError("Expected variant value");
  2229. }
  2230. variants[count++] = {
  2231. key,
  2232. value
  2233. };
  2234. }
  2235. if (count === 0) {
  2236. return null;
  2237. }
  2238. if (star === undefined) {
  2239. throw new SyntaxError("Expected default variant");
  2240. }
  2241. return {
  2242. variants,
  2243. star
  2244. };
  2245. }
  2246. function parseVariantKey() {
  2247. consumeToken(TOKEN_BRACKET_OPEN, SyntaxError);
  2248. let key;
  2249. if (test(RE_NUMBER_LITERAL)) {
  2250. key = parseNumberLiteral();
  2251. } else {
  2252. key = {
  2253. type: "str",
  2254. value: match1(RE_IDENTIFIER)
  2255. };
  2256. }
  2257. consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError);
  2258. return key;
  2259. }
  2260. function parseLiteral() {
  2261. if (test(RE_NUMBER_LITERAL)) {
  2262. return parseNumberLiteral();
  2263. }
  2264. if (source[cursor] === '"') {
  2265. return parseStringLiteral();
  2266. }
  2267. throw new SyntaxError("Invalid expression");
  2268. }
  2269. function parseNumberLiteral() {
  2270. let [, value, fraction = ""] = match(RE_NUMBER_LITERAL);
  2271. let precision = fraction.length;
  2272. return {
  2273. type: "num",
  2274. value: parseFloat(value),
  2275. precision
  2276. };
  2277. }
  2278. function parseStringLiteral() {
  2279. consumeChar('"', SyntaxError);
  2280. let value = "";
  2281. while (true) {
  2282. value += match1(RE_STRING_RUN);
  2283. if (source[cursor] === "\\") {
  2284. value += parseEscapeSequence();
  2285. continue;
  2286. }
  2287. if (consumeChar('"')) {
  2288. return {
  2289. type: "str",
  2290. value
  2291. };
  2292. }
  2293. throw new SyntaxError("Unclosed string literal");
  2294. }
  2295. }
  2296. function parseEscapeSequence() {
  2297. if (test(RE_STRING_ESCAPE)) {
  2298. return match1(RE_STRING_ESCAPE);
  2299. }
  2300. if (test(RE_UNICODE_ESCAPE)) {
  2301. let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE);
  2302. let codepoint = parseInt(codepoint4 || codepoint6, 16);
  2303. return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�";
  2304. }
  2305. throw new SyntaxError("Unknown escape sequence");
  2306. }
  2307. function parseIndent() {
  2308. let start = cursor;
  2309. consumeToken(TOKEN_BLANK);
  2310. switch (source[cursor]) {
  2311. case ".":
  2312. case "[":
  2313. case "*":
  2314. case "}":
  2315. case undefined:
  2316. return false;
  2317. case "{":
  2318. return makeIndent(source.slice(start, cursor));
  2319. }
  2320. if (source[cursor - 1] === " ") {
  2321. return makeIndent(source.slice(start, cursor));
  2322. }
  2323. return false;
  2324. }
  2325. function trim(text, re) {
  2326. return text.replace(re, "");
  2327. }
  2328. function makeIndent(blank) {
  2329. let value = blank.replace(RE_BLANK_LINES, "\n");
  2330. let length = RE_INDENT.exec(blank)[1].length;
  2331. return new Indent(value, length);
  2332. }
  2333. }
  2334. }
  2335. class Indent {
  2336. constructor(value, length) {
  2337. this.value = value;
  2338. this.length = length;
  2339. }
  2340. }
  2341. ;// ./node_modules/@fluent/bundle/esm/index.js
  2342. ;// ./node_modules/@fluent/dom/esm/overlay.js
  2343. const reOverlay = /<|&#?\w+;/;
  2344. const TEXT_LEVEL_ELEMENTS = {
  2345. "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"]
  2346. };
  2347. const LOCALIZABLE_ATTRIBUTES = {
  2348. "http://www.w3.org/1999/xhtml": {
  2349. global: ["title", "aria-description", "aria-label", "aria-valuetext"],
  2350. a: ["download"],
  2351. area: ["download", "alt"],
  2352. input: ["alt", "placeholder"],
  2353. menuitem: ["label"],
  2354. menu: ["label"],
  2355. optgroup: ["label"],
  2356. option: ["label"],
  2357. track: ["label"],
  2358. img: ["alt"],
  2359. textarea: ["placeholder"],
  2360. th: ["abbr"]
  2361. },
  2362. "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": {
  2363. global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"],
  2364. description: ["value"],
  2365. key: ["key", "keycode"],
  2366. label: ["value"],
  2367. textbox: ["placeholder", "value"]
  2368. }
  2369. };
  2370. function translateElement(element, translation) {
  2371. const {
  2372. value
  2373. } = translation;
  2374. if (typeof value === "string") {
  2375. if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") {
  2376. element.textContent = value;
  2377. } else if (!reOverlay.test(value)) {
  2378. element.textContent = value;
  2379. } else {
  2380. const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template");
  2381. templateElement.innerHTML = value;
  2382. overlayChildNodes(templateElement.content, element);
  2383. }
  2384. }
  2385. overlayAttributes(translation, element);
  2386. }
  2387. function overlayChildNodes(fromFragment, toElement) {
  2388. for (const childNode of fromFragment.childNodes) {
  2389. if (childNode.nodeType === childNode.TEXT_NODE) {
  2390. continue;
  2391. }
  2392. if (childNode.hasAttribute("data-l10n-name")) {
  2393. const sanitized = getNodeForNamedElement(toElement, childNode);
  2394. fromFragment.replaceChild(sanitized, childNode);
  2395. continue;
  2396. }
  2397. if (isElementAllowed(childNode)) {
  2398. const sanitized = createSanitizedElement(childNode);
  2399. fromFragment.replaceChild(sanitized, childNode);
  2400. continue;
  2401. }
  2402. 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.");
  2403. fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode);
  2404. }
  2405. toElement.textContent = "";
  2406. toElement.appendChild(fromFragment);
  2407. }
  2408. function hasAttribute(attributes, name) {
  2409. if (!attributes) {
  2410. return false;
  2411. }
  2412. for (let attr of attributes) {
  2413. if (attr.name === name) {
  2414. return true;
  2415. }
  2416. }
  2417. return false;
  2418. }
  2419. function overlayAttributes(fromElement, toElement) {
  2420. const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null;
  2421. for (const attr of Array.from(toElement.attributes)) {
  2422. if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) {
  2423. toElement.removeAttribute(attr.name);
  2424. }
  2425. }
  2426. if (!fromElement.attributes) {
  2427. return;
  2428. }
  2429. for (const attr of Array.from(fromElement.attributes)) {
  2430. if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) {
  2431. toElement.setAttribute(attr.name, attr.value);
  2432. }
  2433. }
  2434. }
  2435. function getNodeForNamedElement(sourceElement, translatedChild) {
  2436. const childName = translatedChild.getAttribute("data-l10n-name");
  2437. const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`);
  2438. if (!sourceChild) {
  2439. console.warn(`An element named "${childName}" wasn't found in the source.`);
  2440. return createTextNodeFromTextContent(translatedChild);
  2441. }
  2442. if (sourceChild.localName !== translatedChild.localName) {
  2443. 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}).`);
  2444. return createTextNodeFromTextContent(translatedChild);
  2445. }
  2446. sourceElement.removeChild(sourceChild);
  2447. const clone = sourceChild.cloneNode(false);
  2448. return shallowPopulateUsing(translatedChild, clone);
  2449. }
  2450. function createSanitizedElement(element) {
  2451. const clone = element.ownerDocument.createElement(element.localName);
  2452. return shallowPopulateUsing(element, clone);
  2453. }
  2454. function createTextNodeFromTextContent(element) {
  2455. return element.ownerDocument.createTextNode(element.textContent);
  2456. }
  2457. function isElementAllowed(element) {
  2458. const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI];
  2459. return allowed && allowed.includes(element.localName);
  2460. }
  2461. function isAttrNameLocalizable(name, element, explicitlyAllowed = null) {
  2462. if (explicitlyAllowed && explicitlyAllowed.includes(name)) {
  2463. return true;
  2464. }
  2465. const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI];
  2466. if (!allowed) {
  2467. return false;
  2468. }
  2469. const attrName = name.toLowerCase();
  2470. const elemName = element.localName;
  2471. if (allowed.global.includes(attrName)) {
  2472. return true;
  2473. }
  2474. if (!allowed[elemName]) {
  2475. return false;
  2476. }
  2477. if (allowed[elemName].includes(attrName)) {
  2478. return true;
  2479. }
  2480. if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") {
  2481. const type = element.type.toLowerCase();
  2482. if (type === "submit" || type === "button" || type === "reset") {
  2483. return true;
  2484. }
  2485. }
  2486. return false;
  2487. }
  2488. function shallowPopulateUsing(fromElement, toElement) {
  2489. toElement.textContent = fromElement.textContent;
  2490. overlayAttributes(fromElement, toElement);
  2491. return toElement;
  2492. }
  2493. ;// ./node_modules/cached-iterable/src/cached_iterable.mjs
  2494. class CachedIterable extends Array {
  2495. static from(iterable) {
  2496. if (iterable instanceof this) {
  2497. return iterable;
  2498. }
  2499. return new this(iterable);
  2500. }
  2501. }
  2502. ;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs
  2503. class CachedSyncIterable extends CachedIterable {
  2504. constructor(iterable) {
  2505. super();
  2506. if (Symbol.iterator in Object(iterable)) {
  2507. this.iterator = iterable[Symbol.iterator]();
  2508. } else {
  2509. throw new TypeError("Argument must implement the iteration protocol.");
  2510. }
  2511. }
  2512. [Symbol.iterator]() {
  2513. const cached = this;
  2514. let cur = 0;
  2515. return {
  2516. next() {
  2517. if (cached.length <= cur) {
  2518. cached.push(cached.iterator.next());
  2519. }
  2520. return cached[cur++];
  2521. }
  2522. };
  2523. }
  2524. touchNext(count = 1) {
  2525. let idx = 0;
  2526. while (idx++ < count) {
  2527. const last = this[this.length - 1];
  2528. if (last && last.done) {
  2529. break;
  2530. }
  2531. this.push(this.iterator.next());
  2532. }
  2533. return this[this.length - 1];
  2534. }
  2535. }
  2536. ;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs
  2537. class CachedAsyncIterable extends CachedIterable {
  2538. constructor(iterable) {
  2539. super();
  2540. if (Symbol.asyncIterator in Object(iterable)) {
  2541. this.iterator = iterable[Symbol.asyncIterator]();
  2542. } else if (Symbol.iterator in Object(iterable)) {
  2543. this.iterator = iterable[Symbol.iterator]();
  2544. } else {
  2545. throw new TypeError("Argument must implement the iteration protocol.");
  2546. }
  2547. }
  2548. [Symbol.asyncIterator]() {
  2549. const cached = this;
  2550. let cur = 0;
  2551. return {
  2552. async next() {
  2553. if (cached.length <= cur) {
  2554. cached.push(cached.iterator.next());
  2555. }
  2556. return cached[cur++];
  2557. }
  2558. };
  2559. }
  2560. async touchNext(count = 1) {
  2561. let idx = 0;
  2562. while (idx++ < count) {
  2563. const last = this[this.length - 1];
  2564. if (last && (await last).done) {
  2565. break;
  2566. }
  2567. this.push(this.iterator.next());
  2568. }
  2569. return this[this.length - 1];
  2570. }
  2571. }
  2572. ;// ./node_modules/cached-iterable/src/index.mjs
  2573. ;// ./node_modules/@fluent/dom/esm/localization.js
  2574. class Localization {
  2575. constructor(resourceIds = [], generateBundles) {
  2576. this.resourceIds = resourceIds;
  2577. this.generateBundles = generateBundles;
  2578. this.onChange(true);
  2579. }
  2580. addResourceIds(resourceIds, eager = false) {
  2581. this.resourceIds.push(...resourceIds);
  2582. this.onChange(eager);
  2583. return this.resourceIds.length;
  2584. }
  2585. removeResourceIds(resourceIds) {
  2586. this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r));
  2587. this.onChange();
  2588. return this.resourceIds.length;
  2589. }
  2590. async formatWithFallback(keys, method) {
  2591. const translations = [];
  2592. let hasAtLeastOneBundle = false;
  2593. for await (const bundle of this.bundles) {
  2594. hasAtLeastOneBundle = true;
  2595. const missingIds = keysFromBundle(method, bundle, keys, translations);
  2596. if (missingIds.size === 0) {
  2597. break;
  2598. }
  2599. if (typeof console !== "undefined") {
  2600. const locale = bundle.locales[0];
  2601. const ids = Array.from(missingIds).join(", ");
  2602. console.warn(`[fluent] Missing translations in ${locale}: ${ids}`);
  2603. }
  2604. }
  2605. if (!hasAtLeastOneBundle && typeof console !== "undefined") {
  2606. console.warn(`[fluent] Request for keys failed because no resource bundles got generated.
  2607. keys: ${JSON.stringify(keys)}.
  2608. resourceIds: ${JSON.stringify(this.resourceIds)}.`);
  2609. }
  2610. return translations;
  2611. }
  2612. formatMessages(keys) {
  2613. return this.formatWithFallback(keys, messageFromBundle);
  2614. }
  2615. formatValues(keys) {
  2616. return this.formatWithFallback(keys, valueFromBundle);
  2617. }
  2618. async formatValue(id, args) {
  2619. const [val] = await this.formatValues([{
  2620. id,
  2621. args
  2622. }]);
  2623. return val;
  2624. }
  2625. handleEvent() {
  2626. this.onChange();
  2627. }
  2628. onChange(eager = false) {
  2629. this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds));
  2630. if (eager) {
  2631. this.bundles.touchNext(2);
  2632. }
  2633. }
  2634. }
  2635. function valueFromBundle(bundle, errors, message, args) {
  2636. if (message.value) {
  2637. return bundle.formatPattern(message.value, args, errors);
  2638. }
  2639. return null;
  2640. }
  2641. function messageFromBundle(bundle, errors, message, args) {
  2642. const formatted = {
  2643. value: null,
  2644. attributes: null
  2645. };
  2646. if (message.value) {
  2647. formatted.value = bundle.formatPattern(message.value, args, errors);
  2648. }
  2649. let attrNames = Object.keys(message.attributes);
  2650. if (attrNames.length > 0) {
  2651. formatted.attributes = new Array(attrNames.length);
  2652. for (let [i, name] of attrNames.entries()) {
  2653. let value = bundle.formatPattern(message.attributes[name], args, errors);
  2654. formatted.attributes[i] = {
  2655. name,
  2656. value
  2657. };
  2658. }
  2659. }
  2660. return formatted;
  2661. }
  2662. function keysFromBundle(method, bundle, keys, translations) {
  2663. const messageErrors = [];
  2664. const missingIds = new Set();
  2665. keys.forEach(({
  2666. id,
  2667. args
  2668. }, i) => {
  2669. if (translations[i] !== undefined) {
  2670. return;
  2671. }
  2672. let message = bundle.getMessage(id);
  2673. if (message) {
  2674. messageErrors.length = 0;
  2675. translations[i] = method(bundle, messageErrors, message, args);
  2676. if (messageErrors.length > 0 && typeof console !== "undefined") {
  2677. const locale = bundle.locales[0];
  2678. const errors = messageErrors.join(", ");
  2679. console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`);
  2680. }
  2681. } else {
  2682. missingIds.add(id);
  2683. }
  2684. });
  2685. return missingIds;
  2686. }
  2687. ;// ./node_modules/@fluent/dom/esm/dom_localization.js
  2688. const L10NID_ATTR_NAME = "data-l10n-id";
  2689. const L10NARGS_ATTR_NAME = "data-l10n-args";
  2690. const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`;
  2691. class DOMLocalization extends Localization {
  2692. constructor(resourceIds, generateBundles) {
  2693. super(resourceIds, generateBundles);
  2694. this.roots = new Set();
  2695. this.pendingrAF = null;
  2696. this.pendingElements = new Set();
  2697. this.windowElement = null;
  2698. this.mutationObserver = null;
  2699. this.observerConfig = {
  2700. attributes: true,
  2701. characterData: false,
  2702. childList: true,
  2703. subtree: true,
  2704. attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME]
  2705. };
  2706. }
  2707. onChange(eager = false) {
  2708. super.onChange(eager);
  2709. if (this.roots) {
  2710. this.translateRoots();
  2711. }
  2712. }
  2713. setAttributes(element, id, args) {
  2714. element.setAttribute(L10NID_ATTR_NAME, id);
  2715. if (args) {
  2716. element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args));
  2717. } else {
  2718. element.removeAttribute(L10NARGS_ATTR_NAME);
  2719. }
  2720. return element;
  2721. }
  2722. getAttributes(element) {
  2723. return {
  2724. id: element.getAttribute(L10NID_ATTR_NAME),
  2725. args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null)
  2726. };
  2727. }
  2728. connectRoot(newRoot) {
  2729. for (const root of this.roots) {
  2730. if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) {
  2731. throw new Error("Cannot add a root that overlaps with existing root.");
  2732. }
  2733. }
  2734. if (this.windowElement) {
  2735. if (this.windowElement !== newRoot.ownerDocument.defaultView) {
  2736. throw new Error(`Cannot connect a root:
  2737. DOMLocalization already has a root from a different window.`);
  2738. }
  2739. } else {
  2740. this.windowElement = newRoot.ownerDocument.defaultView;
  2741. this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations));
  2742. }
  2743. this.roots.add(newRoot);
  2744. this.mutationObserver.observe(newRoot, this.observerConfig);
  2745. }
  2746. disconnectRoot(root) {
  2747. this.roots.delete(root);
  2748. this.pauseObserving();
  2749. if (this.roots.size === 0) {
  2750. this.mutationObserver = null;
  2751. if (this.windowElement && this.pendingrAF) {
  2752. this.windowElement.cancelAnimationFrame(this.pendingrAF);
  2753. }
  2754. this.windowElement = null;
  2755. this.pendingrAF = null;
  2756. this.pendingElements.clear();
  2757. return true;
  2758. }
  2759. this.resumeObserving();
  2760. return false;
  2761. }
  2762. translateRoots() {
  2763. const roots = Array.from(this.roots);
  2764. return Promise.all(roots.map(root => this.translateFragment(root)));
  2765. }
  2766. pauseObserving() {
  2767. if (!this.mutationObserver) {
  2768. return;
  2769. }
  2770. this.translateMutations(this.mutationObserver.takeRecords());
  2771. this.mutationObserver.disconnect();
  2772. }
  2773. resumeObserving() {
  2774. if (!this.mutationObserver) {
  2775. return;
  2776. }
  2777. for (const root of this.roots) {
  2778. this.mutationObserver.observe(root, this.observerConfig);
  2779. }
  2780. }
  2781. translateMutations(mutations) {
  2782. for (const mutation of mutations) {
  2783. switch (mutation.type) {
  2784. case "attributes":
  2785. if (mutation.target.hasAttribute("data-l10n-id")) {
  2786. this.pendingElements.add(mutation.target);
  2787. }
  2788. break;
  2789. case "childList":
  2790. for (const addedNode of mutation.addedNodes) {
  2791. if (addedNode.nodeType === addedNode.ELEMENT_NODE) {
  2792. if (addedNode.childElementCount) {
  2793. for (const element of this.getTranslatables(addedNode)) {
  2794. this.pendingElements.add(element);
  2795. }
  2796. } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) {
  2797. this.pendingElements.add(addedNode);
  2798. }
  2799. }
  2800. }
  2801. break;
  2802. }
  2803. }
  2804. if (this.pendingElements.size > 0) {
  2805. if (this.pendingrAF === null) {
  2806. this.pendingrAF = this.windowElement.requestAnimationFrame(() => {
  2807. this.translateElements(Array.from(this.pendingElements));
  2808. this.pendingElements.clear();
  2809. this.pendingrAF = null;
  2810. });
  2811. }
  2812. }
  2813. }
  2814. translateFragment(frag) {
  2815. return this.translateElements(this.getTranslatables(frag));
  2816. }
  2817. async translateElements(elements) {
  2818. if (!elements.length) {
  2819. return undefined;
  2820. }
  2821. const keys = elements.map(this.getKeysForElement);
  2822. const translations = await this.formatMessages(keys);
  2823. return this.applyTranslations(elements, translations);
  2824. }
  2825. applyTranslations(elements, translations) {
  2826. this.pauseObserving();
  2827. for (let i = 0; i < elements.length; i++) {
  2828. if (translations[i] !== undefined) {
  2829. translateElement(elements[i], translations[i]);
  2830. }
  2831. }
  2832. this.resumeObserving();
  2833. }
  2834. getTranslatables(element) {
  2835. const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY));
  2836. if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) {
  2837. nodes.push(element);
  2838. }
  2839. return nodes;
  2840. }
  2841. getKeysForElement(element) {
  2842. return {
  2843. id: element.getAttribute(L10NID_ATTR_NAME),
  2844. args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null)
  2845. };
  2846. }
  2847. }
  2848. ;// ./node_modules/@fluent/dom/esm/index.js
  2849. ;// ./web/l10n.js
  2850. class L10n {
  2851. #dir;
  2852. #elements;
  2853. #lang;
  2854. #l10n;
  2855. constructor({
  2856. lang,
  2857. isRTL
  2858. }, l10n = null) {
  2859. this.#lang = L10n.#fixupLangCode(lang);
  2860. this.#l10n = l10n;
  2861. this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr";
  2862. }
  2863. _setL10n(l10n) {
  2864. this.#l10n = l10n;
  2865. }
  2866. getLanguage() {
  2867. return this.#lang;
  2868. }
  2869. getDirection() {
  2870. return this.#dir;
  2871. }
  2872. async get(ids, args = null, fallback) {
  2873. if (Array.isArray(ids)) {
  2874. ids = ids.map(id => ({
  2875. id
  2876. }));
  2877. const messages = await this.#l10n.formatMessages(ids);
  2878. return messages.map(message => message.value);
  2879. }
  2880. const messages = await this.#l10n.formatMessages([{
  2881. id: ids,
  2882. args
  2883. }]);
  2884. return messages[0]?.value || fallback;
  2885. }
  2886. async translate(element) {
  2887. (this.#elements ||= new Set()).add(element);
  2888. try {
  2889. this.#l10n.connectRoot(element);
  2890. await this.#l10n.translateRoots();
  2891. } catch {}
  2892. }
  2893. async translateOnce(element) {
  2894. try {
  2895. await this.#l10n.translateElements([element]);
  2896. } catch (ex) {
  2897. console.error("translateOnce:", ex);
  2898. }
  2899. }
  2900. async destroy() {
  2901. if (this.#elements) {
  2902. for (const element of this.#elements) {
  2903. this.#l10n.disconnectRoot(element);
  2904. }
  2905. this.#elements.clear();
  2906. this.#elements = null;
  2907. }
  2908. this.#l10n.pauseObserving();
  2909. }
  2910. pause() {
  2911. this.#l10n.pauseObserving();
  2912. }
  2913. resume() {
  2914. this.#l10n.resumeObserving();
  2915. }
  2916. static #fixupLangCode(langCode) {
  2917. langCode = langCode?.toLowerCase() || "en-us";
  2918. const PARTIAL_LANG_CODES = {
  2919. en: "en-us",
  2920. es: "es-es",
  2921. fy: "fy-nl",
  2922. ga: "ga-ie",
  2923. gu: "gu-in",
  2924. hi: "hi-in",
  2925. hy: "hy-am",
  2926. nb: "nb-no",
  2927. ne: "ne-np",
  2928. nn: "nn-no",
  2929. pa: "pa-in",
  2930. pt: "pt-pt",
  2931. sv: "sv-se",
  2932. zh: "zh-cn"
  2933. };
  2934. return PARTIAL_LANG_CODES[langCode] || langCode;
  2935. }
  2936. static #isRTL(lang) {
  2937. const shortCode = lang.split("-", 1)[0];
  2938. return ["ar", "he", "fa", "ps", "ur"].includes(shortCode);
  2939. }
  2940. }
  2941. const GenericL10n = null;
  2942. ;// ./web/genericl10n.js
  2943. function PLATFORM() {
  2944. const {
  2945. isAndroid,
  2946. isLinux,
  2947. isMac,
  2948. isWindows
  2949. } = FeatureTest.platform;
  2950. if (isLinux) {
  2951. return "linux";
  2952. }
  2953. if (isWindows) {
  2954. return "windows";
  2955. }
  2956. if (isMac) {
  2957. return "macos";
  2958. }
  2959. if (isAndroid) {
  2960. return "android";
  2961. }
  2962. return "other";
  2963. }
  2964. function createBundle(lang, text) {
  2965. const resource = new FluentResource(text);
  2966. const bundle = new FluentBundle(lang, {
  2967. functions: {
  2968. PLATFORM
  2969. }
  2970. });
  2971. const errors = bundle.addResource(resource);
  2972. if (errors.length) {
  2973. console.error("L10n errors", errors);
  2974. }
  2975. return bundle;
  2976. }
  2977. class genericl10n_GenericL10n extends L10n {
  2978. constructor(lang) {
  2979. super({
  2980. lang
  2981. });
  2982. const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage());
  2983. this._setL10n(new DOMLocalization([], generateBundles));
  2984. }
  2985. static async *#generateBundles(defaultLang, baseLang) {
  2986. const {
  2987. baseURL,
  2988. paths
  2989. } = await this.#getPaths();
  2990. const langs = [baseLang];
  2991. if (defaultLang !== baseLang) {
  2992. const shortLang = baseLang.split("-", 1)[0];
  2993. if (shortLang !== baseLang) {
  2994. langs.push(shortLang);
  2995. }
  2996. langs.push(defaultLang);
  2997. }
  2998. const bundles = langs.map(lang => [lang, this.#createBundle(lang, baseURL, paths)]);
  2999. for (const [lang, bundlePromise] of bundles) {
  3000. const bundle = await bundlePromise;
  3001. if (bundle) {
  3002. yield bundle;
  3003. } else if (lang === "en-us") {
  3004. yield this.#createBundleFallback(lang);
  3005. }
  3006. }
  3007. }
  3008. static async #createBundle(lang, baseURL, paths) {
  3009. const path = paths[lang];
  3010. if (!path) {
  3011. return null;
  3012. }
  3013. const url = new URL(path, baseURL);
  3014. const text = await fetchData(url, "text");
  3015. return createBundle(lang, text);
  3016. }
  3017. static async #getPaths() {
  3018. try {
  3019. const {
  3020. href
  3021. } = document.querySelector(`link[type="application/l10n"]`);
  3022. const paths = await fetchData(href, "json");
  3023. return {
  3024. baseURL: href.substring(0, href.lastIndexOf("/") + 1) || "./",
  3025. paths
  3026. };
  3027. } catch {}
  3028. return {
  3029. baseURL: "./",
  3030. paths: Object.create(null)
  3031. };
  3032. }
  3033. static async *#generateBundlesFallback(lang) {
  3034. yield this.#createBundleFallback(lang);
  3035. }
  3036. static async #createBundleFallback(lang) {
  3037. 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-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $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-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\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-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\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-signature-button =\n .title = Add signature\npdfjs-editor-signature-button-label = Add signature\npdfjs-editor-highlight-editor =\n .aria-label = Highlight editor\npdfjs-editor-ink-editor =\n .aria-label = Drawing editor\npdfjs-editor-signature-editor1 =\n .aria-description = Signature editor: { $description }\npdfjs-editor-stamp-editor =\n .aria-label = Image editor\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-remove-signature-button =\n .title = Remove signature\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-editor-add-signature-container =\n .aria-label = Signature controls and saved signatures\npdfjs-editor-signature-add-signature-button =\n .title = Add new signature\npdfjs-editor-signature-add-signature-button-label = Add new signature\npdfjs-editor-add-saved-signature-button =\n .title = Saved signature: { $description }\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-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-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = 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\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-signature = Signature removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close\npdfjs-editor-add-signature-dialog-label = This modal allows the user to create a signature to add to a PDF document. The user can edit the name (which also serves as the alt text), and optionally save the signature for repeated use.\npdfjs-editor-add-signature-dialog-title = Add a signature\npdfjs-editor-add-signature-type-button = Type\n .title = Type\npdfjs-editor-add-signature-draw-button = Draw\n .title = Draw\npdfjs-editor-add-signature-image-button = Image\n .title = Image\npdfjs-editor-add-signature-type-input =\n .aria-label = Type your signature\n .placeholder = Type your signature\npdfjs-editor-add-signature-draw-placeholder = Draw your signature\npdfjs-editor-add-signature-draw-thickness-range-label = Thickness\npdfjs-editor-add-signature-draw-thickness-range =\n .title = Drawing thickness: { $thickness }\npdfjs-editor-add-signature-image-placeholder = Drag a file here to upload\npdfjs-editor-add-signature-image-browse-link =\n { PLATFORM() ->\n [macos] Or choose image files\n *[other] Or browse image files\n }\npdfjs-editor-add-signature-description-label = Description (alt text)\npdfjs-editor-add-signature-description-input =\n .title = Description (alt text)\npdfjs-editor-add-signature-description-default-when-drawing = Signature\npdfjs-editor-add-signature-clear-button-label = Clear signature\npdfjs-editor-add-signature-clear-button =\n .title = Clear signature\npdfjs-editor-add-signature-save-checkbox = Save signature\npdfjs-editor-add-signature-save-warning-message = You\u2019ve reached the limit of 5 saved signatures. Remove one to save more.\npdfjs-editor-add-signature-image-upload-error-title = Couldn\u2019t upload image\npdfjs-editor-add-signature-image-upload-error-description = Check your network connection or try another image.\npdfjs-editor-add-signature-error-close-button = Close\npdfjs-editor-add-signature-cancel-button = Cancel\npdfjs-editor-add-signature-add-button = Add\npdfjs-editor-delete-signature-button1 =\n .title = Remove saved signature\npdfjs-editor-delete-signature-button-label1 = Remove saved signature\npdfjs-editor-add-signature-edit-button-label = Edit description\npdfjs-editor-edit-signature-dialog-title = Edit description\npdfjs-editor-edit-signature-update-button = Update";
  3038. return createBundle(lang, text);
  3039. }
  3040. }
  3041. ;// ./web/generic_scripting.js
  3042. async function docProperties(pdfDocument) {
  3043. const url = "",
  3044. baseUrl = "";
  3045. const {
  3046. info,
  3047. metadata,
  3048. contentDispositionFilename,
  3049. contentLength
  3050. } = await pdfDocument.getMetadata();
  3051. return {
  3052. ...info,
  3053. baseURL: baseUrl,
  3054. filesize: contentLength || (await pdfDocument.getDownloadInfo()).length,
  3055. filename: contentDispositionFilename || getPdfFilenameFromUrl(url),
  3056. metadata: metadata?.getRaw(),
  3057. authors: metadata?.get("dc:creator"),
  3058. numPages: pdfDocument.numPages,
  3059. URL: url
  3060. };
  3061. }
  3062. class GenericScripting {
  3063. constructor(sandboxBundleSrc) {
  3064. this._ready = new Promise((resolve, reject) => {
  3065. const sandbox = import(
  3066. /*webpackIgnore: true*/
  3067. /*@vite-ignore*/
  3068. sandboxBundleSrc);
  3069. sandbox.then(pdfjsSandbox => {
  3070. resolve(pdfjsSandbox.QuickJSSandbox());
  3071. }).catch(reject);
  3072. });
  3073. }
  3074. async createSandbox(data) {
  3075. const sandbox = await this._ready;
  3076. sandbox.create(data);
  3077. }
  3078. async dispatchEventInSandbox(event) {
  3079. const sandbox = await this._ready;
  3080. setTimeout(() => sandbox.dispatchEvent(event), 0);
  3081. }
  3082. async destroySandbox() {
  3083. const sandbox = await this._ready;
  3084. sandbox.nukeSandbox();
  3085. }
  3086. }
  3087. ;// ./web/generic_signature_storage.js
  3088. const KEY_STORAGE = "pdfjs.signature";
  3089. class SignatureStorage {
  3090. #eventBus;
  3091. #signatures = null;
  3092. #signal = null;
  3093. constructor(eventBus, signal) {
  3094. this.#eventBus = eventBus;
  3095. this.#signal = signal;
  3096. }
  3097. #save() {
  3098. localStorage.setItem(KEY_STORAGE, JSON.stringify(Object.fromEntries(this.#signatures)));
  3099. }
  3100. async getAll() {
  3101. if (this.#signal) {
  3102. window.addEventListener("storage", ({
  3103. key
  3104. }) => {
  3105. if (key === KEY_STORAGE) {
  3106. this.#signatures = null;
  3107. this.#eventBus?.dispatch("storedsignatureschanged", {
  3108. source: this
  3109. });
  3110. }
  3111. }, {
  3112. signal: this.#signal
  3113. });
  3114. this.#signal = null;
  3115. }
  3116. if (!this.#signatures) {
  3117. this.#signatures = new Map();
  3118. const data = localStorage.getItem(KEY_STORAGE);
  3119. if (data) {
  3120. for (const [key, value] of Object.entries(JSON.parse(data))) {
  3121. this.#signatures.set(key, value);
  3122. }
  3123. }
  3124. }
  3125. return this.#signatures;
  3126. }
  3127. async isFull() {
  3128. return (await this.size()) === 5;
  3129. }
  3130. async size() {
  3131. return (await this.getAll()).size;
  3132. }
  3133. async create(data) {
  3134. if (await this.isFull()) {
  3135. return null;
  3136. }
  3137. const uuid = getUuid();
  3138. this.#signatures.set(uuid, data);
  3139. this.#save();
  3140. return uuid;
  3141. }
  3142. async delete(uuid) {
  3143. const signatures = await this.getAll();
  3144. if (!signatures.has(uuid)) {
  3145. return false;
  3146. }
  3147. signatures.delete(uuid);
  3148. this.#save();
  3149. return true;
  3150. }
  3151. }
  3152. ;// ./web/genericcom.js
  3153. function initCom(app) {}
  3154. class Preferences extends BasePreferences {
  3155. async _writeToStorage(prefObj) {
  3156. localStorage.setItem("pdfjs.preferences", JSON.stringify(prefObj));
  3157. }
  3158. async _readFromStorage(prefObj) {
  3159. return {
  3160. prefs: JSON.parse(localStorage.getItem("pdfjs.preferences"))
  3161. };
  3162. }
  3163. }
  3164. class ExternalServices extends BaseExternalServices {
  3165. async createL10n() {
  3166. return new genericl10n_GenericL10n(AppOptions.get("localeProperties")?.lang);
  3167. }
  3168. createScripting() {
  3169. return new GenericScripting(AppOptions.get("sandboxBundleSrc"));
  3170. }
  3171. createSignatureStorage(eventBus, signal) {
  3172. return new SignatureStorage(eventBus, signal);
  3173. }
  3174. }
  3175. class MLManager {
  3176. async isEnabledFor(_name) {
  3177. return false;
  3178. }
  3179. async deleteModel(_service) {
  3180. return null;
  3181. }
  3182. isReady(_name) {
  3183. return false;
  3184. }
  3185. guess(_data) {}
  3186. toggleService(_name, _enabled) {}
  3187. }
  3188. ;// ./web/new_alt_text_manager.js
  3189. class NewAltTextManager {
  3190. #boundCancel = this.#cancel.bind(this);
  3191. #createAutomaticallyButton;
  3192. #currentEditor = null;
  3193. #cancelButton;
  3194. #descriptionContainer;
  3195. #dialog;
  3196. #disclaimer;
  3197. #downloadModel;
  3198. #downloadModelDescription;
  3199. #eventBus;
  3200. #firstTime = false;
  3201. #guessedAltText;
  3202. #hasAI = null;
  3203. #isEditing = null;
  3204. #imagePreview;
  3205. #imageData;
  3206. #isAILoading = false;
  3207. #wasAILoading = false;
  3208. #learnMore;
  3209. #notNowButton;
  3210. #overlayManager;
  3211. #textarea;
  3212. #title;
  3213. #uiManager;
  3214. #previousAltText = null;
  3215. constructor({
  3216. descriptionContainer,
  3217. dialog,
  3218. imagePreview,
  3219. cancelButton,
  3220. disclaimer,
  3221. notNowButton,
  3222. saveButton,
  3223. textarea,
  3224. learnMore,
  3225. errorCloseButton,
  3226. createAutomaticallyButton,
  3227. downloadModel,
  3228. downloadModelDescription,
  3229. title
  3230. }, overlayManager, eventBus) {
  3231. this.#cancelButton = cancelButton;
  3232. this.#createAutomaticallyButton = createAutomaticallyButton;
  3233. this.#descriptionContainer = descriptionContainer;
  3234. this.#dialog = dialog;
  3235. this.#disclaimer = disclaimer;
  3236. this.#notNowButton = notNowButton;
  3237. this.#imagePreview = imagePreview;
  3238. this.#textarea = textarea;
  3239. this.#learnMore = learnMore;
  3240. this.#title = title;
  3241. this.#downloadModel = downloadModel;
  3242. this.#downloadModelDescription = downloadModelDescription;
  3243. this.#overlayManager = overlayManager;
  3244. this.#eventBus = eventBus;
  3245. dialog.addEventListener("close", this.#close.bind(this));
  3246. dialog.addEventListener("contextmenu", event => {
  3247. if (event.target !== this.#textarea) {
  3248. event.preventDefault();
  3249. }
  3250. });
  3251. cancelButton.addEventListener("click", this.#boundCancel);
  3252. notNowButton.addEventListener("click", this.#boundCancel);
  3253. saveButton.addEventListener("click", this.#save.bind(this));
  3254. errorCloseButton.addEventListener("click", () => {
  3255. this.#toggleError(false);
  3256. });
  3257. createAutomaticallyButton.addEventListener("click", async () => {
  3258. const checked = createAutomaticallyButton.getAttribute("aria-pressed") !== "true";
  3259. this.#currentEditor._reportTelemetry({
  3260. action: "pdfjs.image.alt_text.ai_generation_check",
  3261. data: {
  3262. status: checked
  3263. }
  3264. });
  3265. if (this.#uiManager) {
  3266. this.#uiManager.setPreference("enableGuessAltText", checked);
  3267. await this.#uiManager.mlManager.toggleService("altText", checked);
  3268. }
  3269. this.#toggleGuessAltText(checked, false);
  3270. });
  3271. textarea.addEventListener("focus", () => {
  3272. this.#wasAILoading = this.#isAILoading;
  3273. this.#toggleLoading(false);
  3274. this.#toggleTitleAndDisclaimer();
  3275. });
  3276. textarea.addEventListener("blur", () => {
  3277. if (!textarea.value) {
  3278. this.#toggleLoading(this.#wasAILoading);
  3279. }
  3280. this.#toggleTitleAndDisclaimer();
  3281. });
  3282. textarea.addEventListener("input", () => {
  3283. this.#toggleTitleAndDisclaimer();
  3284. });
  3285. eventBus._on("enableguessalttext", ({
  3286. value
  3287. }) => {
  3288. this.#toggleGuessAltText(value, false);
  3289. });
  3290. this.#overlayManager.register(dialog);
  3291. this.#learnMore.addEventListener("click", () => {
  3292. this.#currentEditor._reportTelemetry({
  3293. action: "pdfjs.image.alt_text.info",
  3294. data: {
  3295. topic: "alt_text"
  3296. }
  3297. });
  3298. });
  3299. }
  3300. #toggleLoading(value) {
  3301. if (!this.#uiManager || this.#isAILoading === value) {
  3302. return;
  3303. }
  3304. this.#isAILoading = value;
  3305. this.#descriptionContainer.classList.toggle("loading", value);
  3306. }
  3307. #toggleError(value) {
  3308. if (!this.#uiManager) {
  3309. return;
  3310. }
  3311. this.#dialog.classList.toggle("error", value);
  3312. }
  3313. async #toggleGuessAltText(value, isInitial = false) {
  3314. if (!this.#uiManager) {
  3315. return;
  3316. }
  3317. this.#dialog.classList.toggle("aiDisabled", !value);
  3318. this.#createAutomaticallyButton.setAttribute("aria-pressed", value);
  3319. if (value) {
  3320. const {
  3321. altTextLearnMoreUrl
  3322. } = this.#uiManager.mlManager;
  3323. if (altTextLearnMoreUrl) {
  3324. this.#learnMore.href = altTextLearnMoreUrl;
  3325. }
  3326. this.#mlGuessAltText(isInitial);
  3327. } else {
  3328. this.#toggleLoading(false);
  3329. this.#isAILoading = false;
  3330. this.#toggleTitleAndDisclaimer();
  3331. }
  3332. }
  3333. #toggleNotNow() {
  3334. this.#notNowButton.classList.toggle("hidden", !this.#firstTime);
  3335. this.#cancelButton.classList.toggle("hidden", this.#firstTime);
  3336. }
  3337. #toggleAI(value) {
  3338. if (!this.#uiManager || this.#hasAI === value) {
  3339. return;
  3340. }
  3341. this.#hasAI = value;
  3342. this.#dialog.classList.toggle("noAi", !value);
  3343. this.#toggleTitleAndDisclaimer();
  3344. }
  3345. #toggleTitleAndDisclaimer() {
  3346. const visible = this.#isAILoading || this.#guessedAltText && this.#guessedAltText === this.#textarea.value;
  3347. this.#disclaimer.hidden = !visible;
  3348. const isEditing = this.#isAILoading || !!this.#textarea.value;
  3349. if (this.#isEditing === isEditing) {
  3350. return;
  3351. }
  3352. this.#isEditing = isEditing;
  3353. this.#title.setAttribute("data-l10n-id", isEditing ? "pdfjs-editor-new-alt-text-dialog-edit-label" : "pdfjs-editor-new-alt-text-dialog-add-label");
  3354. }
  3355. async #mlGuessAltText(isInitial) {
  3356. if (this.#isAILoading) {
  3357. return;
  3358. }
  3359. if (this.#textarea.value) {
  3360. return;
  3361. }
  3362. if (isInitial && this.#previousAltText !== null) {
  3363. return;
  3364. }
  3365. this.#guessedAltText = this.#currentEditor.guessedAltText;
  3366. if (this.#previousAltText === null && this.#guessedAltText) {
  3367. this.#addAltText(this.#guessedAltText);
  3368. return;
  3369. }
  3370. this.#toggleLoading(true);
  3371. this.#toggleTitleAndDisclaimer();
  3372. let hasError = false;
  3373. try {
  3374. const altText = await this.#currentEditor.mlGuessAltText(this.#imageData, false);
  3375. if (altText) {
  3376. this.#guessedAltText = altText;
  3377. this.#wasAILoading = this.#isAILoading;
  3378. if (this.#isAILoading) {
  3379. this.#addAltText(altText);
  3380. }
  3381. }
  3382. } catch (e) {
  3383. console.error(e);
  3384. hasError = true;
  3385. }
  3386. this.#toggleLoading(false);
  3387. this.#toggleTitleAndDisclaimer();
  3388. if (hasError && this.#uiManager) {
  3389. this.#toggleError(true);
  3390. }
  3391. }
  3392. #addAltText(altText) {
  3393. if (!this.#uiManager || this.#textarea.value) {
  3394. return;
  3395. }
  3396. this.#textarea.value = altText;
  3397. this.#toggleTitleAndDisclaimer();
  3398. }
  3399. #setProgress() {
  3400. this.#downloadModel.classList.toggle("hidden", false);
  3401. const callback = async ({
  3402. detail: {
  3403. finished,
  3404. total,
  3405. totalLoaded
  3406. }
  3407. }) => {
  3408. const ONE_MEGA_BYTES = 1e6;
  3409. totalLoaded = Math.min(0.99 * total, totalLoaded);
  3410. const totalSize = this.#downloadModelDescription.ariaValueMax = Math.round(total / ONE_MEGA_BYTES);
  3411. const downloadedSize = this.#downloadModelDescription.ariaValueNow = Math.round(totalLoaded / ONE_MEGA_BYTES);
  3412. this.#downloadModelDescription.setAttribute("data-l10n-args", JSON.stringify({
  3413. totalSize,
  3414. downloadedSize
  3415. }));
  3416. if (!finished) {
  3417. return;
  3418. }
  3419. this.#eventBus._off("loadaiengineprogress", callback);
  3420. this.#downloadModel.classList.toggle("hidden", true);
  3421. this.#toggleAI(true);
  3422. if (!this.#uiManager) {
  3423. return;
  3424. }
  3425. const {
  3426. mlManager
  3427. } = this.#uiManager;
  3428. mlManager.toggleService("altText", true);
  3429. this.#toggleGuessAltText(await mlManager.isEnabledFor("altText"), true);
  3430. };
  3431. this.#eventBus._on("loadaiengineprogress", callback);
  3432. }
  3433. async editAltText(uiManager, editor, firstTime) {
  3434. if (this.#currentEditor || !editor) {
  3435. return;
  3436. }
  3437. if (firstTime && editor.hasAltTextData()) {
  3438. editor.altTextFinish();
  3439. return;
  3440. }
  3441. this.#firstTime = firstTime;
  3442. let {
  3443. mlManager
  3444. } = uiManager;
  3445. let hasAI = !!mlManager;
  3446. this.#toggleTitleAndDisclaimer();
  3447. if (mlManager && !mlManager.isReady("altText")) {
  3448. hasAI = false;
  3449. if (mlManager.hasProgress) {
  3450. this.#setProgress();
  3451. } else {
  3452. mlManager = null;
  3453. }
  3454. } else {
  3455. this.#downloadModel.classList.toggle("hidden", true);
  3456. }
  3457. const isAltTextEnabledPromise = mlManager?.isEnabledFor("altText");
  3458. this.#currentEditor = editor;
  3459. this.#uiManager = uiManager;
  3460. this.#uiManager.removeEditListeners();
  3461. ({
  3462. altText: this.#previousAltText
  3463. } = editor.altTextData);
  3464. this.#textarea.value = this.#previousAltText ?? "";
  3465. const AI_MAX_IMAGE_DIMENSION = 224;
  3466. const MAX_PREVIEW_DIMENSION = 180;
  3467. let canvas, width, height;
  3468. if (mlManager) {
  3469. ({
  3470. canvas,
  3471. width,
  3472. height,
  3473. imageData: this.#imageData
  3474. } = editor.copyCanvas(AI_MAX_IMAGE_DIMENSION, MAX_PREVIEW_DIMENSION, true));
  3475. if (hasAI) {
  3476. this.#toggleGuessAltText(await isAltTextEnabledPromise, true);
  3477. }
  3478. } else {
  3479. ({
  3480. canvas,
  3481. width,
  3482. height
  3483. } = editor.copyCanvas(AI_MAX_IMAGE_DIMENSION, MAX_PREVIEW_DIMENSION, false));
  3484. }
  3485. canvas.setAttribute("role", "presentation");
  3486. const {
  3487. style
  3488. } = canvas;
  3489. style.width = `${width}px`;
  3490. style.height = `${height}px`;
  3491. this.#imagePreview.append(canvas);
  3492. this.#toggleNotNow();
  3493. this.#toggleAI(hasAI);
  3494. this.#toggleError(false);
  3495. try {
  3496. await this.#overlayManager.open(this.#dialog);
  3497. } catch (ex) {
  3498. this.#close();
  3499. throw ex;
  3500. }
  3501. }
  3502. #cancel() {
  3503. this.#currentEditor.altTextData = {
  3504. cancel: true
  3505. };
  3506. const altText = this.#textarea.value.trim();
  3507. this.#currentEditor._reportTelemetry({
  3508. action: "pdfjs.image.alt_text.dismiss",
  3509. data: {
  3510. alt_text_type: altText ? "present" : "empty",
  3511. flow: this.#firstTime ? "image_add" : "alt_text_edit"
  3512. }
  3513. });
  3514. this.#currentEditor._reportTelemetry({
  3515. action: "pdfjs.image.image_added",
  3516. data: {
  3517. alt_text_modal: true,
  3518. alt_text_type: "skipped"
  3519. }
  3520. });
  3521. this.#finish();
  3522. }
  3523. #finish() {
  3524. this.#overlayManager.closeIfActive(this.#dialog);
  3525. }
  3526. #close() {
  3527. const canvas = this.#imagePreview.firstChild;
  3528. canvas.remove();
  3529. canvas.width = canvas.height = 0;
  3530. this.#imageData = null;
  3531. this.#toggleLoading(false);
  3532. this.#uiManager?.addEditListeners();
  3533. this.#currentEditor.altTextFinish();
  3534. this.#uiManager?.setSelected(this.#currentEditor);
  3535. this.#currentEditor = null;
  3536. this.#uiManager = null;
  3537. }
  3538. #extractWords(text) {
  3539. return new Set(text.toLowerCase().split(/[^\p{L}\p{N}]+/gu).filter(x => !!x));
  3540. }
  3541. #save() {
  3542. const altText = this.#textarea.value.trim();
  3543. this.#currentEditor.altTextData = {
  3544. altText,
  3545. decorative: false
  3546. };
  3547. this.#currentEditor.altTextData.guessedAltText = this.#guessedAltText;
  3548. if (this.#guessedAltText && this.#guessedAltText !== altText) {
  3549. const guessedWords = this.#extractWords(this.#guessedAltText);
  3550. const words = this.#extractWords(altText);
  3551. this.#currentEditor._reportTelemetry({
  3552. action: "pdfjs.image.alt_text.user_edit",
  3553. data: {
  3554. total_words: guessedWords.size,
  3555. words_removed: guessedWords.difference(words).size,
  3556. words_added: words.difference(guessedWords).size
  3557. }
  3558. });
  3559. }
  3560. this.#currentEditor._reportTelemetry({
  3561. action: "pdfjs.image.image_added",
  3562. data: {
  3563. alt_text_modal: true,
  3564. alt_text_type: altText ? "present" : "empty"
  3565. }
  3566. });
  3567. this.#currentEditor._reportTelemetry({
  3568. action: "pdfjs.image.alt_text.save",
  3569. data: {
  3570. alt_text_type: altText ? "present" : "empty",
  3571. flow: this.#firstTime ? "image_add" : "alt_text_edit"
  3572. }
  3573. });
  3574. this.#finish();
  3575. }
  3576. destroy() {
  3577. this.#uiManager = null;
  3578. this.#finish();
  3579. }
  3580. }
  3581. class ImageAltTextSettings {
  3582. #aiModelSettings;
  3583. #createModelButton;
  3584. #downloadModelButton;
  3585. #dialog;
  3586. #eventBus;
  3587. #mlManager;
  3588. #overlayManager;
  3589. #showAltTextDialogButton;
  3590. constructor({
  3591. dialog,
  3592. createModelButton,
  3593. aiModelSettings,
  3594. learnMore,
  3595. closeButton,
  3596. deleteModelButton,
  3597. downloadModelButton,
  3598. showAltTextDialogButton
  3599. }, overlayManager, eventBus, mlManager) {
  3600. this.#dialog = dialog;
  3601. this.#aiModelSettings = aiModelSettings;
  3602. this.#createModelButton = createModelButton;
  3603. this.#downloadModelButton = downloadModelButton;
  3604. this.#showAltTextDialogButton = showAltTextDialogButton;
  3605. this.#overlayManager = overlayManager;
  3606. this.#eventBus = eventBus;
  3607. this.#mlManager = mlManager;
  3608. const {
  3609. altTextLearnMoreUrl
  3610. } = mlManager;
  3611. if (altTextLearnMoreUrl) {
  3612. learnMore.href = altTextLearnMoreUrl;
  3613. }
  3614. dialog.addEventListener("contextmenu", noContextMenu);
  3615. createModelButton.addEventListener("click", async e => {
  3616. const checked = this.#togglePref("enableGuessAltText", e);
  3617. await mlManager.toggleService("altText", checked);
  3618. this.#reportTelemetry({
  3619. type: "stamp",
  3620. action: "pdfjs.image.alt_text.settings_ai_generation_check",
  3621. data: {
  3622. status: checked
  3623. }
  3624. });
  3625. });
  3626. showAltTextDialogButton.addEventListener("click", e => {
  3627. const checked = this.#togglePref("enableNewAltTextWhenAddingImage", e);
  3628. this.#reportTelemetry({
  3629. type: "stamp",
  3630. action: "pdfjs.image.alt_text.settings_edit_alt_text_check",
  3631. data: {
  3632. status: checked
  3633. }
  3634. });
  3635. });
  3636. deleteModelButton.addEventListener("click", this.#delete.bind(this, true));
  3637. downloadModelButton.addEventListener("click", this.#download.bind(this, true));
  3638. closeButton.addEventListener("click", this.#finish.bind(this));
  3639. learnMore.addEventListener("click", () => {
  3640. this.#reportTelemetry({
  3641. type: "stamp",
  3642. action: "pdfjs.image.alt_text.info",
  3643. data: {
  3644. topic: "ai_generation"
  3645. }
  3646. });
  3647. });
  3648. eventBus._on("enablealttextmodeldownload", ({
  3649. value
  3650. }) => {
  3651. if (value) {
  3652. this.#download(false);
  3653. } else {
  3654. this.#delete(false);
  3655. }
  3656. });
  3657. this.#overlayManager.register(dialog);
  3658. }
  3659. #reportTelemetry(data) {
  3660. this.#eventBus.dispatch("reporttelemetry", {
  3661. source: this,
  3662. details: {
  3663. type: "editing",
  3664. data
  3665. }
  3666. });
  3667. }
  3668. async #download(isFromUI = false) {
  3669. if (isFromUI) {
  3670. this.#downloadModelButton.disabled = true;
  3671. const span = this.#downloadModelButton.firstChild;
  3672. span.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-settings-downloading-model-button");
  3673. await this.#mlManager.downloadModel("altText");
  3674. span.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-settings-download-model-button");
  3675. this.#createModelButton.disabled = false;
  3676. this.#setPref("enableGuessAltText", true);
  3677. this.#mlManager.toggleService("altText", true);
  3678. this.#setPref("enableAltTextModelDownload", true);
  3679. this.#downloadModelButton.disabled = false;
  3680. }
  3681. this.#aiModelSettings.classList.toggle("download", false);
  3682. this.#createModelButton.setAttribute("aria-pressed", true);
  3683. }
  3684. async #delete(isFromUI = false) {
  3685. if (isFromUI) {
  3686. await this.#mlManager.deleteModel("altText");
  3687. this.#setPref("enableGuessAltText", false);
  3688. this.#setPref("enableAltTextModelDownload", false);
  3689. }
  3690. this.#aiModelSettings.classList.toggle("download", true);
  3691. this.#createModelButton.disabled = true;
  3692. this.#createModelButton.setAttribute("aria-pressed", false);
  3693. }
  3694. async open({
  3695. enableGuessAltText,
  3696. enableNewAltTextWhenAddingImage
  3697. }) {
  3698. const {
  3699. enableAltTextModelDownload
  3700. } = this.#mlManager;
  3701. this.#createModelButton.disabled = !enableAltTextModelDownload;
  3702. this.#createModelButton.setAttribute("aria-pressed", enableAltTextModelDownload && enableGuessAltText);
  3703. this.#showAltTextDialogButton.setAttribute("aria-pressed", enableNewAltTextWhenAddingImage);
  3704. this.#aiModelSettings.classList.toggle("download", !enableAltTextModelDownload);
  3705. await this.#overlayManager.open(this.#dialog);
  3706. this.#reportTelemetry({
  3707. type: "stamp",
  3708. action: "pdfjs.image.alt_text.settings_displayed"
  3709. });
  3710. }
  3711. #togglePref(name, {
  3712. target
  3713. }) {
  3714. const checked = target.getAttribute("aria-pressed") !== "true";
  3715. this.#setPref(name, checked);
  3716. target.setAttribute("aria-pressed", checked);
  3717. return checked;
  3718. }
  3719. #setPref(name, value) {
  3720. this.#eventBus.dispatch("setpreference", {
  3721. source: this,
  3722. name,
  3723. value
  3724. });
  3725. }
  3726. #finish() {
  3727. this.#overlayManager.closeIfActive(this.#dialog);
  3728. }
  3729. }
  3730. ;// ./web/alt_text_manager.js
  3731. class AltTextManager {
  3732. #clickAC = null;
  3733. #currentEditor = null;
  3734. #cancelButton;
  3735. #dialog;
  3736. #eventBus;
  3737. #hasUsedPointer = false;
  3738. #optionDescription;
  3739. #optionDecorative;
  3740. #overlayManager;
  3741. #saveButton;
  3742. #textarea;
  3743. #uiManager;
  3744. #previousAltText = null;
  3745. #resizeAC = null;
  3746. #svgElement = null;
  3747. #rectElement = null;
  3748. #container;
  3749. #telemetryData = null;
  3750. constructor({
  3751. dialog,
  3752. optionDescription,
  3753. optionDecorative,
  3754. textarea,
  3755. cancelButton,
  3756. saveButton
  3757. }, container, overlayManager, eventBus) {
  3758. this.#dialog = dialog;
  3759. this.#optionDescription = optionDescription;
  3760. this.#optionDecorative = optionDecorative;
  3761. this.#textarea = textarea;
  3762. this.#cancelButton = cancelButton;
  3763. this.#saveButton = saveButton;
  3764. this.#overlayManager = overlayManager;
  3765. this.#eventBus = eventBus;
  3766. this.#container = container;
  3767. const onUpdateUIState = this.#updateUIState.bind(this);
  3768. dialog.addEventListener("close", this.#close.bind(this));
  3769. dialog.addEventListener("contextmenu", event => {
  3770. if (event.target !== this.#textarea) {
  3771. event.preventDefault();
  3772. }
  3773. });
  3774. cancelButton.addEventListener("click", this.#finish.bind(this));
  3775. saveButton.addEventListener("click", this.#save.bind(this));
  3776. optionDescription.addEventListener("change", onUpdateUIState);
  3777. optionDecorative.addEventListener("change", onUpdateUIState);
  3778. this.#overlayManager.register(dialog);
  3779. }
  3780. #createSVGElement() {
  3781. if (this.#svgElement) {
  3782. return;
  3783. }
  3784. const svgFactory = new DOMSVGFactory();
  3785. const svg = this.#svgElement = svgFactory.createElement("svg");
  3786. svg.setAttribute("width", "0");
  3787. svg.setAttribute("height", "0");
  3788. const defs = svgFactory.createElement("defs");
  3789. svg.append(defs);
  3790. const mask = svgFactory.createElement("mask");
  3791. defs.append(mask);
  3792. mask.setAttribute("id", "alttext-manager-mask");
  3793. mask.setAttribute("maskContentUnits", "objectBoundingBox");
  3794. let rect = svgFactory.createElement("rect");
  3795. mask.append(rect);
  3796. rect.setAttribute("fill", "white");
  3797. rect.setAttribute("width", "1");
  3798. rect.setAttribute("height", "1");
  3799. rect.setAttribute("x", "0");
  3800. rect.setAttribute("y", "0");
  3801. rect = this.#rectElement = svgFactory.createElement("rect");
  3802. mask.append(rect);
  3803. rect.setAttribute("fill", "black");
  3804. this.#dialog.append(svg);
  3805. }
  3806. async editAltText(uiManager, editor) {
  3807. if (this.#currentEditor || !editor) {
  3808. return;
  3809. }
  3810. this.#createSVGElement();
  3811. this.#hasUsedPointer = false;
  3812. this.#clickAC = new AbortController();
  3813. const clickOpts = {
  3814. signal: this.#clickAC.signal
  3815. },
  3816. onClick = this.#onClick.bind(this);
  3817. for (const element of [this.#optionDescription, this.#optionDecorative, this.#textarea, this.#saveButton, this.#cancelButton]) {
  3818. element.addEventListener("click", onClick, clickOpts);
  3819. }
  3820. const {
  3821. altText,
  3822. decorative
  3823. } = editor.altTextData;
  3824. if (decorative === true) {
  3825. this.#optionDecorative.checked = true;
  3826. this.#optionDescription.checked = false;
  3827. } else {
  3828. this.#optionDecorative.checked = false;
  3829. this.#optionDescription.checked = true;
  3830. }
  3831. this.#previousAltText = this.#textarea.value = altText?.trim() || "";
  3832. this.#updateUIState();
  3833. this.#currentEditor = editor;
  3834. this.#uiManager = uiManager;
  3835. this.#uiManager.removeEditListeners();
  3836. this.#resizeAC = new AbortController();
  3837. this.#eventBus._on("resize", this.#setPosition.bind(this), {
  3838. signal: this.#resizeAC.signal
  3839. });
  3840. try {
  3841. await this.#overlayManager.open(this.#dialog);
  3842. this.#setPosition();
  3843. } catch (ex) {
  3844. this.#close();
  3845. throw ex;
  3846. }
  3847. }
  3848. #setPosition() {
  3849. if (!this.#currentEditor) {
  3850. return;
  3851. }
  3852. const dialog = this.#dialog;
  3853. const {
  3854. style
  3855. } = dialog;
  3856. const {
  3857. x: containerX,
  3858. y: containerY,
  3859. width: containerW,
  3860. height: containerH
  3861. } = this.#container.getBoundingClientRect();
  3862. const {
  3863. innerWidth: windowW,
  3864. innerHeight: windowH
  3865. } = window;
  3866. const {
  3867. width: dialogW,
  3868. height: dialogH
  3869. } = dialog.getBoundingClientRect();
  3870. const {
  3871. x,
  3872. y,
  3873. width,
  3874. height
  3875. } = this.#currentEditor.getClientDimensions();
  3876. const MARGIN = 10;
  3877. const isLTR = this.#uiManager.direction === "ltr";
  3878. const xs = Math.max(x, containerX);
  3879. const xe = Math.min(x + width, containerX + containerW);
  3880. const ys = Math.max(y, containerY);
  3881. const ye = Math.min(y + height, containerY + containerH);
  3882. this.#rectElement.setAttribute("width", `${(xe - xs) / windowW}`);
  3883. this.#rectElement.setAttribute("height", `${(ye - ys) / windowH}`);
  3884. this.#rectElement.setAttribute("x", `${xs / windowW}`);
  3885. this.#rectElement.setAttribute("y", `${ys / windowH}`);
  3886. let left = null;
  3887. let top = Math.max(y, 0);
  3888. top += Math.min(windowH - (top + dialogH), 0);
  3889. if (isLTR) {
  3890. if (x + width + MARGIN + dialogW < windowW) {
  3891. left = x + width + MARGIN;
  3892. } else if (x > dialogW + MARGIN) {
  3893. left = x - dialogW - MARGIN;
  3894. }
  3895. } else if (x > dialogW + MARGIN) {
  3896. left = x - dialogW - MARGIN;
  3897. } else if (x + width + MARGIN + dialogW < windowW) {
  3898. left = x + width + MARGIN;
  3899. }
  3900. if (left === null) {
  3901. top = null;
  3902. left = Math.max(x, 0);
  3903. left += Math.min(windowW - (left + dialogW), 0);
  3904. if (y > dialogH + MARGIN) {
  3905. top = y - dialogH - MARGIN;
  3906. } else if (y + height + MARGIN + dialogH < windowH) {
  3907. top = y + height + MARGIN;
  3908. }
  3909. }
  3910. if (top !== null) {
  3911. dialog.classList.add("positioned");
  3912. if (isLTR) {
  3913. style.left = `${left}px`;
  3914. } else {
  3915. style.right = `${windowW - left - dialogW}px`;
  3916. }
  3917. style.top = `${top}px`;
  3918. } else {
  3919. dialog.classList.remove("positioned");
  3920. style.left = "";
  3921. style.top = "";
  3922. }
  3923. }
  3924. #finish() {
  3925. this.#overlayManager.closeIfActive(this.#dialog);
  3926. }
  3927. #close() {
  3928. this.#currentEditor._reportTelemetry(this.#telemetryData || {
  3929. action: "alt_text_cancel",
  3930. alt_text_keyboard: !this.#hasUsedPointer
  3931. });
  3932. this.#telemetryData = null;
  3933. this.#removeOnClickListeners();
  3934. this.#uiManager?.addEditListeners();
  3935. this.#resizeAC?.abort();
  3936. this.#resizeAC = null;
  3937. this.#currentEditor.altTextFinish();
  3938. this.#currentEditor = null;
  3939. this.#uiManager = null;
  3940. }
  3941. #updateUIState() {
  3942. this.#textarea.disabled = this.#optionDecorative.checked;
  3943. }
  3944. #save() {
  3945. const altText = this.#textarea.value.trim();
  3946. const decorative = this.#optionDecorative.checked;
  3947. this.#currentEditor.altTextData = {
  3948. altText,
  3949. decorative
  3950. };
  3951. this.#telemetryData = {
  3952. action: "alt_text_save",
  3953. alt_text_description: !!altText,
  3954. alt_text_edit: !!this.#previousAltText && this.#previousAltText !== altText,
  3955. alt_text_decorative: decorative,
  3956. alt_text_keyboard: !this.#hasUsedPointer
  3957. };
  3958. this.#finish();
  3959. }
  3960. #onClick(evt) {
  3961. if (evt.detail === 0) {
  3962. return;
  3963. }
  3964. this.#hasUsedPointer = true;
  3965. this.#removeOnClickListeners();
  3966. }
  3967. #removeOnClickListeners() {
  3968. this.#clickAC?.abort();
  3969. this.#clickAC = null;
  3970. }
  3971. destroy() {
  3972. this.#uiManager = null;
  3973. this.#finish();
  3974. this.#svgElement?.remove();
  3975. this.#svgElement = this.#rectElement = null;
  3976. }
  3977. }
  3978. ;// ./web/annotation_editor_params.js
  3979. class AnnotationEditorParams {
  3980. constructor(options, eventBus) {
  3981. this.eventBus = eventBus;
  3982. this.#bindListeners(options);
  3983. }
  3984. #bindListeners({
  3985. editorFreeTextFontSize,
  3986. editorFreeTextColor,
  3987. editorInkColor,
  3988. editorInkThickness,
  3989. editorInkOpacity,
  3990. editorStampAddImage,
  3991. editorFreeHighlightThickness,
  3992. editorHighlightShowAll,
  3993. editorSignatureAddSignature
  3994. }) {
  3995. const {
  3996. eventBus
  3997. } = this;
  3998. const dispatchEvent = (typeStr, value) => {
  3999. eventBus.dispatch("switchannotationeditorparams", {
  4000. source: this,
  4001. type: AnnotationEditorParamsType[typeStr],
  4002. value
  4003. });
  4004. };
  4005. editorFreeTextFontSize.addEventListener("input", function () {
  4006. dispatchEvent("FREETEXT_SIZE", this.valueAsNumber);
  4007. });
  4008. editorFreeTextColor.addEventListener("input", function () {
  4009. dispatchEvent("FREETEXT_COLOR", this.value);
  4010. });
  4011. editorInkColor.addEventListener("input", function () {
  4012. dispatchEvent("INK_COLOR", this.value);
  4013. });
  4014. editorInkThickness.addEventListener("input", function () {
  4015. dispatchEvent("INK_THICKNESS", this.valueAsNumber);
  4016. });
  4017. editorInkOpacity.addEventListener("input", function () {
  4018. dispatchEvent("INK_OPACITY", this.valueAsNumber);
  4019. });
  4020. editorStampAddImage.addEventListener("click", () => {
  4021. eventBus.dispatch("reporttelemetry", {
  4022. source: this,
  4023. details: {
  4024. type: "editing",
  4025. data: {
  4026. action: "pdfjs.image.add_image_click"
  4027. }
  4028. }
  4029. });
  4030. dispatchEvent("CREATE");
  4031. });
  4032. editorFreeHighlightThickness.addEventListener("input", function () {
  4033. dispatchEvent("HIGHLIGHT_THICKNESS", this.valueAsNumber);
  4034. });
  4035. editorHighlightShowAll.addEventListener("click", function () {
  4036. const checked = this.getAttribute("aria-pressed") === "true";
  4037. this.setAttribute("aria-pressed", !checked);
  4038. dispatchEvent("HIGHLIGHT_SHOW_ALL", !checked);
  4039. });
  4040. editorSignatureAddSignature.addEventListener("click", () => {
  4041. dispatchEvent("CREATE");
  4042. });
  4043. eventBus._on("annotationeditorparamschanged", evt => {
  4044. for (const [type, value] of evt.details) {
  4045. switch (type) {
  4046. case AnnotationEditorParamsType.FREETEXT_SIZE:
  4047. editorFreeTextFontSize.value = value;
  4048. break;
  4049. case AnnotationEditorParamsType.FREETEXT_COLOR:
  4050. editorFreeTextColor.value = value;
  4051. break;
  4052. case AnnotationEditorParamsType.INK_COLOR:
  4053. editorInkColor.value = value;
  4054. break;
  4055. case AnnotationEditorParamsType.INK_THICKNESS:
  4056. editorInkThickness.value = value;
  4057. break;
  4058. case AnnotationEditorParamsType.INK_OPACITY:
  4059. editorInkOpacity.value = value;
  4060. break;
  4061. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  4062. eventBus.dispatch("mainhighlightcolorpickerupdatecolor", {
  4063. source: this,
  4064. value
  4065. });
  4066. break;
  4067. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  4068. editorFreeHighlightThickness.value = value;
  4069. break;
  4070. case AnnotationEditorParamsType.HIGHLIGHT_FREE:
  4071. editorFreeHighlightThickness.disabled = !value;
  4072. break;
  4073. case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
  4074. editorHighlightShowAll.setAttribute("aria-pressed", value);
  4075. break;
  4076. }
  4077. }
  4078. });
  4079. }
  4080. }
  4081. ;// ./web/caret_browsing.js
  4082. const PRECISION = 1e-1;
  4083. class CaretBrowsingMode {
  4084. #mainContainer;
  4085. #toolBarHeight = 0;
  4086. #viewerContainer;
  4087. constructor(abortSignal, mainContainer, viewerContainer, toolbarContainer) {
  4088. this.#mainContainer = mainContainer;
  4089. this.#viewerContainer = viewerContainer;
  4090. if (!toolbarContainer) {
  4091. return;
  4092. }
  4093. this.#toolBarHeight = toolbarContainer.getBoundingClientRect().height;
  4094. const toolbarObserver = new ResizeObserver(entries => {
  4095. for (const entry of entries) {
  4096. if (entry.target === toolbarContainer) {
  4097. this.#toolBarHeight = Math.floor(entry.borderBoxSize[0].blockSize);
  4098. break;
  4099. }
  4100. }
  4101. });
  4102. toolbarObserver.observe(toolbarContainer);
  4103. abortSignal.addEventListener("abort", () => toolbarObserver.disconnect(), {
  4104. once: true
  4105. });
  4106. }
  4107. #isOnSameLine(rect1, rect2) {
  4108. const top1 = rect1.y;
  4109. const bot1 = rect1.bottom;
  4110. const mid1 = rect1.y + rect1.height / 2;
  4111. const top2 = rect2.y;
  4112. const bot2 = rect2.bottom;
  4113. const mid2 = rect2.y + rect2.height / 2;
  4114. return top1 <= mid2 && mid2 <= bot1 || top2 <= mid1 && mid1 <= bot2;
  4115. }
  4116. #isUnderOver(rect, x, y, isUp) {
  4117. const midY = rect.y + rect.height / 2;
  4118. return (isUp ? y >= midY : y <= midY) && rect.x - PRECISION <= x && x <= rect.right + PRECISION;
  4119. }
  4120. #isVisible(rect) {
  4121. return rect.top >= this.#toolBarHeight && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth);
  4122. }
  4123. #getCaretPosition(selection, isUp) {
  4124. const {
  4125. focusNode,
  4126. focusOffset
  4127. } = selection;
  4128. const range = document.createRange();
  4129. range.setStart(focusNode, focusOffset);
  4130. range.setEnd(focusNode, focusOffset);
  4131. const rect = range.getBoundingClientRect();
  4132. return [rect.x, isUp ? rect.top : rect.bottom];
  4133. }
  4134. static #caretPositionFromPoint(x, y) {
  4135. if (!document.caretPositionFromPoint) {
  4136. const {
  4137. startContainer: offsetNode,
  4138. startOffset: offset
  4139. } = document.caretRangeFromPoint(x, y);
  4140. return {
  4141. offsetNode,
  4142. offset
  4143. };
  4144. }
  4145. return document.caretPositionFromPoint(x, y);
  4146. }
  4147. #setCaretPositionHelper(selection, caretX, select, element, rect) {
  4148. rect ||= element.getBoundingClientRect();
  4149. if (caretX <= rect.x + PRECISION) {
  4150. if (select) {
  4151. selection.extend(element.firstChild, 0);
  4152. } else {
  4153. selection.setPosition(element.firstChild, 0);
  4154. }
  4155. return;
  4156. }
  4157. if (rect.right - PRECISION <= caretX) {
  4158. const {
  4159. lastChild
  4160. } = element;
  4161. if (select) {
  4162. selection.extend(lastChild, lastChild.length);
  4163. } else {
  4164. selection.setPosition(lastChild, lastChild.length);
  4165. }
  4166. return;
  4167. }
  4168. const midY = rect.y + rect.height / 2;
  4169. let caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);
  4170. let parentElement = caretPosition.offsetNode?.parentElement;
  4171. if (parentElement && parentElement !== element) {
  4172. const elementsAtPoint = document.elementsFromPoint(caretX, midY);
  4173. const savedVisibilities = [];
  4174. for (const el of elementsAtPoint) {
  4175. if (el === element) {
  4176. break;
  4177. }
  4178. const {
  4179. style
  4180. } = el;
  4181. savedVisibilities.push([el, style.visibility]);
  4182. style.visibility = "hidden";
  4183. }
  4184. caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);
  4185. parentElement = caretPosition.offsetNode?.parentElement;
  4186. for (const [el, visibility] of savedVisibilities) {
  4187. el.style.visibility = visibility;
  4188. }
  4189. }
  4190. if (parentElement !== element) {
  4191. if (select) {
  4192. selection.extend(element.firstChild, 0);
  4193. } else {
  4194. selection.setPosition(element.firstChild, 0);
  4195. }
  4196. return;
  4197. }
  4198. if (select) {
  4199. selection.extend(caretPosition.offsetNode, caretPosition.offset);
  4200. } else {
  4201. selection.setPosition(caretPosition.offsetNode, caretPosition.offset);
  4202. }
  4203. }
  4204. #setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX) {
  4205. if (this.#isVisible(newLineElementRect)) {
  4206. this.#setCaretPositionHelper(selection, caretX, select, newLineElement, newLineElementRect);
  4207. return;
  4208. }
  4209. this.#mainContainer.addEventListener("scrollend", this.#setCaretPositionHelper.bind(this, selection, caretX, select, newLineElement, null), {
  4210. once: true
  4211. });
  4212. newLineElement.scrollIntoView();
  4213. }
  4214. #getNodeOnNextPage(textLayer, isUp) {
  4215. while (true) {
  4216. const page = textLayer.closest(".page");
  4217. const pageNumber = parseInt(page.getAttribute("data-page-number"));
  4218. const nextPage = isUp ? pageNumber - 1 : pageNumber + 1;
  4219. textLayer = this.#viewerContainer.querySelector(`.page[data-page-number="${nextPage}"] .textLayer`);
  4220. if (!textLayer) {
  4221. return null;
  4222. }
  4223. const walker = document.createTreeWalker(textLayer, NodeFilter.SHOW_TEXT);
  4224. const node = isUp ? walker.lastChild() : walker.firstChild();
  4225. if (node) {
  4226. return node;
  4227. }
  4228. }
  4229. }
  4230. moveCaret(isUp, select) {
  4231. const selection = document.getSelection();
  4232. if (selection.rangeCount === 0) {
  4233. return;
  4234. }
  4235. const {
  4236. focusNode
  4237. } = selection;
  4238. const focusElement = focusNode.nodeType !== Node.ELEMENT_NODE ? focusNode.parentElement : focusNode;
  4239. const root = focusElement.closest(".textLayer");
  4240. if (!root) {
  4241. return;
  4242. }
  4243. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  4244. walker.currentNode = focusNode;
  4245. const focusRect = focusElement.getBoundingClientRect();
  4246. let newLineElement = null;
  4247. const nodeIterator = (isUp ? walker.previousSibling : walker.nextSibling).bind(walker);
  4248. while (nodeIterator()) {
  4249. const element = walker.currentNode.parentElement;
  4250. if (!this.#isOnSameLine(focusRect, element.getBoundingClientRect())) {
  4251. newLineElement = element;
  4252. break;
  4253. }
  4254. }
  4255. if (!newLineElement) {
  4256. const node = this.#getNodeOnNextPage(root, isUp);
  4257. if (!node) {
  4258. return;
  4259. }
  4260. if (select) {
  4261. const lastNode = (isUp ? walker.firstChild() : walker.lastChild()) || focusNode;
  4262. selection.extend(lastNode, isUp ? 0 : lastNode.length);
  4263. const range = document.createRange();
  4264. range.setStart(node, isUp ? node.length : 0);
  4265. range.setEnd(node, isUp ? node.length : 0);
  4266. selection.addRange(range);
  4267. return;
  4268. }
  4269. const [caretX] = this.#getCaretPosition(selection, isUp);
  4270. const {
  4271. parentElement
  4272. } = node;
  4273. this.#setCaretPosition(select, selection, parentElement, parentElement.getBoundingClientRect(), caretX);
  4274. return;
  4275. }
  4276. const [caretX, caretY] = this.#getCaretPosition(selection, isUp);
  4277. const newLineElementRect = newLineElement.getBoundingClientRect();
  4278. if (this.#isUnderOver(newLineElementRect, caretX, caretY, isUp)) {
  4279. this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX);
  4280. return;
  4281. }
  4282. while (nodeIterator()) {
  4283. const element = walker.currentNode.parentElement;
  4284. const elementRect = element.getBoundingClientRect();
  4285. if (!this.#isOnSameLine(newLineElementRect, elementRect)) {
  4286. break;
  4287. }
  4288. if (this.#isUnderOver(elementRect, caretX, caretY, isUp)) {
  4289. this.#setCaretPosition(select, selection, element, elementRect, caretX);
  4290. return;
  4291. }
  4292. }
  4293. this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX);
  4294. }
  4295. }
  4296. ;// ./web/download_manager.js
  4297. function download(blobUrl, filename) {
  4298. const a = document.createElement("a");
  4299. if (!a.click) {
  4300. throw new Error('DownloadManager: "a.click()" is not supported.');
  4301. }
  4302. a.href = blobUrl;
  4303. a.target = "_parent";
  4304. if ("download" in a) {
  4305. a.download = filename;
  4306. }
  4307. (document.body || document.documentElement).append(a);
  4308. a.click();
  4309. a.remove();
  4310. }
  4311. class DownloadManager {
  4312. #openBlobUrls = new WeakMap();
  4313. downloadData(data, filename, contentType) {
  4314. const blobUrl = URL.createObjectURL(new Blob([data], {
  4315. type: contentType
  4316. }));
  4317. download(blobUrl, filename);
  4318. }
  4319. openOrDownloadData(data, filename, dest = null) {
  4320. const isPdfData = isPdfFile(filename);
  4321. const contentType = isPdfData ? "application/pdf" : "";
  4322. if (isPdfData) {
  4323. let blobUrl = this.#openBlobUrls.get(data);
  4324. if (!blobUrl) {
  4325. blobUrl = URL.createObjectURL(new Blob([data], {
  4326. type: contentType
  4327. }));
  4328. this.#openBlobUrls.set(data, blobUrl);
  4329. }
  4330. let viewerUrl;
  4331. viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename);
  4332. if (dest) {
  4333. viewerUrl += `#${escape(dest)}`;
  4334. }
  4335. try {
  4336. window.open(viewerUrl);
  4337. return true;
  4338. } catch (ex) {
  4339. console.error("openOrDownloadData:", ex);
  4340. URL.revokeObjectURL(blobUrl);
  4341. this.#openBlobUrls.delete(data);
  4342. }
  4343. }
  4344. this.downloadData(data, filename, contentType);
  4345. return false;
  4346. }
  4347. download(data, url, filename) {
  4348. let blobUrl;
  4349. if (data) {
  4350. blobUrl = URL.createObjectURL(new Blob([data], {
  4351. type: "application/pdf"
  4352. }));
  4353. } else {
  4354. if (!createValidAbsoluteUrl(url, "http://example.com")) {
  4355. console.error(`download - not a valid URL: ${url}`);
  4356. return;
  4357. }
  4358. blobUrl = url + "#pdfjs.action=download";
  4359. }
  4360. download(blobUrl, filename);
  4361. }
  4362. }
  4363. ;// ./web/editor_undo_bar.js
  4364. class EditorUndoBar {
  4365. #closeButton = null;
  4366. #container;
  4367. #eventBus = null;
  4368. #focusTimeout = null;
  4369. #initController = null;
  4370. isOpen = false;
  4371. #message;
  4372. #showController = null;
  4373. #undoButton;
  4374. static #l10nMessages = Object.freeze({
  4375. highlight: "pdfjs-editor-undo-bar-message-highlight",
  4376. freetext: "pdfjs-editor-undo-bar-message-freetext",
  4377. stamp: "pdfjs-editor-undo-bar-message-stamp",
  4378. ink: "pdfjs-editor-undo-bar-message-ink",
  4379. signature: "pdfjs-editor-undo-bar-message-signature",
  4380. _multiple: "pdfjs-editor-undo-bar-message-multiple"
  4381. });
  4382. constructor({
  4383. container,
  4384. message,
  4385. undoButton,
  4386. closeButton
  4387. }, eventBus) {
  4388. this.#container = container;
  4389. this.#message = message;
  4390. this.#undoButton = undoButton;
  4391. this.#closeButton = closeButton;
  4392. this.#eventBus = eventBus;
  4393. }
  4394. destroy() {
  4395. this.#initController?.abort();
  4396. this.#initController = null;
  4397. this.hide();
  4398. }
  4399. show(undoAction, messageData) {
  4400. if (!this.#initController) {
  4401. this.#initController = new AbortController();
  4402. const opts = {
  4403. signal: this.#initController.signal
  4404. };
  4405. const boundHide = this.hide.bind(this);
  4406. this.#container.addEventListener("contextmenu", noContextMenu, opts);
  4407. this.#closeButton.addEventListener("click", boundHide, opts);
  4408. this.#eventBus._on("beforeprint", boundHide, opts);
  4409. this.#eventBus._on("download", boundHide, opts);
  4410. }
  4411. this.hide();
  4412. if (typeof messageData === "string") {
  4413. this.#message.setAttribute("data-l10n-id", EditorUndoBar.#l10nMessages[messageData]);
  4414. } else {
  4415. this.#message.setAttribute("data-l10n-id", EditorUndoBar.#l10nMessages._multiple);
  4416. this.#message.setAttribute("data-l10n-args", JSON.stringify({
  4417. count: messageData
  4418. }));
  4419. }
  4420. this.isOpen = true;
  4421. this.#container.hidden = false;
  4422. this.#showController = new AbortController();
  4423. this.#undoButton.addEventListener("click", () => {
  4424. undoAction();
  4425. this.hide();
  4426. }, {
  4427. signal: this.#showController.signal
  4428. });
  4429. this.#focusTimeout = setTimeout(() => {
  4430. this.#container.focus();
  4431. this.#focusTimeout = null;
  4432. }, 100);
  4433. }
  4434. hide() {
  4435. if (!this.isOpen) {
  4436. return;
  4437. }
  4438. this.isOpen = false;
  4439. this.#container.hidden = true;
  4440. this.#showController?.abort();
  4441. this.#showController = null;
  4442. if (this.#focusTimeout) {
  4443. clearTimeout(this.#focusTimeout);
  4444. this.#focusTimeout = null;
  4445. }
  4446. }
  4447. }
  4448. ;// ./web/overlay_manager.js
  4449. class OverlayManager {
  4450. #overlays = new WeakMap();
  4451. #active = null;
  4452. get active() {
  4453. return this.#active;
  4454. }
  4455. async register(dialog, canForceClose = false) {
  4456. if (typeof dialog !== "object") {
  4457. throw new Error("Not enough parameters.");
  4458. } else if (this.#overlays.has(dialog)) {
  4459. throw new Error("The overlay is already registered.");
  4460. }
  4461. this.#overlays.set(dialog, {
  4462. canForceClose
  4463. });
  4464. dialog.addEventListener("cancel", ({
  4465. target
  4466. }) => {
  4467. if (this.#active === target) {
  4468. this.#active = null;
  4469. }
  4470. });
  4471. }
  4472. async open(dialog) {
  4473. if (!this.#overlays.has(dialog)) {
  4474. throw new Error("The overlay does not exist.");
  4475. } else if (this.#active) {
  4476. if (this.#active === dialog) {
  4477. throw new Error("The overlay is already active.");
  4478. } else if (this.#overlays.get(dialog).canForceClose) {
  4479. await this.close();
  4480. } else {
  4481. throw new Error("Another overlay is currently active.");
  4482. }
  4483. }
  4484. this.#active = dialog;
  4485. dialog.showModal();
  4486. }
  4487. async close(dialog = this.#active) {
  4488. if (!this.#overlays.has(dialog)) {
  4489. throw new Error("The overlay does not exist.");
  4490. } else if (!this.#active) {
  4491. throw new Error("The overlay is currently not active.");
  4492. } else if (this.#active !== dialog) {
  4493. throw new Error("Another overlay is currently active.");
  4494. }
  4495. dialog.close();
  4496. this.#active = null;
  4497. }
  4498. async closeIfActive(dialog) {
  4499. if (this.#active === dialog) {
  4500. await this.close(dialog);
  4501. }
  4502. }
  4503. }
  4504. ;// ./web/password_prompt.js
  4505. class PasswordPrompt {
  4506. #activeCapability = null;
  4507. #updateCallback = null;
  4508. #reason = null;
  4509. constructor(options, overlayManager, isViewerEmbedded = false) {
  4510. this.dialog = options.dialog;
  4511. this.label = options.label;
  4512. this.input = options.input;
  4513. this.submitButton = options.submitButton;
  4514. this.cancelButton = options.cancelButton;
  4515. this.overlayManager = overlayManager;
  4516. this._isViewerEmbedded = isViewerEmbedded;
  4517. this.submitButton.addEventListener("click", this.#verify.bind(this));
  4518. this.cancelButton.addEventListener("click", this.close.bind(this));
  4519. this.input.addEventListener("keydown", e => {
  4520. if (e.keyCode === 13) {
  4521. this.#verify();
  4522. }
  4523. });
  4524. this.overlayManager.register(this.dialog, true);
  4525. this.dialog.addEventListener("close", this.#cancel.bind(this));
  4526. }
  4527. async open() {
  4528. await this.#activeCapability?.promise;
  4529. this.#activeCapability = Promise.withResolvers();
  4530. try {
  4531. await this.overlayManager.open(this.dialog);
  4532. } catch (ex) {
  4533. this.#activeCapability.resolve();
  4534. throw ex;
  4535. }
  4536. const passwordIncorrect = this.#reason === PasswordResponses.INCORRECT_PASSWORD;
  4537. if (!this._isViewerEmbedded || passwordIncorrect) {
  4538. this.input.focus();
  4539. }
  4540. this.label.setAttribute("data-l10n-id", passwordIncorrect ? "pdfjs-password-invalid" : "pdfjs-password-label");
  4541. }
  4542. async close() {
  4543. this.overlayManager.closeIfActive(this.dialog);
  4544. }
  4545. #verify() {
  4546. const password = this.input.value;
  4547. if (password?.length > 0) {
  4548. this.#invokeCallback(password);
  4549. }
  4550. }
  4551. #cancel() {
  4552. this.#invokeCallback(new Error("PasswordPrompt cancelled."));
  4553. this.#activeCapability.resolve();
  4554. }
  4555. #invokeCallback(password) {
  4556. if (!this.#updateCallback) {
  4557. return;
  4558. }
  4559. this.close();
  4560. this.input.value = "";
  4561. this.#updateCallback(password);
  4562. this.#updateCallback = null;
  4563. }
  4564. async setUpdateCallback(updateCallback, reason) {
  4565. if (this.#activeCapability) {
  4566. await this.#activeCapability.promise;
  4567. }
  4568. this.#updateCallback = updateCallback;
  4569. this.#reason = reason;
  4570. }
  4571. }
  4572. ;// ./web/base_tree_viewer.js
  4573. const TREEITEM_OFFSET_TOP = -100;
  4574. const TREEITEM_SELECTED_CLASS = "selected";
  4575. class BaseTreeViewer {
  4576. constructor(options) {
  4577. this.container = options.container;
  4578. this.eventBus = options.eventBus;
  4579. this._l10n = options.l10n;
  4580. this.reset();
  4581. }
  4582. reset() {
  4583. this._pdfDocument = null;
  4584. this._lastToggleIsShow = true;
  4585. this._currentTreeItem = null;
  4586. this.container.textContent = "";
  4587. this.container.classList.remove("treeWithDeepNesting");
  4588. }
  4589. _dispatchEvent(count) {
  4590. throw new Error("Not implemented: _dispatchEvent");
  4591. }
  4592. _bindLink(element, params) {
  4593. throw new Error("Not implemented: _bindLink");
  4594. }
  4595. _normalizeTextContent(str) {
  4596. return removeNullCharacters(str, true) || "\u2013";
  4597. }
  4598. _addToggleButton(div, hidden = false) {
  4599. const toggler = document.createElement("div");
  4600. toggler.className = "treeItemToggler";
  4601. if (hidden) {
  4602. toggler.classList.add("treeItemsHidden");
  4603. }
  4604. toggler.onclick = evt => {
  4605. evt.stopPropagation();
  4606. toggler.classList.toggle("treeItemsHidden");
  4607. if (evt.shiftKey) {
  4608. const shouldShowAll = !toggler.classList.contains("treeItemsHidden");
  4609. this._toggleTreeItem(div, shouldShowAll);
  4610. }
  4611. };
  4612. div.prepend(toggler);
  4613. }
  4614. _toggleTreeItem(root, show = false) {
  4615. this._l10n.pause();
  4616. this._lastToggleIsShow = show;
  4617. for (const toggler of root.querySelectorAll(".treeItemToggler")) {
  4618. toggler.classList.toggle("treeItemsHidden", !show);
  4619. }
  4620. this._l10n.resume();
  4621. }
  4622. _toggleAllTreeItems() {
  4623. this._toggleTreeItem(this.container, !this._lastToggleIsShow);
  4624. }
  4625. _finishRendering(fragment, count, hasAnyNesting = false) {
  4626. if (hasAnyNesting) {
  4627. this.container.classList.add("treeWithDeepNesting");
  4628. this._lastToggleIsShow = !fragment.querySelector(".treeItemsHidden");
  4629. }
  4630. this._l10n.pause();
  4631. this.container.append(fragment);
  4632. this._l10n.resume();
  4633. this._dispatchEvent(count);
  4634. }
  4635. render(params) {
  4636. throw new Error("Not implemented: render");
  4637. }
  4638. _updateCurrentTreeItem(treeItem = null) {
  4639. if (this._currentTreeItem) {
  4640. this._currentTreeItem.classList.remove(TREEITEM_SELECTED_CLASS);
  4641. this._currentTreeItem = null;
  4642. }
  4643. if (treeItem) {
  4644. treeItem.classList.add(TREEITEM_SELECTED_CLASS);
  4645. this._currentTreeItem = treeItem;
  4646. }
  4647. }
  4648. _scrollToCurrentTreeItem(treeItem) {
  4649. if (!treeItem) {
  4650. return;
  4651. }
  4652. this._l10n.pause();
  4653. let currentNode = treeItem.parentNode;
  4654. while (currentNode && currentNode !== this.container) {
  4655. if (currentNode.classList.contains("treeItem")) {
  4656. const toggler = currentNode.firstElementChild;
  4657. toggler?.classList.remove("treeItemsHidden");
  4658. }
  4659. currentNode = currentNode.parentNode;
  4660. }
  4661. this._l10n.resume();
  4662. this._updateCurrentTreeItem(treeItem);
  4663. this.container.scrollTo(treeItem.offsetLeft, treeItem.offsetTop + TREEITEM_OFFSET_TOP);
  4664. }
  4665. }
  4666. ;// ./web/pdf_attachment_viewer.js
  4667. class PDFAttachmentViewer extends BaseTreeViewer {
  4668. constructor(options) {
  4669. super(options);
  4670. this.downloadManager = options.downloadManager;
  4671. this.eventBus._on("fileattachmentannotation", this.#appendAttachment.bind(this));
  4672. }
  4673. reset(keepRenderedCapability = false) {
  4674. super.reset();
  4675. this._attachments = null;
  4676. if (!keepRenderedCapability) {
  4677. this._renderedCapability = Promise.withResolvers();
  4678. }
  4679. this._pendingDispatchEvent = false;
  4680. }
  4681. async _dispatchEvent(attachmentsCount) {
  4682. this._renderedCapability.resolve();
  4683. if (attachmentsCount === 0 && !this._pendingDispatchEvent) {
  4684. this._pendingDispatchEvent = true;
  4685. await waitOnEventOrTimeout({
  4686. target: this.eventBus,
  4687. name: "annotationlayerrendered",
  4688. delay: 1000
  4689. });
  4690. if (!this._pendingDispatchEvent) {
  4691. return;
  4692. }
  4693. }
  4694. this._pendingDispatchEvent = false;
  4695. this.eventBus.dispatch("attachmentsloaded", {
  4696. source: this,
  4697. attachmentsCount
  4698. });
  4699. }
  4700. _bindLink(element, {
  4701. content,
  4702. description,
  4703. filename
  4704. }) {
  4705. if (description) {
  4706. element.title = description;
  4707. }
  4708. element.onclick = () => {
  4709. this.downloadManager.openOrDownloadData(content, filename);
  4710. return false;
  4711. };
  4712. }
  4713. render({
  4714. attachments,
  4715. keepRenderedCapability = false
  4716. }) {
  4717. if (this._attachments) {
  4718. this.reset(keepRenderedCapability);
  4719. }
  4720. this._attachments = attachments || null;
  4721. if (!attachments) {
  4722. this._dispatchEvent(0);
  4723. return;
  4724. }
  4725. const fragment = document.createDocumentFragment();
  4726. let attachmentsCount = 0;
  4727. for (const name in attachments) {
  4728. const item = attachments[name];
  4729. const div = document.createElement("div");
  4730. div.className = "treeItem";
  4731. const element = document.createElement("a");
  4732. this._bindLink(element, item);
  4733. element.textContent = this._normalizeTextContent(item.filename);
  4734. div.append(element);
  4735. fragment.append(div);
  4736. attachmentsCount++;
  4737. }
  4738. this._finishRendering(fragment, attachmentsCount);
  4739. }
  4740. #appendAttachment(item) {
  4741. const renderedPromise = this._renderedCapability.promise;
  4742. renderedPromise.then(() => {
  4743. if (renderedPromise !== this._renderedCapability.promise) {
  4744. return;
  4745. }
  4746. const attachments = this._attachments || Object.create(null);
  4747. for (const name in attachments) {
  4748. if (item.filename === name) {
  4749. return;
  4750. }
  4751. }
  4752. attachments[item.filename] = item;
  4753. this.render({
  4754. attachments,
  4755. keepRenderedCapability: true
  4756. });
  4757. });
  4758. }
  4759. }
  4760. ;// ./web/grab_to_pan.js
  4761. const CSS_CLASS_GRAB = "grab-to-pan-grab";
  4762. class GrabToPan {
  4763. #activateAC = null;
  4764. #mouseDownAC = null;
  4765. #scrollAC = null;
  4766. constructor({
  4767. element
  4768. }) {
  4769. this.element = element;
  4770. this.document = element.ownerDocument;
  4771. const overlay = this.overlay = document.createElement("div");
  4772. overlay.className = "grab-to-pan-grabbing";
  4773. }
  4774. activate() {
  4775. if (!this.#activateAC) {
  4776. this.#activateAC = new AbortController();
  4777. this.element.addEventListener("mousedown", this.#onMouseDown.bind(this), {
  4778. capture: true,
  4779. signal: this.#activateAC.signal
  4780. });
  4781. this.element.classList.add(CSS_CLASS_GRAB);
  4782. }
  4783. }
  4784. deactivate() {
  4785. if (this.#activateAC) {
  4786. this.#activateAC.abort();
  4787. this.#activateAC = null;
  4788. this.#endPan();
  4789. this.element.classList.remove(CSS_CLASS_GRAB);
  4790. }
  4791. }
  4792. toggle() {
  4793. if (this.#activateAC) {
  4794. this.deactivate();
  4795. } else {
  4796. this.activate();
  4797. }
  4798. }
  4799. ignoreTarget(node) {
  4800. return node.matches("a[href], a[href] *, input, textarea, button, button *, select, option");
  4801. }
  4802. #onMouseDown(event) {
  4803. if (event.button !== 0 || this.ignoreTarget(event.target)) {
  4804. return;
  4805. }
  4806. if (event.originalTarget) {
  4807. try {
  4808. event.originalTarget.tagName;
  4809. } catch {
  4810. return;
  4811. }
  4812. }
  4813. this.scrollLeftStart = this.element.scrollLeft;
  4814. this.scrollTopStart = this.element.scrollTop;
  4815. this.clientXStart = event.clientX;
  4816. this.clientYStart = event.clientY;
  4817. this.#mouseDownAC = new AbortController();
  4818. const boundEndPan = this.#endPan.bind(this),
  4819. mouseOpts = {
  4820. capture: true,
  4821. signal: this.#mouseDownAC.signal
  4822. };
  4823. this.document.addEventListener("mousemove", this.#onMouseMove.bind(this), mouseOpts);
  4824. this.document.addEventListener("mouseup", boundEndPan, mouseOpts);
  4825. this.#scrollAC = new AbortController();
  4826. this.element.addEventListener("scroll", boundEndPan, {
  4827. capture: true,
  4828. signal: this.#scrollAC.signal
  4829. });
  4830. stopEvent(event);
  4831. const focusedElement = document.activeElement;
  4832. if (focusedElement && !focusedElement.contains(event.target)) {
  4833. focusedElement.blur();
  4834. }
  4835. }
  4836. #onMouseMove(event) {
  4837. this.#scrollAC?.abort();
  4838. this.#scrollAC = null;
  4839. if (!(event.buttons & 1)) {
  4840. this.#endPan();
  4841. return;
  4842. }
  4843. const xDiff = event.clientX - this.clientXStart;
  4844. const yDiff = event.clientY - this.clientYStart;
  4845. this.element.scrollTo({
  4846. top: this.scrollTopStart - yDiff,
  4847. left: this.scrollLeftStart - xDiff,
  4848. behavior: "instant"
  4849. });
  4850. if (!this.overlay.parentNode) {
  4851. document.body.append(this.overlay);
  4852. }
  4853. }
  4854. #endPan() {
  4855. this.#mouseDownAC?.abort();
  4856. this.#mouseDownAC = null;
  4857. this.#scrollAC?.abort();
  4858. this.#scrollAC = null;
  4859. this.overlay.remove();
  4860. }
  4861. }
  4862. ;// ./web/pdf_cursor_tools.js
  4863. class PDFCursorTools {
  4864. #active = CursorTool.SELECT;
  4865. #prevActive = null;
  4866. constructor({
  4867. container,
  4868. eventBus,
  4869. cursorToolOnLoad = CursorTool.SELECT
  4870. }) {
  4871. this.container = container;
  4872. this.eventBus = eventBus;
  4873. this.#addEventListeners();
  4874. Promise.resolve().then(() => {
  4875. this.switchTool(cursorToolOnLoad);
  4876. });
  4877. }
  4878. get activeTool() {
  4879. return this.#active;
  4880. }
  4881. switchTool(tool) {
  4882. if (this.#prevActive !== null) {
  4883. return;
  4884. }
  4885. this.#switchTool(tool);
  4886. }
  4887. #switchTool(tool, disabled = false) {
  4888. if (tool === this.#active) {
  4889. if (this.#prevActive !== null) {
  4890. this.eventBus.dispatch("cursortoolchanged", {
  4891. source: this,
  4892. tool,
  4893. disabled
  4894. });
  4895. }
  4896. return;
  4897. }
  4898. const disableActiveTool = () => {
  4899. switch (this.#active) {
  4900. case CursorTool.SELECT:
  4901. break;
  4902. case CursorTool.HAND:
  4903. this._handTool.deactivate();
  4904. break;
  4905. case CursorTool.ZOOM:
  4906. }
  4907. };
  4908. switch (tool) {
  4909. case CursorTool.SELECT:
  4910. disableActiveTool();
  4911. break;
  4912. case CursorTool.HAND:
  4913. disableActiveTool();
  4914. this._handTool.activate();
  4915. break;
  4916. case CursorTool.ZOOM:
  4917. default:
  4918. console.error(`switchTool: "${tool}" is an unsupported value.`);
  4919. return;
  4920. }
  4921. this.#active = tool;
  4922. this.eventBus.dispatch("cursortoolchanged", {
  4923. source: this,
  4924. tool,
  4925. disabled
  4926. });
  4927. }
  4928. #addEventListeners() {
  4929. this.eventBus._on("switchcursortool", evt => {
  4930. if (!evt.reset) {
  4931. this.switchTool(evt.tool);
  4932. } else if (this.#prevActive !== null) {
  4933. annotationEditorMode = AnnotationEditorType.NONE;
  4934. presentationModeState = PresentationModeState.NORMAL;
  4935. enableActive();
  4936. }
  4937. });
  4938. let annotationEditorMode = AnnotationEditorType.NONE,
  4939. presentationModeState = PresentationModeState.NORMAL;
  4940. const disableActive = () => {
  4941. this.#prevActive ??= this.#active;
  4942. this.#switchTool(CursorTool.SELECT, true);
  4943. };
  4944. const enableActive = () => {
  4945. if (this.#prevActive !== null && annotationEditorMode === AnnotationEditorType.NONE && presentationModeState === PresentationModeState.NORMAL) {
  4946. this.#switchTool(this.#prevActive);
  4947. this.#prevActive = null;
  4948. }
  4949. };
  4950. this.eventBus._on("annotationeditormodechanged", ({
  4951. mode
  4952. }) => {
  4953. annotationEditorMode = mode;
  4954. if (mode === AnnotationEditorType.NONE) {
  4955. enableActive();
  4956. } else {
  4957. disableActive();
  4958. }
  4959. });
  4960. this.eventBus._on("presentationmodechanged", ({
  4961. state
  4962. }) => {
  4963. presentationModeState = state;
  4964. if (state === PresentationModeState.NORMAL) {
  4965. enableActive();
  4966. } else if (state === PresentationModeState.FULLSCREEN) {
  4967. disableActive();
  4968. }
  4969. });
  4970. }
  4971. get _handTool() {
  4972. return shadow(this, "_handTool", new GrabToPan({
  4973. element: this.container
  4974. }));
  4975. }
  4976. }
  4977. ;// ./web/pdf_document_properties.js
  4978. const NON_METRIC_LOCALES = ["en-us", "en-lr", "my"];
  4979. const US_PAGE_NAMES = {
  4980. "8.5x11": "pdfjs-document-properties-page-size-name-letter",
  4981. "8.5x14": "pdfjs-document-properties-page-size-name-legal"
  4982. };
  4983. const METRIC_PAGE_NAMES = {
  4984. "297x420": "pdfjs-document-properties-page-size-name-a-three",
  4985. "210x297": "pdfjs-document-properties-page-size-name-a-four"
  4986. };
  4987. function getPageName(size, isPortrait, pageNames) {
  4988. const width = isPortrait ? size.width : size.height;
  4989. const height = isPortrait ? size.height : size.width;
  4990. return pageNames[`${width}x${height}`];
  4991. }
  4992. class PDFDocumentProperties {
  4993. #fieldData = null;
  4994. constructor({
  4995. dialog,
  4996. fields,
  4997. closeButton
  4998. }, overlayManager, eventBus, l10n, fileNameLookup) {
  4999. this.dialog = dialog;
  5000. this.fields = fields;
  5001. this.overlayManager = overlayManager;
  5002. this.l10n = l10n;
  5003. this._fileNameLookup = fileNameLookup;
  5004. this.#reset();
  5005. closeButton.addEventListener("click", this.close.bind(this));
  5006. this.overlayManager.register(this.dialog);
  5007. eventBus._on("pagechanging", evt => {
  5008. this._currentPageNumber = evt.pageNumber;
  5009. });
  5010. eventBus._on("rotationchanging", evt => {
  5011. this._pagesRotation = evt.pagesRotation;
  5012. });
  5013. }
  5014. async open() {
  5015. await Promise.all([this.overlayManager.open(this.dialog), this._dataAvailableCapability.promise]);
  5016. const currentPageNumber = this._currentPageNumber;
  5017. const pagesRotation = this._pagesRotation;
  5018. if (this.#fieldData && currentPageNumber === this.#fieldData._currentPageNumber && pagesRotation === this.#fieldData._pagesRotation) {
  5019. this.#updateUI();
  5020. return;
  5021. }
  5022. const [{
  5023. info,
  5024. contentLength
  5025. }, pdfPage] = await Promise.all([this.pdfDocument.getMetadata(), this.pdfDocument.getPage(currentPageNumber)]);
  5026. const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([this._fileNameLookup(), this.#parseFileSize(contentLength), this.#parseDate(info.CreationDate), this.#parseDate(info.ModDate), this.#parsePageSize(getPageSizeInches(pdfPage), pagesRotation), this.#parseLinearization(info.IsLinearized)]);
  5027. this.#fieldData = Object.freeze({
  5028. fileName,
  5029. fileSize,
  5030. title: info.Title,
  5031. author: info.Author,
  5032. subject: info.Subject,
  5033. keywords: info.Keywords,
  5034. creationDate,
  5035. modificationDate,
  5036. creator: info.Creator,
  5037. producer: info.Producer,
  5038. version: info.PDFFormatVersion,
  5039. pageCount: this.pdfDocument.numPages,
  5040. pageSize,
  5041. linearized: isLinearized,
  5042. _currentPageNumber: currentPageNumber,
  5043. _pagesRotation: pagesRotation
  5044. });
  5045. this.#updateUI();
  5046. const {
  5047. length
  5048. } = await this.pdfDocument.getDownloadInfo();
  5049. if (contentLength === length) {
  5050. return;
  5051. }
  5052. const data = Object.assign(Object.create(null), this.#fieldData);
  5053. data.fileSize = await this.#parseFileSize(length);
  5054. this.#fieldData = Object.freeze(data);
  5055. this.#updateUI();
  5056. }
  5057. async close() {
  5058. this.overlayManager.close(this.dialog);
  5059. }
  5060. setDocument(pdfDocument) {
  5061. if (this.pdfDocument) {
  5062. this.#reset();
  5063. this.#updateUI();
  5064. }
  5065. if (!pdfDocument) {
  5066. return;
  5067. }
  5068. this.pdfDocument = pdfDocument;
  5069. this._dataAvailableCapability.resolve();
  5070. }
  5071. #reset() {
  5072. this.pdfDocument = null;
  5073. this.#fieldData = null;
  5074. this._dataAvailableCapability = Promise.withResolvers();
  5075. this._currentPageNumber = 1;
  5076. this._pagesRotation = 0;
  5077. }
  5078. #updateUI() {
  5079. if (this.#fieldData && this.overlayManager.active !== this.dialog) {
  5080. return;
  5081. }
  5082. for (const id in this.fields) {
  5083. const content = this.#fieldData?.[id];
  5084. this.fields[id].textContent = content || content === 0 ? content : "-";
  5085. }
  5086. }
  5087. async #parseFileSize(b = 0) {
  5088. const kb = b / 1024,
  5089. mb = kb / 1024;
  5090. return kb ? this.l10n.get(mb >= 1 ? "pdfjs-document-properties-size-mb" : "pdfjs-document-properties-size-kb", {
  5091. mb,
  5092. kb,
  5093. b
  5094. }) : undefined;
  5095. }
  5096. async #parsePageSize(pageSizeInches, pagesRotation) {
  5097. if (!pageSizeInches) {
  5098. return undefined;
  5099. }
  5100. if (pagesRotation % 180 !== 0) {
  5101. pageSizeInches = {
  5102. width: pageSizeInches.height,
  5103. height: pageSizeInches.width
  5104. };
  5105. }
  5106. const isPortrait = isPortraitOrientation(pageSizeInches),
  5107. nonMetric = NON_METRIC_LOCALES.includes(this.l10n.getLanguage());
  5108. let sizeInches = {
  5109. width: Math.round(pageSizeInches.width * 100) / 100,
  5110. height: Math.round(pageSizeInches.height * 100) / 100
  5111. };
  5112. let sizeMillimeters = {
  5113. width: Math.round(pageSizeInches.width * 25.4 * 10) / 10,
  5114. height: Math.round(pageSizeInches.height * 25.4 * 10) / 10
  5115. };
  5116. let nameId = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES);
  5117. if (!nameId && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) {
  5118. const exactMillimeters = {
  5119. width: pageSizeInches.width * 25.4,
  5120. height: pageSizeInches.height * 25.4
  5121. };
  5122. const intMillimeters = {
  5123. width: Math.round(sizeMillimeters.width),
  5124. height: Math.round(sizeMillimeters.height)
  5125. };
  5126. if (Math.abs(exactMillimeters.width - intMillimeters.width) < 0.1 && Math.abs(exactMillimeters.height - intMillimeters.height) < 0.1) {
  5127. nameId = getPageName(intMillimeters, isPortrait, METRIC_PAGE_NAMES);
  5128. if (nameId) {
  5129. sizeInches = {
  5130. width: Math.round(intMillimeters.width / 25.4 * 100) / 100,
  5131. height: Math.round(intMillimeters.height / 25.4 * 100) / 100
  5132. };
  5133. sizeMillimeters = intMillimeters;
  5134. }
  5135. }
  5136. }
  5137. const [{
  5138. width,
  5139. height
  5140. }, unit, name, orientation] = await Promise.all([nonMetric ? sizeInches : sizeMillimeters, this.l10n.get(nonMetric ? "pdfjs-document-properties-page-size-unit-inches" : "pdfjs-document-properties-page-size-unit-millimeters"), nameId && this.l10n.get(nameId), this.l10n.get(isPortrait ? "pdfjs-document-properties-page-size-orientation-portrait" : "pdfjs-document-properties-page-size-orientation-landscape")]);
  5141. return this.l10n.get(name ? "pdfjs-document-properties-page-size-dimension-name-string" : "pdfjs-document-properties-page-size-dimension-string", {
  5142. width,
  5143. height,
  5144. unit,
  5145. name,
  5146. orientation
  5147. });
  5148. }
  5149. async #parseDate(inputDate) {
  5150. const dateObj = PDFDateString.toDateObject(inputDate);
  5151. return dateObj ? this.l10n.get("pdfjs-document-properties-date-time-string", {
  5152. dateObj: dateObj.valueOf()
  5153. }) : undefined;
  5154. }
  5155. #parseLinearization(isLinearized) {
  5156. return this.l10n.get(isLinearized ? "pdfjs-document-properties-linearized-yes" : "pdfjs-document-properties-linearized-no");
  5157. }
  5158. }
  5159. ;// ./web/pdf_find_utils.js
  5160. const CharacterType = {
  5161. SPACE: 0,
  5162. ALPHA_LETTER: 1,
  5163. PUNCT: 2,
  5164. HAN_LETTER: 3,
  5165. KATAKANA_LETTER: 4,
  5166. HIRAGANA_LETTER: 5,
  5167. HALFWIDTH_KATAKANA_LETTER: 6,
  5168. THAI_LETTER: 7
  5169. };
  5170. function isAlphabeticalScript(charCode) {
  5171. return charCode < 0x2e80;
  5172. }
  5173. function isAscii(charCode) {
  5174. return (charCode & 0xff80) === 0;
  5175. }
  5176. function isAsciiAlpha(charCode) {
  5177. return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a;
  5178. }
  5179. function isAsciiDigit(charCode) {
  5180. return charCode >= 0x30 && charCode <= 0x39;
  5181. }
  5182. function isAsciiSpace(charCode) {
  5183. return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a;
  5184. }
  5185. function isHan(charCode) {
  5186. return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff;
  5187. }
  5188. function isKatakana(charCode) {
  5189. return charCode >= 0x30a0 && charCode <= 0x30ff;
  5190. }
  5191. function isHiragana(charCode) {
  5192. return charCode >= 0x3040 && charCode <= 0x309f;
  5193. }
  5194. function isHalfwidthKatakana(charCode) {
  5195. return charCode >= 0xff60 && charCode <= 0xff9f;
  5196. }
  5197. function isThai(charCode) {
  5198. return (charCode & 0xff80) === 0x0e00;
  5199. }
  5200. function getCharacterType(charCode) {
  5201. if (isAlphabeticalScript(charCode)) {
  5202. if (isAscii(charCode)) {
  5203. if (isAsciiSpace(charCode)) {
  5204. return CharacterType.SPACE;
  5205. } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) {
  5206. return CharacterType.ALPHA_LETTER;
  5207. }
  5208. return CharacterType.PUNCT;
  5209. } else if (isThai(charCode)) {
  5210. return CharacterType.THAI_LETTER;
  5211. } else if (charCode === 0xa0) {
  5212. return CharacterType.SPACE;
  5213. }
  5214. return CharacterType.ALPHA_LETTER;
  5215. }
  5216. if (isHan(charCode)) {
  5217. return CharacterType.HAN_LETTER;
  5218. } else if (isKatakana(charCode)) {
  5219. return CharacterType.KATAKANA_LETTER;
  5220. } else if (isHiragana(charCode)) {
  5221. return CharacterType.HIRAGANA_LETTER;
  5222. } else if (isHalfwidthKatakana(charCode)) {
  5223. return CharacterType.HALFWIDTH_KATAKANA_LETTER;
  5224. }
  5225. return CharacterType.ALPHA_LETTER;
  5226. }
  5227. let NormalizeWithNFKC;
  5228. function getNormalizeWithNFKC() {
  5229. NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`;
  5230. return NormalizeWithNFKC;
  5231. }
  5232. ;// ./web/pdf_find_controller.js
  5233. const FindState = {
  5234. FOUND: 0,
  5235. NOT_FOUND: 1,
  5236. WRAPPED: 2,
  5237. PENDING: 3
  5238. };
  5239. const FIND_TIMEOUT = 250;
  5240. const MATCH_SCROLL_OFFSET_TOP = -50;
  5241. const MATCH_SCROLL_OFFSET_LEFT = -400;
  5242. const CHARACTERS_TO_NORMALIZE = {
  5243. "\u2010": "-",
  5244. "\u2018": "'",
  5245. "\u2019": "'",
  5246. "\u201A": "'",
  5247. "\u201B": "'",
  5248. "\u201C": '"',
  5249. "\u201D": '"',
  5250. "\u201E": '"',
  5251. "\u201F": '"',
  5252. "\u00BC": "1/4",
  5253. "\u00BD": "1/2",
  5254. "\u00BE": "3/4"
  5255. };
  5256. 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]);
  5257. let DIACRITICS_EXCEPTION_STR;
  5258. const DIACRITICS_REG_EXP = /\p{M}+/gu;
  5259. const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu;
  5260. const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u;
  5261. const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u;
  5262. const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g;
  5263. const SYLLABLES_LENGTHS = new Map();
  5264. const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]";
  5265. const NFKC_CHARS_TO_NORMALIZE = new Map();
  5266. let noSyllablesRegExp = null;
  5267. let withSyllablesRegExp = null;
  5268. function normalize(text) {
  5269. const syllablePositions = [];
  5270. let m;
  5271. while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) {
  5272. let {
  5273. index
  5274. } = m;
  5275. for (const char of m[0]) {
  5276. let len = SYLLABLES_LENGTHS.get(char);
  5277. if (!len) {
  5278. len = char.normalize("NFD").length;
  5279. SYLLABLES_LENGTHS.set(char, len);
  5280. }
  5281. syllablePositions.push([len, index++]);
  5282. }
  5283. }
  5284. const hasSyllables = syllablePositions.length > 0;
  5285. let normalizationRegex;
  5286. if (!hasSyllables && noSyllablesRegExp) {
  5287. normalizationRegex = noSyllablesRegExp;
  5288. } else if (hasSyllables && withSyllablesRegExp) {
  5289. normalizationRegex = withSyllablesRegExp;
  5290. } else {
  5291. const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join("");
  5292. const toNormalizeWithNFKC = getNormalizeWithNFKC();
  5293. const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])";
  5294. const HKDiacritics = "(?:\u3099|\u309A)";
  5295. const BrokenWord = `\\p{Ll}-\\n(?=\\p{Ll})|\\p{Lu}-\\n(?=\\p{L})`;
  5296. const regexps = [`[${replace}]`, `[${toNormalizeWithNFKC}]`, `${HKDiacritics}\\n`, "\\p{M}+(?:-\\n)?", `${BrokenWord}`, "\\S-\\n", `${CJK}\\n`, "\\n", hasSyllables ? FIRST_CHAR_SYLLABLES_REG_EXP : "\\u0000"];
  5297. normalizationRegex = new RegExp(regexps.map(r => `(${r})`).join("|"), "gum");
  5298. if (hasSyllables) {
  5299. withSyllablesRegExp = normalizationRegex;
  5300. } else {
  5301. noSyllablesRegExp = normalizationRegex;
  5302. }
  5303. }
  5304. const rawDiacriticsPositions = [];
  5305. while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) {
  5306. rawDiacriticsPositions.push([m[0].length, m.index]);
  5307. }
  5308. let normalized = text.normalize("NFD");
  5309. const positions = [0, 0];
  5310. let rawDiacriticsIndex = 0;
  5311. let syllableIndex = 0;
  5312. let shift = 0;
  5313. let shiftOrigin = 0;
  5314. let eol = 0;
  5315. let hasDiacritics = false;
  5316. normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => {
  5317. i -= shiftOrigin;
  5318. if (p1) {
  5319. const replacement = CHARACTERS_TO_NORMALIZE[p1];
  5320. const jj = replacement.length;
  5321. for (let j = 1; j < jj; j++) {
  5322. positions.push(i - shift + j, shift - j);
  5323. }
  5324. shift -= jj - 1;
  5325. return replacement;
  5326. }
  5327. if (p2) {
  5328. let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2);
  5329. if (!replacement) {
  5330. replacement = p2.normalize("NFKC");
  5331. NFKC_CHARS_TO_NORMALIZE.set(p2, replacement);
  5332. }
  5333. const jj = replacement.length;
  5334. for (let j = 1; j < jj; j++) {
  5335. positions.push(i - shift + j, shift - j);
  5336. }
  5337. shift -= jj - 1;
  5338. return replacement;
  5339. }
  5340. if (p3) {
  5341. hasDiacritics = true;
  5342. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  5343. ++rawDiacriticsIndex;
  5344. } else {
  5345. positions.push(i - 1 - shift + 1, shift - 1);
  5346. shift -= 1;
  5347. shiftOrigin += 1;
  5348. }
  5349. positions.push(i - shift + 1, shift);
  5350. shiftOrigin += 1;
  5351. eol += 1;
  5352. return p3.charAt(0);
  5353. }
  5354. if (p4) {
  5355. const hasTrailingDashEOL = p4.endsWith("\n");
  5356. const len = hasTrailingDashEOL ? p4.length - 2 : p4.length;
  5357. hasDiacritics = true;
  5358. let jj = len;
  5359. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  5360. jj -= rawDiacriticsPositions[rawDiacriticsIndex][0];
  5361. ++rawDiacriticsIndex;
  5362. }
  5363. for (let j = 1; j <= jj; j++) {
  5364. positions.push(i - 1 - shift + j, shift - j);
  5365. }
  5366. shift -= jj;
  5367. shiftOrigin += jj;
  5368. if (hasTrailingDashEOL) {
  5369. i += len - 1;
  5370. positions.push(i - shift + 1, 1 + shift);
  5371. shift += 1;
  5372. shiftOrigin += 1;
  5373. eol += 1;
  5374. return p4.slice(0, len);
  5375. }
  5376. return p4;
  5377. }
  5378. if (p5) {
  5379. const len = p5.length - 2;
  5380. positions.push(i - shift + len, 1 + shift);
  5381. shift += 1;
  5382. shiftOrigin += 1;
  5383. eol += 1;
  5384. return p5.slice(0, -2);
  5385. }
  5386. if (p6) {
  5387. shiftOrigin += 1;
  5388. eol += 1;
  5389. return p6.slice(0, -1);
  5390. }
  5391. if (p7) {
  5392. const len = p7.length - 1;
  5393. positions.push(i - shift + len, shift);
  5394. shiftOrigin += 1;
  5395. eol += 1;
  5396. return p7.slice(0, -1);
  5397. }
  5398. if (p8) {
  5399. positions.push(i - shift + 1, shift - 1);
  5400. shift -= 1;
  5401. shiftOrigin += 1;
  5402. eol += 1;
  5403. return " ";
  5404. }
  5405. if (i + eol === syllablePositions[syllableIndex]?.[1]) {
  5406. const newCharLen = syllablePositions[syllableIndex][0] - 1;
  5407. ++syllableIndex;
  5408. for (let j = 1; j <= newCharLen; j++) {
  5409. positions.push(i - (shift - j), shift - j);
  5410. }
  5411. shift -= newCharLen;
  5412. shiftOrigin += newCharLen;
  5413. }
  5414. return p9;
  5415. });
  5416. positions.push(normalized.length, shift);
  5417. const starts = new Uint32Array(positions.length >> 1);
  5418. const shifts = new Int32Array(positions.length >> 1);
  5419. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  5420. starts[i >> 1] = positions[i];
  5421. shifts[i >> 1] = positions[i + 1];
  5422. }
  5423. return [normalized, [starts, shifts], hasDiacritics];
  5424. }
  5425. function getOriginalIndex(diffs, pos, len) {
  5426. if (!diffs) {
  5427. return [pos, len];
  5428. }
  5429. const [starts, shifts] = diffs;
  5430. const start = pos;
  5431. const end = pos + len - 1;
  5432. let i = binarySearchFirstItem(starts, x => x >= start);
  5433. if (starts[i] > start) {
  5434. --i;
  5435. }
  5436. let j = binarySearchFirstItem(starts, x => x >= end, i);
  5437. if (starts[j] > end) {
  5438. --j;
  5439. }
  5440. const oldStart = start + shifts[i];
  5441. const oldEnd = end + shifts[j];
  5442. const oldLen = oldEnd + 1 - oldStart;
  5443. return [oldStart, oldLen];
  5444. }
  5445. class PDFFindController {
  5446. #state = null;
  5447. #updateMatchesCountOnProgress = true;
  5448. #visitedPagesCount = 0;
  5449. constructor({
  5450. linkService,
  5451. eventBus,
  5452. updateMatchesCountOnProgress = true
  5453. }) {
  5454. this._linkService = linkService;
  5455. this._eventBus = eventBus;
  5456. this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress;
  5457. this.onIsPageVisible = null;
  5458. this.#reset();
  5459. eventBus._on("find", this.#onFind.bind(this));
  5460. eventBus._on("findbarclose", this.#onFindBarClose.bind(this));
  5461. }
  5462. get highlightMatches() {
  5463. return this._highlightMatches;
  5464. }
  5465. get pageMatches() {
  5466. return this._pageMatches;
  5467. }
  5468. get pageMatchesLength() {
  5469. return this._pageMatchesLength;
  5470. }
  5471. get selected() {
  5472. return this._selected;
  5473. }
  5474. get state() {
  5475. return this.#state;
  5476. }
  5477. setDocument(pdfDocument) {
  5478. if (this._pdfDocument) {
  5479. this.#reset();
  5480. }
  5481. if (!pdfDocument) {
  5482. return;
  5483. }
  5484. this._pdfDocument = pdfDocument;
  5485. this._firstPageCapability.resolve();
  5486. }
  5487. #onFind(state) {
  5488. if (!state) {
  5489. return;
  5490. }
  5491. const pdfDocument = this._pdfDocument;
  5492. const {
  5493. type
  5494. } = state;
  5495. if (this.#state === null || this.#shouldDirtyMatch(state)) {
  5496. this._dirtyMatch = true;
  5497. }
  5498. this.#state = state;
  5499. if (type !== "highlightallchange") {
  5500. this.#updateUIState(FindState.PENDING);
  5501. }
  5502. this._firstPageCapability.promise.then(() => {
  5503. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  5504. return;
  5505. }
  5506. this.#extractText();
  5507. const findbarClosed = !this._highlightMatches;
  5508. const pendingTimeout = !!this._findTimeout;
  5509. if (this._findTimeout) {
  5510. clearTimeout(this._findTimeout);
  5511. this._findTimeout = null;
  5512. }
  5513. if (!type) {
  5514. this._findTimeout = setTimeout(() => {
  5515. this.#nextMatch();
  5516. this._findTimeout = null;
  5517. }, FIND_TIMEOUT);
  5518. } else if (this._dirtyMatch) {
  5519. this.#nextMatch();
  5520. } else if (type === "again") {
  5521. this.#nextMatch();
  5522. if (findbarClosed && this.#state.highlightAll) {
  5523. this.#updateAllPages();
  5524. }
  5525. } else if (type === "highlightallchange") {
  5526. if (pendingTimeout) {
  5527. this.#nextMatch();
  5528. } else {
  5529. this._highlightMatches = true;
  5530. }
  5531. this.#updateAllPages();
  5532. } else {
  5533. this.#nextMatch();
  5534. }
  5535. });
  5536. }
  5537. scrollMatchIntoView({
  5538. element = null,
  5539. selectedLeft = 0,
  5540. pageIndex = -1,
  5541. matchIndex = -1
  5542. }) {
  5543. if (!this._scrollMatches || !element) {
  5544. return;
  5545. } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) {
  5546. return;
  5547. } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) {
  5548. return;
  5549. }
  5550. this._scrollMatches = false;
  5551. const spot = {
  5552. top: MATCH_SCROLL_OFFSET_TOP,
  5553. left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT
  5554. };
  5555. scrollIntoView(element, spot, true);
  5556. }
  5557. #reset() {
  5558. this._highlightMatches = false;
  5559. this._scrollMatches = false;
  5560. this._pdfDocument = null;
  5561. this._pageMatches = [];
  5562. this._pageMatchesLength = [];
  5563. this.#visitedPagesCount = 0;
  5564. this.#state = null;
  5565. this._selected = {
  5566. pageIdx: -1,
  5567. matchIdx: -1
  5568. };
  5569. this._offset = {
  5570. pageIdx: null,
  5571. matchIdx: null,
  5572. wrapped: false
  5573. };
  5574. this._extractTextPromises = [];
  5575. this._pageContents = [];
  5576. this._pageDiffs = [];
  5577. this._hasDiacritics = [];
  5578. this._matchesCountTotal = 0;
  5579. this._pagesToSearch = null;
  5580. this._pendingFindMatches = new Set();
  5581. this._resumePageIdx = null;
  5582. this._dirtyMatch = false;
  5583. clearTimeout(this._findTimeout);
  5584. this._findTimeout = null;
  5585. this._firstPageCapability = Promise.withResolvers();
  5586. }
  5587. get #query() {
  5588. const {
  5589. query
  5590. } = this.#state;
  5591. if (typeof query === "string") {
  5592. if (query !== this._rawQuery) {
  5593. this._rawQuery = query;
  5594. [this._normalizedQuery] = normalize(query);
  5595. }
  5596. return this._normalizedQuery;
  5597. }
  5598. return (query || []).filter(q => !!q).map(q => normalize(q)[0]);
  5599. }
  5600. #shouldDirtyMatch(state) {
  5601. const newQuery = state.query,
  5602. prevQuery = this.#state.query;
  5603. const newType = typeof newQuery,
  5604. prevType = typeof prevQuery;
  5605. if (newType !== prevType) {
  5606. return true;
  5607. }
  5608. if (newType === "string") {
  5609. if (newQuery !== prevQuery) {
  5610. return true;
  5611. }
  5612. } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) {
  5613. return true;
  5614. }
  5615. switch (state.type) {
  5616. case "again":
  5617. const pageNumber = this._selected.pageIdx + 1;
  5618. const linkService = this._linkService;
  5619. return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true);
  5620. case "highlightallchange":
  5621. return false;
  5622. }
  5623. return true;
  5624. }
  5625. #isEntireWord(content, startIdx, length) {
  5626. let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP);
  5627. if (match) {
  5628. const first = content.charCodeAt(startIdx);
  5629. const limit = match[1].charCodeAt(0);
  5630. if (getCharacterType(first) === getCharacterType(limit)) {
  5631. return false;
  5632. }
  5633. }
  5634. match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP);
  5635. if (match) {
  5636. const last = content.charCodeAt(startIdx + length - 1);
  5637. const limit = match[1].charCodeAt(0);
  5638. if (getCharacterType(last) === getCharacterType(limit)) {
  5639. return false;
  5640. }
  5641. }
  5642. return true;
  5643. }
  5644. #convertToRegExpString(query, hasDiacritics) {
  5645. const {
  5646. matchDiacritics
  5647. } = this.#state;
  5648. let isUnicode = false;
  5649. query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => {
  5650. if (p1) {
  5651. return `[ ]*\\${p1}[ ]*`;
  5652. }
  5653. if (p2) {
  5654. return `[ ]*${p2}[ ]*`;
  5655. }
  5656. if (p3) {
  5657. return "[ ]+";
  5658. }
  5659. if (matchDiacritics) {
  5660. return p4 || p5;
  5661. }
  5662. if (p4) {
  5663. return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : "";
  5664. }
  5665. if (hasDiacritics) {
  5666. isUnicode = true;
  5667. return `${p5}\\p{M}*`;
  5668. }
  5669. return p5;
  5670. });
  5671. const trailingSpaces = "[ ]*";
  5672. if (query.endsWith(trailingSpaces)) {
  5673. query = query.slice(0, query.length - trailingSpaces.length);
  5674. }
  5675. if (matchDiacritics) {
  5676. if (hasDiacritics) {
  5677. DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION);
  5678. isUnicode = true;
  5679. query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`;
  5680. }
  5681. }
  5682. return [isUnicode, query];
  5683. }
  5684. #calculateMatch(pageIndex) {
  5685. if (!this.#state) {
  5686. return;
  5687. }
  5688. const query = this.#query;
  5689. if (query.length === 0) {
  5690. return;
  5691. }
  5692. const pageContent = this._pageContents[pageIndex];
  5693. const matcherResult = this.match(query, pageContent, pageIndex);
  5694. const matches = this._pageMatches[pageIndex] = [];
  5695. const matchesLength = this._pageMatchesLength[pageIndex] = [];
  5696. const diffs = this._pageDiffs[pageIndex];
  5697. matcherResult?.forEach(({
  5698. index,
  5699. length
  5700. }) => {
  5701. const [matchPos, matchLen] = getOriginalIndex(diffs, index, length);
  5702. if (matchLen) {
  5703. matches.push(matchPos);
  5704. matchesLength.push(matchLen);
  5705. }
  5706. });
  5707. if (this.#state.highlightAll) {
  5708. this.#updatePage(pageIndex);
  5709. }
  5710. if (this._resumePageIdx === pageIndex) {
  5711. this._resumePageIdx = null;
  5712. this.#nextPageMatch();
  5713. }
  5714. const pageMatchesCount = matches.length;
  5715. this._matchesCountTotal += pageMatchesCount;
  5716. if (this.#updateMatchesCountOnProgress) {
  5717. if (pageMatchesCount > 0) {
  5718. this.#updateUIResultsCount();
  5719. }
  5720. } else if (++this.#visitedPagesCount === this._linkService.pagesCount) {
  5721. this.#updateUIResultsCount();
  5722. }
  5723. }
  5724. match(query, pageContent, pageIndex) {
  5725. const hasDiacritics = this._hasDiacritics[pageIndex];
  5726. let isUnicode = false;
  5727. if (typeof query === "string") {
  5728. [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics);
  5729. } else {
  5730. query = query.sort().reverse().map(q => {
  5731. const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics);
  5732. isUnicode ||= isUnicodePart;
  5733. return `(${queryPart})`;
  5734. }).join("|");
  5735. }
  5736. if (!query) {
  5737. return undefined;
  5738. }
  5739. const {
  5740. caseSensitive,
  5741. entireWord
  5742. } = this.#state;
  5743. const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`;
  5744. query = new RegExp(query, flags);
  5745. const matches = [];
  5746. let match;
  5747. while ((match = query.exec(pageContent)) !== null) {
  5748. if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) {
  5749. continue;
  5750. }
  5751. matches.push({
  5752. index: match.index,
  5753. length: match[0].length
  5754. });
  5755. }
  5756. return matches;
  5757. }
  5758. #extractText() {
  5759. if (this._extractTextPromises.length > 0) {
  5760. return;
  5761. }
  5762. let deferred = Promise.resolve();
  5763. const textOptions = {
  5764. disableNormalization: true
  5765. };
  5766. const pdfDoc = this._pdfDocument;
  5767. for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) {
  5768. const {
  5769. promise,
  5770. resolve
  5771. } = Promise.withResolvers();
  5772. this._extractTextPromises[i] = promise;
  5773. deferred = deferred.then(async () => {
  5774. if (pdfDoc !== this._pdfDocument) {
  5775. resolve();
  5776. return;
  5777. }
  5778. await pdfDoc.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => {
  5779. const strBuf = [];
  5780. for (const textItem of textContent.items) {
  5781. strBuf.push(textItem.str);
  5782. if (textItem.hasEOL) {
  5783. strBuf.push("\n");
  5784. }
  5785. }
  5786. [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join(""));
  5787. resolve();
  5788. }, reason => {
  5789. console.error(`Unable to get text content for page ${i + 1}`, reason);
  5790. this._pageContents[i] = "";
  5791. this._pageDiffs[i] = null;
  5792. this._hasDiacritics[i] = false;
  5793. resolve();
  5794. });
  5795. });
  5796. }
  5797. }
  5798. #updatePage(index) {
  5799. if (this._scrollMatches && this._selected.pageIdx === index) {
  5800. this._linkService.page = index + 1;
  5801. }
  5802. this._eventBus.dispatch("updatetextlayermatches", {
  5803. source: this,
  5804. pageIndex: index
  5805. });
  5806. }
  5807. #updateAllPages() {
  5808. this._eventBus.dispatch("updatetextlayermatches", {
  5809. source: this,
  5810. pageIndex: -1
  5811. });
  5812. }
  5813. #nextMatch() {
  5814. const previous = this.#state.findPrevious;
  5815. const currentPageIndex = this._linkService.page - 1;
  5816. const numPages = this._linkService.pagesCount;
  5817. this._highlightMatches = true;
  5818. if (this._dirtyMatch) {
  5819. this._dirtyMatch = false;
  5820. this._selected.pageIdx = this._selected.matchIdx = -1;
  5821. this._offset.pageIdx = currentPageIndex;
  5822. this._offset.matchIdx = null;
  5823. this._offset.wrapped = false;
  5824. this._resumePageIdx = null;
  5825. this._pageMatches.length = 0;
  5826. this._pageMatchesLength.length = 0;
  5827. this.#visitedPagesCount = 0;
  5828. this._matchesCountTotal = 0;
  5829. this.#updateAllPages();
  5830. for (let i = 0; i < numPages; i++) {
  5831. if (this._pendingFindMatches.has(i)) {
  5832. continue;
  5833. }
  5834. this._pendingFindMatches.add(i);
  5835. this._extractTextPromises[i].then(() => {
  5836. this._pendingFindMatches.delete(i);
  5837. this.#calculateMatch(i);
  5838. });
  5839. }
  5840. }
  5841. const query = this.#query;
  5842. if (query.length === 0) {
  5843. this.#updateUIState(FindState.FOUND);
  5844. return;
  5845. }
  5846. if (this._resumePageIdx) {
  5847. return;
  5848. }
  5849. const offset = this._offset;
  5850. this._pagesToSearch = numPages;
  5851. if (offset.matchIdx !== null) {
  5852. const numPageMatches = this._pageMatches[offset.pageIdx].length;
  5853. if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
  5854. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  5855. this.#updateMatch(true);
  5856. return;
  5857. }
  5858. this.#advanceOffsetPage(previous);
  5859. }
  5860. this.#nextPageMatch();
  5861. }
  5862. #matchesReady(matches) {
  5863. const offset = this._offset;
  5864. const numMatches = matches.length;
  5865. const previous = this.#state.findPrevious;
  5866. if (numMatches) {
  5867. offset.matchIdx = previous ? numMatches - 1 : 0;
  5868. this.#updateMatch(true);
  5869. return true;
  5870. }
  5871. this.#advanceOffsetPage(previous);
  5872. if (offset.wrapped) {
  5873. offset.matchIdx = null;
  5874. if (this._pagesToSearch < 0) {
  5875. this.#updateMatch(false);
  5876. return true;
  5877. }
  5878. }
  5879. return false;
  5880. }
  5881. #nextPageMatch() {
  5882. if (this._resumePageIdx !== null) {
  5883. console.error("There can only be one pending page.");
  5884. }
  5885. let matches = null;
  5886. do {
  5887. const pageIdx = this._offset.pageIdx;
  5888. matches = this._pageMatches[pageIdx];
  5889. if (!matches) {
  5890. this._resumePageIdx = pageIdx;
  5891. break;
  5892. }
  5893. } while (!this.#matchesReady(matches));
  5894. }
  5895. #advanceOffsetPage(previous) {
  5896. const offset = this._offset;
  5897. const numPages = this._linkService.pagesCount;
  5898. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  5899. offset.matchIdx = null;
  5900. this._pagesToSearch--;
  5901. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  5902. offset.pageIdx = previous ? numPages - 1 : 0;
  5903. offset.wrapped = true;
  5904. }
  5905. }
  5906. #updateMatch(found = false) {
  5907. let state = FindState.NOT_FOUND;
  5908. const wrapped = this._offset.wrapped;
  5909. this._offset.wrapped = false;
  5910. if (found) {
  5911. const previousPage = this._selected.pageIdx;
  5912. this._selected.pageIdx = this._offset.pageIdx;
  5913. this._selected.matchIdx = this._offset.matchIdx;
  5914. state = wrapped ? FindState.WRAPPED : FindState.FOUND;
  5915. if (previousPage !== -1 && previousPage !== this._selected.pageIdx) {
  5916. this.#updatePage(previousPage);
  5917. }
  5918. }
  5919. this.#updateUIState(state, this.#state.findPrevious);
  5920. if (this._selected.pageIdx !== -1) {
  5921. this._scrollMatches = true;
  5922. this.#updatePage(this._selected.pageIdx);
  5923. }
  5924. }
  5925. #onFindBarClose(evt) {
  5926. const pdfDocument = this._pdfDocument;
  5927. this._firstPageCapability.promise.then(() => {
  5928. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  5929. return;
  5930. }
  5931. if (this._findTimeout) {
  5932. clearTimeout(this._findTimeout);
  5933. this._findTimeout = null;
  5934. }
  5935. if (this._resumePageIdx) {
  5936. this._resumePageIdx = null;
  5937. this._dirtyMatch = true;
  5938. }
  5939. this.#updateUIState(FindState.FOUND);
  5940. this._highlightMatches = false;
  5941. this.#updateAllPages();
  5942. });
  5943. }
  5944. #requestMatchesCount() {
  5945. const {
  5946. pageIdx,
  5947. matchIdx
  5948. } = this._selected;
  5949. let current = 0,
  5950. total = this._matchesCountTotal;
  5951. if (matchIdx !== -1) {
  5952. for (let i = 0; i < pageIdx; i++) {
  5953. current += this._pageMatches[i]?.length || 0;
  5954. }
  5955. current += matchIdx + 1;
  5956. }
  5957. if (current < 1 || current > total) {
  5958. current = total = 0;
  5959. }
  5960. return {
  5961. current,
  5962. total
  5963. };
  5964. }
  5965. #updateUIResultsCount() {
  5966. this._eventBus.dispatch("updatefindmatchescount", {
  5967. source: this,
  5968. matchesCount: this.#requestMatchesCount()
  5969. });
  5970. }
  5971. #updateUIState(state, previous = false) {
  5972. if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) {
  5973. return;
  5974. }
  5975. this._eventBus.dispatch("updatefindcontrolstate", {
  5976. source: this,
  5977. state,
  5978. previous,
  5979. entireWord: this.#state?.entireWord ?? null,
  5980. matchesCount: this.#requestMatchesCount(),
  5981. rawQuery: this.#state?.query ?? null
  5982. });
  5983. }
  5984. }
  5985. ;// ./web/pdf_find_bar.js
  5986. const MATCHES_COUNT_LIMIT = 1000;
  5987. class PDFFindBar {
  5988. #mainContainer;
  5989. #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this));
  5990. constructor(options, mainContainer, eventBus) {
  5991. this.opened = false;
  5992. this.bar = options.bar;
  5993. this.toggleButton = options.toggleButton;
  5994. this.findField = options.findField;
  5995. this.highlightAll = options.highlightAllCheckbox;
  5996. this.caseSensitive = options.caseSensitiveCheckbox;
  5997. this.matchDiacritics = options.matchDiacriticsCheckbox;
  5998. this.entireWord = options.entireWordCheckbox;
  5999. this.findMsg = options.findMsg;
  6000. this.findResultsCount = options.findResultsCount;
  6001. this.findPreviousButton = options.findPreviousButton;
  6002. this.findNextButton = options.findNextButton;
  6003. this.eventBus = eventBus;
  6004. this.#mainContainer = mainContainer;
  6005. const checkedInputs = new Map([[this.highlightAll, "highlightallchange"], [this.caseSensitive, "casesensitivitychange"], [this.entireWord, "entirewordchange"], [this.matchDiacritics, "diacriticmatchingchange"]]);
  6006. this.toggleButton.addEventListener("click", () => {
  6007. this.toggle();
  6008. });
  6009. this.findField.addEventListener("input", () => {
  6010. this.dispatchEvent("");
  6011. });
  6012. this.bar.addEventListener("keydown", ({
  6013. keyCode,
  6014. shiftKey,
  6015. target
  6016. }) => {
  6017. switch (keyCode) {
  6018. case 13:
  6019. if (target === this.findField) {
  6020. this.dispatchEvent("again", shiftKey);
  6021. } else if (checkedInputs.has(target)) {
  6022. target.checked = !target.checked;
  6023. this.dispatchEvent(checkedInputs.get(target));
  6024. }
  6025. break;
  6026. case 27:
  6027. this.close();
  6028. break;
  6029. }
  6030. });
  6031. this.findPreviousButton.addEventListener("click", () => {
  6032. this.dispatchEvent("again", true);
  6033. });
  6034. this.findNextButton.addEventListener("click", () => {
  6035. this.dispatchEvent("again", false);
  6036. });
  6037. for (const [elem, evtName] of checkedInputs) {
  6038. elem.addEventListener("click", () => {
  6039. this.dispatchEvent(evtName);
  6040. });
  6041. }
  6042. }
  6043. reset() {
  6044. this.updateUIState();
  6045. }
  6046. dispatchEvent(type, findPrev = false) {
  6047. this.eventBus.dispatch("find", {
  6048. source: this,
  6049. type,
  6050. query: this.findField.value,
  6051. caseSensitive: this.caseSensitive.checked,
  6052. entireWord: this.entireWord.checked,
  6053. highlightAll: this.highlightAll.checked,
  6054. findPrevious: findPrev,
  6055. matchDiacritics: this.matchDiacritics.checked
  6056. });
  6057. }
  6058. updateUIState(state, previous, matchesCount) {
  6059. const {
  6060. findField,
  6061. findMsg
  6062. } = this;
  6063. let findMsgId = "",
  6064. status = "";
  6065. switch (state) {
  6066. case FindState.FOUND:
  6067. break;
  6068. case FindState.PENDING:
  6069. status = "pending";
  6070. break;
  6071. case FindState.NOT_FOUND:
  6072. findMsgId = "pdfjs-find-not-found";
  6073. status = "notFound";
  6074. break;
  6075. case FindState.WRAPPED:
  6076. findMsgId = previous ? "pdfjs-find-reached-top" : "pdfjs-find-reached-bottom";
  6077. break;
  6078. }
  6079. findField.setAttribute("data-status", status);
  6080. findField.setAttribute("aria-invalid", state === FindState.NOT_FOUND);
  6081. findMsg.setAttribute("data-status", status);
  6082. if (findMsgId) {
  6083. findMsg.setAttribute("data-l10n-id", findMsgId);
  6084. } else {
  6085. findMsg.removeAttribute("data-l10n-id");
  6086. findMsg.textContent = "";
  6087. }
  6088. this.updateResultsCount(matchesCount);
  6089. }
  6090. updateResultsCount({
  6091. current = 0,
  6092. total = 0
  6093. } = {}) {
  6094. const {
  6095. findResultsCount
  6096. } = this;
  6097. if (total > 0) {
  6098. const limit = MATCHES_COUNT_LIMIT;
  6099. findResultsCount.setAttribute("data-l10n-id", total > limit ? "pdfjs-find-match-count-limit" : "pdfjs-find-match-count");
  6100. findResultsCount.setAttribute("data-l10n-args", JSON.stringify({
  6101. limit,
  6102. current,
  6103. total
  6104. }));
  6105. } else {
  6106. findResultsCount.removeAttribute("data-l10n-id");
  6107. findResultsCount.textContent = "";
  6108. }
  6109. }
  6110. open() {
  6111. if (!this.opened) {
  6112. this.#resizeObserver.observe(this.#mainContainer);
  6113. this.#resizeObserver.observe(this.bar);
  6114. this.opened = true;
  6115. toggleExpandedBtn(this.toggleButton, true, this.bar);
  6116. }
  6117. this.findField.select();
  6118. this.findField.focus();
  6119. }
  6120. close() {
  6121. if (!this.opened) {
  6122. return;
  6123. }
  6124. this.#resizeObserver.disconnect();
  6125. this.opened = false;
  6126. toggleExpandedBtn(this.toggleButton, false, this.bar);
  6127. this.eventBus.dispatch("findbarclose", {
  6128. source: this
  6129. });
  6130. }
  6131. toggle() {
  6132. if (this.opened) {
  6133. this.close();
  6134. } else {
  6135. this.open();
  6136. }
  6137. }
  6138. #resizeObserverCallback() {
  6139. const {
  6140. bar
  6141. } = this;
  6142. bar.classList.remove("wrapContainers");
  6143. const findbarHeight = bar.clientHeight;
  6144. const inputContainerHeight = bar.firstElementChild.clientHeight;
  6145. if (findbarHeight > inputContainerHeight) {
  6146. bar.classList.add("wrapContainers");
  6147. }
  6148. }
  6149. }
  6150. ;// ./web/pdf_history.js
  6151. const HASH_CHANGE_TIMEOUT = 1000;
  6152. const POSITION_UPDATED_THRESHOLD = 50;
  6153. const UPDATE_VIEWAREA_TIMEOUT = 1000;
  6154. function getCurrentHash() {
  6155. return document.location.hash;
  6156. }
  6157. class PDFHistory {
  6158. #eventAbortController = null;
  6159. constructor({
  6160. linkService,
  6161. eventBus
  6162. }) {
  6163. this.linkService = linkService;
  6164. this.eventBus = eventBus;
  6165. this._initialized = false;
  6166. this._fingerprint = "";
  6167. this.reset();
  6168. this.eventBus._on("pagesinit", () => {
  6169. this._isPagesLoaded = false;
  6170. this.eventBus._on("pagesloaded", evt => {
  6171. this._isPagesLoaded = !!evt.pagesCount;
  6172. }, {
  6173. once: true
  6174. });
  6175. });
  6176. }
  6177. initialize({
  6178. fingerprint,
  6179. resetHistory = false,
  6180. updateUrl = false
  6181. }) {
  6182. if (!fingerprint || typeof fingerprint !== "string") {
  6183. console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');
  6184. return;
  6185. }
  6186. if (this._initialized) {
  6187. this.reset();
  6188. }
  6189. const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint;
  6190. this._fingerprint = fingerprint;
  6191. this._updateUrl = updateUrl === true;
  6192. this._initialized = true;
  6193. this.#bindEvents();
  6194. const state = window.history.state;
  6195. this._popStateInProgress = false;
  6196. this._blockHashChange = 0;
  6197. this._currentHash = getCurrentHash();
  6198. this._numPositionUpdates = 0;
  6199. this._uid = this._maxUid = 0;
  6200. this._destination = null;
  6201. this._position = null;
  6202. if (!this.#isValidState(state, true) || resetHistory) {
  6203. const {
  6204. hash,
  6205. page,
  6206. rotation
  6207. } = this.#parseCurrentHash(true);
  6208. if (!hash || reInitialized || resetHistory) {
  6209. this.#pushOrReplaceState(null, true);
  6210. return;
  6211. }
  6212. this.#pushOrReplaceState({
  6213. hash,
  6214. page,
  6215. rotation
  6216. }, true);
  6217. return;
  6218. }
  6219. const destination = state.destination;
  6220. this.#updateInternalState(destination, state.uid, true);
  6221. if (destination.rotation !== undefined) {
  6222. this._initialRotation = destination.rotation;
  6223. }
  6224. if (destination.dest) {
  6225. this._initialBookmark = JSON.stringify(destination.dest);
  6226. this._destination.page = null;
  6227. } else if (destination.hash) {
  6228. this._initialBookmark = destination.hash;
  6229. } else if (destination.page) {
  6230. this._initialBookmark = `page=${destination.page}`;
  6231. }
  6232. }
  6233. reset() {
  6234. if (this._initialized) {
  6235. this.#pageHide();
  6236. this._initialized = false;
  6237. this.#unbindEvents();
  6238. }
  6239. if (this._updateViewareaTimeout) {
  6240. clearTimeout(this._updateViewareaTimeout);
  6241. this._updateViewareaTimeout = null;
  6242. }
  6243. this._initialBookmark = null;
  6244. this._initialRotation = null;
  6245. }
  6246. push({
  6247. namedDest = null,
  6248. explicitDest,
  6249. pageNumber
  6250. }) {
  6251. if (!this._initialized) {
  6252. return;
  6253. }
  6254. if (namedDest && typeof namedDest !== "string") {
  6255. console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`);
  6256. return;
  6257. } else if (!Array.isArray(explicitDest)) {
  6258. console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`);
  6259. return;
  6260. } else if (!this.#isValidPage(pageNumber)) {
  6261. if (pageNumber !== null || this._destination) {
  6262. console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`);
  6263. return;
  6264. }
  6265. }
  6266. const hash = namedDest || JSON.stringify(explicitDest);
  6267. if (!hash) {
  6268. return;
  6269. }
  6270. let forceReplace = false;
  6271. if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) {
  6272. if (this._destination.page) {
  6273. return;
  6274. }
  6275. forceReplace = true;
  6276. }
  6277. if (this._popStateInProgress && !forceReplace) {
  6278. return;
  6279. }
  6280. this.#pushOrReplaceState({
  6281. dest: explicitDest,
  6282. hash,
  6283. page: pageNumber,
  6284. rotation: this.linkService.rotation
  6285. }, forceReplace);
  6286. if (!this._popStateInProgress) {
  6287. this._popStateInProgress = true;
  6288. Promise.resolve().then(() => {
  6289. this._popStateInProgress = false;
  6290. });
  6291. }
  6292. }
  6293. pushPage(pageNumber) {
  6294. if (!this._initialized) {
  6295. return;
  6296. }
  6297. if (!this.#isValidPage(pageNumber)) {
  6298. console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`);
  6299. return;
  6300. }
  6301. if (this._destination?.page === pageNumber) {
  6302. return;
  6303. }
  6304. if (this._popStateInProgress) {
  6305. return;
  6306. }
  6307. this.#pushOrReplaceState({
  6308. dest: null,
  6309. hash: `page=${pageNumber}`,
  6310. page: pageNumber,
  6311. rotation: this.linkService.rotation
  6312. });
  6313. if (!this._popStateInProgress) {
  6314. this._popStateInProgress = true;
  6315. Promise.resolve().then(() => {
  6316. this._popStateInProgress = false;
  6317. });
  6318. }
  6319. }
  6320. pushCurrentPosition() {
  6321. if (!this._initialized || this._popStateInProgress) {
  6322. return;
  6323. }
  6324. this.#tryPushCurrentPosition();
  6325. }
  6326. back() {
  6327. if (!this._initialized || this._popStateInProgress) {
  6328. return;
  6329. }
  6330. const state = window.history.state;
  6331. if (this.#isValidState(state) && state.uid > 0) {
  6332. window.history.back();
  6333. }
  6334. }
  6335. forward() {
  6336. if (!this._initialized || this._popStateInProgress) {
  6337. return;
  6338. }
  6339. const state = window.history.state;
  6340. if (this.#isValidState(state) && state.uid < this._maxUid) {
  6341. window.history.forward();
  6342. }
  6343. }
  6344. get popStateInProgress() {
  6345. return this._initialized && (this._popStateInProgress || this._blockHashChange > 0);
  6346. }
  6347. get initialBookmark() {
  6348. return this._initialized ? this._initialBookmark : null;
  6349. }
  6350. get initialRotation() {
  6351. return this._initialized ? this._initialRotation : null;
  6352. }
  6353. #pushOrReplaceState(destination, forceReplace = false) {
  6354. const shouldReplace = forceReplace || !this._destination;
  6355. const newState = {
  6356. fingerprint: this._fingerprint,
  6357. uid: shouldReplace ? this._uid : this._uid + 1,
  6358. destination
  6359. };
  6360. this.#updateInternalState(destination, newState.uid);
  6361. let newUrl;
  6362. if (this._updateUrl && destination?.hash) {
  6363. const {
  6364. href,
  6365. protocol
  6366. } = document.location;
  6367. if (protocol !== "file:") {
  6368. newUrl = updateUrlHash(href, destination.hash);
  6369. }
  6370. }
  6371. if (shouldReplace) {
  6372. window.history.replaceState(newState, "", newUrl);
  6373. } else {
  6374. window.history.pushState(newState, "", newUrl);
  6375. }
  6376. }
  6377. #tryPushCurrentPosition(temporary = false) {
  6378. if (!this._position) {
  6379. return;
  6380. }
  6381. let position = this._position;
  6382. if (temporary) {
  6383. position = Object.assign(Object.create(null), this._position);
  6384. position.temporary = true;
  6385. }
  6386. if (!this._destination) {
  6387. this.#pushOrReplaceState(position);
  6388. return;
  6389. }
  6390. if (this._destination.temporary) {
  6391. this.#pushOrReplaceState(position, true);
  6392. return;
  6393. }
  6394. if (this._destination.hash === position.hash) {
  6395. return;
  6396. }
  6397. if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) {
  6398. return;
  6399. }
  6400. let forceReplace = false;
  6401. if (this._destination.page >= position.first && this._destination.page <= position.page) {
  6402. if (this._destination.dest !== undefined || !this._destination.first) {
  6403. return;
  6404. }
  6405. forceReplace = true;
  6406. }
  6407. this.#pushOrReplaceState(position, forceReplace);
  6408. }
  6409. #isValidPage(val) {
  6410. return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount;
  6411. }
  6412. #isValidState(state, checkReload = false) {
  6413. if (!state) {
  6414. return false;
  6415. }
  6416. if (state.fingerprint !== this._fingerprint) {
  6417. if (checkReload) {
  6418. if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) {
  6419. return false;
  6420. }
  6421. const [perfEntry] = performance.getEntriesByType("navigation");
  6422. if (perfEntry?.type !== "reload") {
  6423. return false;
  6424. }
  6425. } else {
  6426. return false;
  6427. }
  6428. }
  6429. if (!Number.isInteger(state.uid) || state.uid < 0) {
  6430. return false;
  6431. }
  6432. if (state.destination === null || typeof state.destination !== "object") {
  6433. return false;
  6434. }
  6435. return true;
  6436. }
  6437. #updateInternalState(destination, uid, removeTemporary = false) {
  6438. if (this._updateViewareaTimeout) {
  6439. clearTimeout(this._updateViewareaTimeout);
  6440. this._updateViewareaTimeout = null;
  6441. }
  6442. if (removeTemporary && destination?.temporary) {
  6443. delete destination.temporary;
  6444. }
  6445. this._destination = destination;
  6446. this._uid = uid;
  6447. this._maxUid = Math.max(this._maxUid, uid);
  6448. this._numPositionUpdates = 0;
  6449. }
  6450. #parseCurrentHash(checkNameddest = false) {
  6451. const hash = unescape(getCurrentHash()).substring(1);
  6452. const params = parseQueryString(hash);
  6453. const nameddest = params.get("nameddest") || "";
  6454. let page = params.get("page") | 0;
  6455. if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) {
  6456. page = null;
  6457. }
  6458. return {
  6459. hash,
  6460. page,
  6461. rotation: this.linkService.rotation
  6462. };
  6463. }
  6464. #updateViewarea({
  6465. location
  6466. }) {
  6467. if (this._updateViewareaTimeout) {
  6468. clearTimeout(this._updateViewareaTimeout);
  6469. this._updateViewareaTimeout = null;
  6470. }
  6471. this._position = {
  6472. hash: location.pdfOpenParams.substring(1),
  6473. page: this.linkService.page,
  6474. first: location.pageNumber,
  6475. rotation: location.rotation
  6476. };
  6477. if (this._popStateInProgress) {
  6478. return;
  6479. }
  6480. if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) {
  6481. this._numPositionUpdates++;
  6482. }
  6483. if (UPDATE_VIEWAREA_TIMEOUT > 0) {
  6484. this._updateViewareaTimeout = setTimeout(() => {
  6485. if (!this._popStateInProgress) {
  6486. this.#tryPushCurrentPosition(true);
  6487. }
  6488. this._updateViewareaTimeout = null;
  6489. }, UPDATE_VIEWAREA_TIMEOUT);
  6490. }
  6491. }
  6492. #popState({
  6493. state
  6494. }) {
  6495. const newHash = getCurrentHash(),
  6496. hashChanged = this._currentHash !== newHash;
  6497. this._currentHash = newHash;
  6498. if (!state) {
  6499. this._uid++;
  6500. const {
  6501. hash,
  6502. page,
  6503. rotation
  6504. } = this.#parseCurrentHash();
  6505. this.#pushOrReplaceState({
  6506. hash,
  6507. page,
  6508. rotation
  6509. }, true);
  6510. return;
  6511. }
  6512. if (!this.#isValidState(state)) {
  6513. return;
  6514. }
  6515. this._popStateInProgress = true;
  6516. if (hashChanged) {
  6517. this._blockHashChange++;
  6518. waitOnEventOrTimeout({
  6519. target: window,
  6520. name: "hashchange",
  6521. delay: HASH_CHANGE_TIMEOUT
  6522. }).then(() => {
  6523. this._blockHashChange--;
  6524. });
  6525. }
  6526. const destination = state.destination;
  6527. this.#updateInternalState(destination, state.uid, true);
  6528. if (isValidRotation(destination.rotation)) {
  6529. this.linkService.rotation = destination.rotation;
  6530. }
  6531. if (destination.dest) {
  6532. this.linkService.goToDestination(destination.dest);
  6533. } else if (destination.hash) {
  6534. this.linkService.setHash(destination.hash);
  6535. } else if (destination.page) {
  6536. this.linkService.page = destination.page;
  6537. }
  6538. Promise.resolve().then(() => {
  6539. this._popStateInProgress = false;
  6540. });
  6541. }
  6542. #pageHide() {
  6543. if (!this._destination || this._destination.temporary) {
  6544. this.#tryPushCurrentPosition();
  6545. }
  6546. }
  6547. #bindEvents() {
  6548. if (this.#eventAbortController) {
  6549. return;
  6550. }
  6551. this.#eventAbortController = new AbortController();
  6552. const {
  6553. signal
  6554. } = this.#eventAbortController;
  6555. this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), {
  6556. signal
  6557. });
  6558. window.addEventListener("popstate", this.#popState.bind(this), {
  6559. signal
  6560. });
  6561. window.addEventListener("pagehide", this.#pageHide.bind(this), {
  6562. signal
  6563. });
  6564. }
  6565. #unbindEvents() {
  6566. this.#eventAbortController?.abort();
  6567. this.#eventAbortController = null;
  6568. }
  6569. }
  6570. function isDestHashesEqual(destHash, pushHash) {
  6571. if (typeof destHash !== "string" || typeof pushHash !== "string") {
  6572. return false;
  6573. }
  6574. if (destHash === pushHash) {
  6575. return true;
  6576. }
  6577. const nameddest = parseQueryString(destHash).get("nameddest");
  6578. if (nameddest === pushHash) {
  6579. return true;
  6580. }
  6581. return false;
  6582. }
  6583. function isDestArraysEqual(firstDest, secondDest) {
  6584. function isEntryEqual(first, second) {
  6585. if (typeof first !== typeof second) {
  6586. return false;
  6587. }
  6588. if (Array.isArray(first) || Array.isArray(second)) {
  6589. return false;
  6590. }
  6591. if (first !== null && typeof first === "object" && second !== null) {
  6592. if (Object.keys(first).length !== Object.keys(second).length) {
  6593. return false;
  6594. }
  6595. for (const key in first) {
  6596. if (!isEntryEqual(first[key], second[key])) {
  6597. return false;
  6598. }
  6599. }
  6600. return true;
  6601. }
  6602. return first === second || Number.isNaN(first) && Number.isNaN(second);
  6603. }
  6604. if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) {
  6605. return false;
  6606. }
  6607. if (firstDest.length !== secondDest.length) {
  6608. return false;
  6609. }
  6610. for (let i = 0, ii = firstDest.length; i < ii; i++) {
  6611. if (!isEntryEqual(firstDest[i], secondDest[i])) {
  6612. return false;
  6613. }
  6614. }
  6615. return true;
  6616. }
  6617. ;// ./web/pdf_layer_viewer.js
  6618. class PDFLayerViewer extends BaseTreeViewer {
  6619. constructor(options) {
  6620. super(options);
  6621. this.eventBus._on("optionalcontentconfigchanged", evt => {
  6622. this.#updateLayers(evt.promise);
  6623. });
  6624. this.eventBus._on("resetlayers", () => {
  6625. this.#updateLayers();
  6626. });
  6627. this.eventBus._on("togglelayerstree", this._toggleAllTreeItems.bind(this));
  6628. }
  6629. reset() {
  6630. super.reset();
  6631. this._optionalContentConfig = null;
  6632. this._optionalContentVisibility?.clear();
  6633. this._optionalContentVisibility = null;
  6634. }
  6635. _dispatchEvent(layersCount) {
  6636. this.eventBus.dispatch("layersloaded", {
  6637. source: this,
  6638. layersCount
  6639. });
  6640. }
  6641. _bindLink(element, {
  6642. groupId,
  6643. input
  6644. }) {
  6645. const setVisibility = () => {
  6646. const visible = input.checked;
  6647. this._optionalContentConfig.setVisibility(groupId, visible);
  6648. const cached = this._optionalContentVisibility.get(groupId);
  6649. if (cached) {
  6650. cached.visible = visible;
  6651. }
  6652. this.eventBus.dispatch("optionalcontentconfig", {
  6653. source: this,
  6654. promise: Promise.resolve(this._optionalContentConfig)
  6655. });
  6656. };
  6657. element.onclick = evt => {
  6658. if (evt.target === input) {
  6659. setVisibility();
  6660. return true;
  6661. } else if (evt.target !== element) {
  6662. return true;
  6663. }
  6664. input.checked = !input.checked;
  6665. setVisibility();
  6666. return false;
  6667. };
  6668. }
  6669. _setNestedName(element, {
  6670. name = null
  6671. }) {
  6672. if (typeof name === "string") {
  6673. element.textContent = this._normalizeTextContent(name);
  6674. return;
  6675. }
  6676. element.setAttribute("data-l10n-id", "pdfjs-additional-layers");
  6677. element.style.fontStyle = "italic";
  6678. this._l10n.translateOnce(element);
  6679. }
  6680. _addToggleButton(div, {
  6681. name = null
  6682. }) {
  6683. super._addToggleButton(div, name === null);
  6684. }
  6685. _toggleAllTreeItems() {
  6686. if (!this._optionalContentConfig) {
  6687. return;
  6688. }
  6689. super._toggleAllTreeItems();
  6690. }
  6691. render({
  6692. optionalContentConfig,
  6693. pdfDocument
  6694. }) {
  6695. if (this._optionalContentConfig) {
  6696. this.reset();
  6697. }
  6698. this._optionalContentConfig = optionalContentConfig || null;
  6699. this._pdfDocument = pdfDocument || null;
  6700. const groups = optionalContentConfig?.getOrder();
  6701. if (!groups) {
  6702. this._dispatchEvent(0);
  6703. return;
  6704. }
  6705. this._optionalContentVisibility = new Map();
  6706. const fragment = document.createDocumentFragment(),
  6707. queue = [{
  6708. parent: fragment,
  6709. groups
  6710. }];
  6711. let layersCount = 0,
  6712. hasAnyNesting = false;
  6713. while (queue.length > 0) {
  6714. const levelData = queue.shift();
  6715. for (const groupId of levelData.groups) {
  6716. const div = document.createElement("div");
  6717. div.className = "treeItem";
  6718. const element = document.createElement("a");
  6719. div.append(element);
  6720. if (typeof groupId === "object") {
  6721. hasAnyNesting = true;
  6722. this._addToggleButton(div, groupId);
  6723. this._setNestedName(element, groupId);
  6724. const itemsDiv = document.createElement("div");
  6725. itemsDiv.className = "treeItems";
  6726. div.append(itemsDiv);
  6727. queue.push({
  6728. parent: itemsDiv,
  6729. groups: groupId.order
  6730. });
  6731. } else {
  6732. const group = optionalContentConfig.getGroup(groupId);
  6733. const input = document.createElement("input");
  6734. this._bindLink(element, {
  6735. groupId,
  6736. input
  6737. });
  6738. input.type = "checkbox";
  6739. input.checked = group.visible;
  6740. this._optionalContentVisibility.set(groupId, {
  6741. input,
  6742. visible: input.checked
  6743. });
  6744. const label = document.createElement("label");
  6745. label.textContent = this._normalizeTextContent(group.name);
  6746. label.append(input);
  6747. element.append(label);
  6748. layersCount++;
  6749. }
  6750. levelData.parent.append(div);
  6751. }
  6752. }
  6753. this._finishRendering(fragment, layersCount, hasAnyNesting);
  6754. }
  6755. async #updateLayers(promise = null) {
  6756. if (!this._optionalContentConfig) {
  6757. return;
  6758. }
  6759. const pdfDocument = this._pdfDocument;
  6760. const optionalContentConfig = await (promise || pdfDocument.getOptionalContentConfig({
  6761. intent: "display"
  6762. }));
  6763. if (pdfDocument !== this._pdfDocument) {
  6764. return;
  6765. }
  6766. if (promise) {
  6767. for (const [groupId, cached] of this._optionalContentVisibility) {
  6768. const group = optionalContentConfig.getGroup(groupId);
  6769. if (group && cached.visible !== group.visible) {
  6770. cached.input.checked = cached.visible = !cached.visible;
  6771. }
  6772. }
  6773. return;
  6774. }
  6775. this.eventBus.dispatch("optionalcontentconfig", {
  6776. source: this,
  6777. promise: Promise.resolve(optionalContentConfig)
  6778. });
  6779. this.render({
  6780. optionalContentConfig,
  6781. pdfDocument: this._pdfDocument
  6782. });
  6783. }
  6784. }
  6785. ;// ./web/pdf_outline_viewer.js
  6786. class PDFOutlineViewer extends BaseTreeViewer {
  6787. constructor(options) {
  6788. super(options);
  6789. this.linkService = options.linkService;
  6790. this.downloadManager = options.downloadManager;
  6791. this.eventBus._on("toggleoutlinetree", this._toggleAllTreeItems.bind(this));
  6792. this.eventBus._on("currentoutlineitem", this._currentOutlineItem.bind(this));
  6793. this.eventBus._on("pagechanging", evt => {
  6794. this._currentPageNumber = evt.pageNumber;
  6795. });
  6796. this.eventBus._on("pagesloaded", evt => {
  6797. this._isPagesLoaded = !!evt.pagesCount;
  6798. this._currentOutlineItemCapability?.resolve(this._isPagesLoaded);
  6799. });
  6800. this.eventBus._on("sidebarviewchanged", evt => {
  6801. this._sidebarView = evt.view;
  6802. });
  6803. }
  6804. reset() {
  6805. super.reset();
  6806. this._outline = null;
  6807. this._pageNumberToDestHashCapability = null;
  6808. this._currentPageNumber = 1;
  6809. this._isPagesLoaded = null;
  6810. this._currentOutlineItemCapability?.resolve(false);
  6811. this._currentOutlineItemCapability = null;
  6812. }
  6813. _dispatchEvent(outlineCount) {
  6814. this._currentOutlineItemCapability = Promise.withResolvers();
  6815. if (outlineCount === 0 || this._pdfDocument?.loadingParams.disableAutoFetch) {
  6816. this._currentOutlineItemCapability.resolve(false);
  6817. } else if (this._isPagesLoaded !== null) {
  6818. this._currentOutlineItemCapability.resolve(this._isPagesLoaded);
  6819. }
  6820. this.eventBus.dispatch("outlineloaded", {
  6821. source: this,
  6822. outlineCount,
  6823. currentOutlineItemPromise: this._currentOutlineItemCapability.promise
  6824. });
  6825. }
  6826. _bindLink(element, {
  6827. url,
  6828. newWindow,
  6829. action,
  6830. attachment,
  6831. dest,
  6832. setOCGState
  6833. }) {
  6834. const {
  6835. linkService
  6836. } = this;
  6837. if (url) {
  6838. linkService.addLinkAttributes(element, url, newWindow);
  6839. return;
  6840. }
  6841. if (action) {
  6842. element.href = linkService.getAnchorUrl("");
  6843. element.onclick = () => {
  6844. linkService.executeNamedAction(action);
  6845. return false;
  6846. };
  6847. return;
  6848. }
  6849. if (attachment) {
  6850. element.href = linkService.getAnchorUrl("");
  6851. element.onclick = () => {
  6852. this.downloadManager.openOrDownloadData(attachment.content, attachment.filename);
  6853. return false;
  6854. };
  6855. return;
  6856. }
  6857. if (setOCGState) {
  6858. element.href = linkService.getAnchorUrl("");
  6859. element.onclick = () => {
  6860. linkService.executeSetOCGState(setOCGState);
  6861. return false;
  6862. };
  6863. return;
  6864. }
  6865. element.href = linkService.getDestinationHash(dest);
  6866. element.onclick = evt => {
  6867. this._updateCurrentTreeItem(evt.target.parentNode);
  6868. if (dest) {
  6869. linkService.goToDestination(dest);
  6870. }
  6871. return false;
  6872. };
  6873. }
  6874. _setStyles(element, {
  6875. bold,
  6876. italic
  6877. }) {
  6878. if (bold) {
  6879. element.style.fontWeight = "bold";
  6880. }
  6881. if (italic) {
  6882. element.style.fontStyle = "italic";
  6883. }
  6884. }
  6885. _addToggleButton(div, {
  6886. count,
  6887. items
  6888. }) {
  6889. let hidden = false;
  6890. if (count < 0) {
  6891. let totalCount = items.length;
  6892. if (totalCount > 0) {
  6893. const queue = [...items];
  6894. while (queue.length > 0) {
  6895. const {
  6896. count: nestedCount,
  6897. items: nestedItems
  6898. } = queue.shift();
  6899. if (nestedCount > 0 && nestedItems.length > 0) {
  6900. totalCount += nestedItems.length;
  6901. queue.push(...nestedItems);
  6902. }
  6903. }
  6904. }
  6905. if (Math.abs(count) === totalCount) {
  6906. hidden = true;
  6907. }
  6908. }
  6909. super._addToggleButton(div, hidden);
  6910. }
  6911. _toggleAllTreeItems() {
  6912. if (!this._outline) {
  6913. return;
  6914. }
  6915. super._toggleAllTreeItems();
  6916. }
  6917. render({
  6918. outline,
  6919. pdfDocument
  6920. }) {
  6921. if (this._outline) {
  6922. this.reset();
  6923. }
  6924. this._outline = outline || null;
  6925. this._pdfDocument = pdfDocument || null;
  6926. if (!outline) {
  6927. this._dispatchEvent(0);
  6928. return;
  6929. }
  6930. const fragment = document.createDocumentFragment();
  6931. const queue = [{
  6932. parent: fragment,
  6933. items: outline
  6934. }];
  6935. let outlineCount = 0,
  6936. hasAnyNesting = false;
  6937. while (queue.length > 0) {
  6938. const levelData = queue.shift();
  6939. for (const item of levelData.items) {
  6940. const div = document.createElement("div");
  6941. div.className = "treeItem";
  6942. const element = document.createElement("a");
  6943. this._bindLink(element, item);
  6944. this._setStyles(element, item);
  6945. element.textContent = this._normalizeTextContent(item.title);
  6946. div.append(element);
  6947. if (item.items.length > 0) {
  6948. hasAnyNesting = true;
  6949. this._addToggleButton(div, item);
  6950. const itemsDiv = document.createElement("div");
  6951. itemsDiv.className = "treeItems";
  6952. div.append(itemsDiv);
  6953. queue.push({
  6954. parent: itemsDiv,
  6955. items: item.items
  6956. });
  6957. }
  6958. levelData.parent.append(div);
  6959. outlineCount++;
  6960. }
  6961. }
  6962. this._finishRendering(fragment, outlineCount, hasAnyNesting);
  6963. }
  6964. async _currentOutlineItem() {
  6965. if (!this._isPagesLoaded) {
  6966. throw new Error("_currentOutlineItem: All pages have not been loaded.");
  6967. }
  6968. if (!this._outline || !this._pdfDocument) {
  6969. return;
  6970. }
  6971. const pageNumberToDestHash = await this._getPageNumberToDestHash(this._pdfDocument);
  6972. if (!pageNumberToDestHash) {
  6973. return;
  6974. }
  6975. this._updateCurrentTreeItem(null);
  6976. if (this._sidebarView !== SidebarView.OUTLINE) {
  6977. return;
  6978. }
  6979. for (let i = this._currentPageNumber; i > 0; i--) {
  6980. const destHash = pageNumberToDestHash.get(i);
  6981. if (!destHash) {
  6982. continue;
  6983. }
  6984. const linkElement = this.container.querySelector(`a[href="${destHash}"]`);
  6985. if (!linkElement) {
  6986. continue;
  6987. }
  6988. this._scrollToCurrentTreeItem(linkElement.parentNode);
  6989. break;
  6990. }
  6991. }
  6992. async _getPageNumberToDestHash(pdfDocument) {
  6993. if (this._pageNumberToDestHashCapability) {
  6994. return this._pageNumberToDestHashCapability.promise;
  6995. }
  6996. this._pageNumberToDestHashCapability = Promise.withResolvers();
  6997. const pageNumberToDestHash = new Map(),
  6998. pageNumberNesting = new Map();
  6999. const queue = [{
  7000. nesting: 0,
  7001. items: this._outline
  7002. }];
  7003. while (queue.length > 0) {
  7004. const levelData = queue.shift(),
  7005. currentNesting = levelData.nesting;
  7006. for (const {
  7007. dest,
  7008. items
  7009. } of levelData.items) {
  7010. let explicitDest, pageNumber;
  7011. if (typeof dest === "string") {
  7012. explicitDest = await pdfDocument.getDestination(dest);
  7013. if (pdfDocument !== this._pdfDocument) {
  7014. return null;
  7015. }
  7016. } else {
  7017. explicitDest = dest;
  7018. }
  7019. if (Array.isArray(explicitDest)) {
  7020. const [destRef] = explicitDest;
  7021. if (destRef && typeof destRef === "object") {
  7022. pageNumber = pdfDocument.cachedPageNumber(destRef);
  7023. } else if (Number.isInteger(destRef)) {
  7024. pageNumber = destRef + 1;
  7025. }
  7026. if (Number.isInteger(pageNumber) && (!pageNumberToDestHash.has(pageNumber) || currentNesting > pageNumberNesting.get(pageNumber))) {
  7027. const destHash = this.linkService.getDestinationHash(dest);
  7028. pageNumberToDestHash.set(pageNumber, destHash);
  7029. pageNumberNesting.set(pageNumber, currentNesting);
  7030. }
  7031. }
  7032. if (items.length > 0) {
  7033. queue.push({
  7034. nesting: currentNesting + 1,
  7035. items
  7036. });
  7037. }
  7038. }
  7039. }
  7040. this._pageNumberToDestHashCapability.resolve(pageNumberToDestHash.size > 0 ? pageNumberToDestHash : null);
  7041. return this._pageNumberToDestHashCapability.promise;
  7042. }
  7043. }
  7044. ;// ./web/pdf_presentation_mode.js
  7045. const DELAY_BEFORE_HIDING_CONTROLS = 3000;
  7046. const ACTIVE_SELECTOR = "pdfPresentationMode";
  7047. const CONTROLS_SELECTOR = "pdfPresentationModeControls";
  7048. const MOUSE_SCROLL_COOLDOWN_TIME = 50;
  7049. const PAGE_SWITCH_THRESHOLD = 0.1;
  7050. const SWIPE_MIN_DISTANCE_THRESHOLD = 50;
  7051. const SWIPE_ANGLE_THRESHOLD = Math.PI / 6;
  7052. class PDFPresentationMode {
  7053. #state = PresentationModeState.UNKNOWN;
  7054. #args = null;
  7055. #fullscreenChangeAbortController = null;
  7056. #windowAbortController = null;
  7057. constructor({
  7058. container,
  7059. pdfViewer,
  7060. eventBus
  7061. }) {
  7062. this.container = container;
  7063. this.pdfViewer = pdfViewer;
  7064. this.eventBus = eventBus;
  7065. this.contextMenuOpen = false;
  7066. this.mouseScrollTimeStamp = 0;
  7067. this.mouseScrollDelta = 0;
  7068. this.touchSwipeState = null;
  7069. }
  7070. async request() {
  7071. const {
  7072. container,
  7073. pdfViewer
  7074. } = this;
  7075. if (this.active || !pdfViewer.pagesCount || !container.requestFullscreen) {
  7076. return false;
  7077. }
  7078. this.#addFullscreenChangeListeners();
  7079. this.#notifyStateChange(PresentationModeState.CHANGING);
  7080. const promise = container.requestFullscreen();
  7081. this.#args = {
  7082. pageNumber: pdfViewer.currentPageNumber,
  7083. scaleValue: pdfViewer.currentScaleValue,
  7084. scrollMode: pdfViewer.scrollMode,
  7085. spreadMode: null,
  7086. annotationEditorMode: null
  7087. };
  7088. if (pdfViewer.spreadMode !== SpreadMode.NONE && !(pdfViewer.pageViewsReady && pdfViewer.hasEqualPageSizes)) {
  7089. console.warn("Ignoring Spread modes when entering PresentationMode, " + "since the document may contain varying page sizes.");
  7090. this.#args.spreadMode = pdfViewer.spreadMode;
  7091. }
  7092. if (pdfViewer.annotationEditorMode !== AnnotationEditorType.DISABLE) {
  7093. this.#args.annotationEditorMode = pdfViewer.annotationEditorMode;
  7094. }
  7095. try {
  7096. await promise;
  7097. pdfViewer.focus();
  7098. return true;
  7099. } catch {
  7100. this.#removeFullscreenChangeListeners();
  7101. this.#notifyStateChange(PresentationModeState.NORMAL);
  7102. }
  7103. return false;
  7104. }
  7105. get active() {
  7106. return this.#state === PresentationModeState.CHANGING || this.#state === PresentationModeState.FULLSCREEN;
  7107. }
  7108. #mouseWheel(evt) {
  7109. if (!this.active) {
  7110. return;
  7111. }
  7112. evt.preventDefault();
  7113. const delta = normalizeWheelEventDelta(evt);
  7114. const currentTime = Date.now();
  7115. const storedTime = this.mouseScrollTimeStamp;
  7116. if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
  7117. return;
  7118. }
  7119. if (this.mouseScrollDelta > 0 && delta < 0 || this.mouseScrollDelta < 0 && delta > 0) {
  7120. this.#resetMouseScrollState();
  7121. }
  7122. this.mouseScrollDelta += delta;
  7123. if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) {
  7124. const totalDelta = this.mouseScrollDelta;
  7125. this.#resetMouseScrollState();
  7126. const success = totalDelta > 0 ? this.pdfViewer.previousPage() : this.pdfViewer.nextPage();
  7127. if (success) {
  7128. this.mouseScrollTimeStamp = currentTime;
  7129. }
  7130. }
  7131. }
  7132. #notifyStateChange(state) {
  7133. this.#state = state;
  7134. this.eventBus.dispatch("presentationmodechanged", {
  7135. source: this,
  7136. state
  7137. });
  7138. }
  7139. #enter() {
  7140. this.#notifyStateChange(PresentationModeState.FULLSCREEN);
  7141. this.container.classList.add(ACTIVE_SELECTOR);
  7142. setTimeout(() => {
  7143. this.pdfViewer.scrollMode = ScrollMode.PAGE;
  7144. if (this.#args.spreadMode !== null) {
  7145. this.pdfViewer.spreadMode = SpreadMode.NONE;
  7146. }
  7147. this.pdfViewer.currentPageNumber = this.#args.pageNumber;
  7148. this.pdfViewer.currentScaleValue = "page-fit";
  7149. if (this.#args.annotationEditorMode !== null) {
  7150. this.pdfViewer.annotationEditorMode = {
  7151. mode: AnnotationEditorType.NONE
  7152. };
  7153. }
  7154. }, 0);
  7155. this.#addWindowListeners();
  7156. this.#showControls();
  7157. this.contextMenuOpen = false;
  7158. document.getSelection().empty();
  7159. }
  7160. #exit() {
  7161. const pageNumber = this.pdfViewer.currentPageNumber;
  7162. this.container.classList.remove(ACTIVE_SELECTOR);
  7163. setTimeout(() => {
  7164. this.#removeFullscreenChangeListeners();
  7165. this.#notifyStateChange(PresentationModeState.NORMAL);
  7166. this.pdfViewer.scrollMode = this.#args.scrollMode;
  7167. if (this.#args.spreadMode !== null) {
  7168. this.pdfViewer.spreadMode = this.#args.spreadMode;
  7169. }
  7170. this.pdfViewer.currentScaleValue = this.#args.scaleValue;
  7171. this.pdfViewer.currentPageNumber = pageNumber;
  7172. if (this.#args.annotationEditorMode !== null) {
  7173. this.pdfViewer.annotationEditorMode = {
  7174. mode: this.#args.annotationEditorMode
  7175. };
  7176. }
  7177. this.#args = null;
  7178. }, 0);
  7179. this.#removeWindowListeners();
  7180. this.#hideControls();
  7181. this.#resetMouseScrollState();
  7182. this.contextMenuOpen = false;
  7183. }
  7184. #mouseDown(evt) {
  7185. if (this.contextMenuOpen) {
  7186. this.contextMenuOpen = false;
  7187. evt.preventDefault();
  7188. return;
  7189. }
  7190. if (evt.button !== 0) {
  7191. return;
  7192. }
  7193. if (evt.target.href && evt.target.parentNode?.hasAttribute("data-internal-link")) {
  7194. return;
  7195. }
  7196. evt.preventDefault();
  7197. if (evt.shiftKey) {
  7198. this.pdfViewer.previousPage();
  7199. } else {
  7200. this.pdfViewer.nextPage();
  7201. }
  7202. }
  7203. #contextMenu() {
  7204. this.contextMenuOpen = true;
  7205. }
  7206. #showControls() {
  7207. if (this.controlsTimeout) {
  7208. clearTimeout(this.controlsTimeout);
  7209. } else {
  7210. this.container.classList.add(CONTROLS_SELECTOR);
  7211. }
  7212. this.controlsTimeout = setTimeout(() => {
  7213. this.container.classList.remove(CONTROLS_SELECTOR);
  7214. delete this.controlsTimeout;
  7215. }, DELAY_BEFORE_HIDING_CONTROLS);
  7216. }
  7217. #hideControls() {
  7218. if (!this.controlsTimeout) {
  7219. return;
  7220. }
  7221. clearTimeout(this.controlsTimeout);
  7222. this.container.classList.remove(CONTROLS_SELECTOR);
  7223. delete this.controlsTimeout;
  7224. }
  7225. #resetMouseScrollState() {
  7226. this.mouseScrollTimeStamp = 0;
  7227. this.mouseScrollDelta = 0;
  7228. }
  7229. #touchSwipe(evt) {
  7230. if (!this.active) {
  7231. return;
  7232. }
  7233. if (evt.touches.length > 1) {
  7234. this.touchSwipeState = null;
  7235. return;
  7236. }
  7237. switch (evt.type) {
  7238. case "touchstart":
  7239. this.touchSwipeState = {
  7240. startX: evt.touches[0].pageX,
  7241. startY: evt.touches[0].pageY,
  7242. endX: evt.touches[0].pageX,
  7243. endY: evt.touches[0].pageY
  7244. };
  7245. break;
  7246. case "touchmove":
  7247. if (this.touchSwipeState === null) {
  7248. return;
  7249. }
  7250. this.touchSwipeState.endX = evt.touches[0].pageX;
  7251. this.touchSwipeState.endY = evt.touches[0].pageY;
  7252. evt.preventDefault();
  7253. break;
  7254. case "touchend":
  7255. if (this.touchSwipeState === null) {
  7256. return;
  7257. }
  7258. let delta = 0;
  7259. const dx = this.touchSwipeState.endX - this.touchSwipeState.startX;
  7260. const dy = this.touchSwipeState.endY - this.touchSwipeState.startY;
  7261. const absAngle = Math.abs(Math.atan2(dy, dx));
  7262. if (Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && (absAngle <= SWIPE_ANGLE_THRESHOLD || absAngle >= Math.PI - SWIPE_ANGLE_THRESHOLD)) {
  7263. delta = dx;
  7264. } else if (Math.abs(dy) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(absAngle - Math.PI / 2) <= SWIPE_ANGLE_THRESHOLD) {
  7265. delta = dy;
  7266. }
  7267. if (delta > 0) {
  7268. this.pdfViewer.previousPage();
  7269. } else if (delta < 0) {
  7270. this.pdfViewer.nextPage();
  7271. }
  7272. break;
  7273. }
  7274. }
  7275. #addWindowListeners() {
  7276. if (this.#windowAbortController) {
  7277. return;
  7278. }
  7279. this.#windowAbortController = new AbortController();
  7280. const {
  7281. signal
  7282. } = this.#windowAbortController;
  7283. const touchSwipeBind = this.#touchSwipe.bind(this);
  7284. window.addEventListener("mousemove", this.#showControls.bind(this), {
  7285. signal
  7286. });
  7287. window.addEventListener("mousedown", this.#mouseDown.bind(this), {
  7288. signal
  7289. });
  7290. window.addEventListener("wheel", this.#mouseWheel.bind(this), {
  7291. passive: false,
  7292. signal
  7293. });
  7294. window.addEventListener("keydown", this.#resetMouseScrollState.bind(this), {
  7295. signal
  7296. });
  7297. window.addEventListener("contextmenu", this.#contextMenu.bind(this), {
  7298. signal
  7299. });
  7300. window.addEventListener("touchstart", touchSwipeBind, {
  7301. signal
  7302. });
  7303. window.addEventListener("touchmove", touchSwipeBind, {
  7304. signal
  7305. });
  7306. window.addEventListener("touchend", touchSwipeBind, {
  7307. signal
  7308. });
  7309. }
  7310. #removeWindowListeners() {
  7311. this.#windowAbortController?.abort();
  7312. this.#windowAbortController = null;
  7313. }
  7314. #addFullscreenChangeListeners() {
  7315. if (this.#fullscreenChangeAbortController) {
  7316. return;
  7317. }
  7318. this.#fullscreenChangeAbortController = new AbortController();
  7319. window.addEventListener("fullscreenchange", () => {
  7320. if (document.fullscreenElement) {
  7321. this.#enter();
  7322. } else {
  7323. this.#exit();
  7324. }
  7325. }, {
  7326. signal: this.#fullscreenChangeAbortController.signal
  7327. });
  7328. }
  7329. #removeFullscreenChangeListeners() {
  7330. this.#fullscreenChangeAbortController?.abort();
  7331. this.#fullscreenChangeAbortController = null;
  7332. }
  7333. }
  7334. ;// ./web/xfa_layer_builder.js
  7335. class XfaLayerBuilder {
  7336. constructor({
  7337. pdfPage,
  7338. annotationStorage = null,
  7339. linkService,
  7340. xfaHtml = null
  7341. }) {
  7342. this.pdfPage = pdfPage;
  7343. this.annotationStorage = annotationStorage;
  7344. this.linkService = linkService;
  7345. this.xfaHtml = xfaHtml;
  7346. this.div = null;
  7347. this._cancelled = false;
  7348. }
  7349. async render({
  7350. viewport,
  7351. intent = "display"
  7352. }) {
  7353. if (intent === "print") {
  7354. const parameters = {
  7355. viewport: viewport.clone({
  7356. dontFlip: true
  7357. }),
  7358. div: this.div,
  7359. xfaHtml: this.xfaHtml,
  7360. annotationStorage: this.annotationStorage,
  7361. linkService: this.linkService,
  7362. intent
  7363. };
  7364. this.div = document.createElement("div");
  7365. parameters.div = this.div;
  7366. return XfaLayer.render(parameters);
  7367. }
  7368. const xfaHtml = await this.pdfPage.getXfa();
  7369. if (this._cancelled || !xfaHtml) {
  7370. return {
  7371. textDivs: []
  7372. };
  7373. }
  7374. const parameters = {
  7375. viewport: viewport.clone({
  7376. dontFlip: true
  7377. }),
  7378. div: this.div,
  7379. xfaHtml,
  7380. annotationStorage: this.annotationStorage,
  7381. linkService: this.linkService,
  7382. intent
  7383. };
  7384. if (this.div) {
  7385. return XfaLayer.update(parameters);
  7386. }
  7387. this.div = document.createElement("div");
  7388. parameters.div = this.div;
  7389. return XfaLayer.render(parameters);
  7390. }
  7391. cancel() {
  7392. this._cancelled = true;
  7393. }
  7394. hide() {
  7395. if (!this.div) {
  7396. return;
  7397. }
  7398. this.div.hidden = true;
  7399. }
  7400. }
  7401. ;// ./web/print_utils.js
  7402. function getXfaHtmlForPrinting(printContainer, pdfDocument) {
  7403. const xfaHtml = pdfDocument.allXfaHtml;
  7404. const linkService = new SimpleLinkService();
  7405. const scale = Math.round(PixelsPerInch.PDF_TO_CSS_UNITS * 100) / 100;
  7406. for (const xfaPage of xfaHtml.children) {
  7407. const page = document.createElement("div");
  7408. page.className = "xfaPrintedPage";
  7409. printContainer.append(page);
  7410. const builder = new XfaLayerBuilder({
  7411. pdfPage: null,
  7412. annotationStorage: pdfDocument.annotationStorage,
  7413. linkService,
  7414. xfaHtml: xfaPage
  7415. });
  7416. const viewport = getXfaPageViewport(xfaPage, {
  7417. scale
  7418. });
  7419. builder.render({
  7420. viewport,
  7421. intent: "print"
  7422. });
  7423. page.append(builder.div);
  7424. }
  7425. }
  7426. ;// ./web/pdf_print_service.js
  7427. let activeService = null;
  7428. let dialog = null;
  7429. let overlayManager = null;
  7430. let viewerApp = {
  7431. initialized: false
  7432. };
  7433. function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printResolution, optionalContentConfigPromise, printAnnotationStoragePromise) {
  7434. const scratchCanvas = activeService.scratchCanvas;
  7435. const PRINT_UNITS = printResolution / PixelsPerInch.PDF;
  7436. scratchCanvas.width = Math.floor(size.width * PRINT_UNITS);
  7437. scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);
  7438. const ctx = scratchCanvas.getContext("2d");
  7439. ctx.save();
  7440. ctx.fillStyle = "rgb(255, 255, 255)";
  7441. ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
  7442. ctx.restore();
  7443. return Promise.all([pdfDocument.getPage(pageNumber), printAnnotationStoragePromise]).then(function ([pdfPage, printAnnotationStorage]) {
  7444. const renderContext = {
  7445. canvasContext: ctx,
  7446. transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0],
  7447. viewport: pdfPage.getViewport({
  7448. scale: 1,
  7449. rotation: size.rotation
  7450. }),
  7451. intent: "print",
  7452. annotationMode: AnnotationMode.ENABLE_STORAGE,
  7453. optionalContentConfigPromise,
  7454. printAnnotationStorage
  7455. };
  7456. const renderTask = pdfPage.render(renderContext);
  7457. return renderTask.promise.catch(reason => {
  7458. if (!(reason instanceof RenderingCancelledException)) {
  7459. console.error(reason);
  7460. }
  7461. throw reason;
  7462. });
  7463. });
  7464. }
  7465. class PDFPrintService {
  7466. constructor({
  7467. pdfDocument,
  7468. pagesOverview,
  7469. printContainer,
  7470. printResolution,
  7471. printAnnotationStoragePromise = null
  7472. }) {
  7473. this.pdfDocument = pdfDocument;
  7474. this.pagesOverview = pagesOverview;
  7475. this.printContainer = printContainer;
  7476. this._printResolution = printResolution || 150;
  7477. this._optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({
  7478. intent: "print"
  7479. });
  7480. this._printAnnotationStoragePromise = printAnnotationStoragePromise || Promise.resolve();
  7481. this.currentPage = -1;
  7482. this.scratchCanvas = document.createElement("canvas");
  7483. }
  7484. layout() {
  7485. this.throwIfInactive();
  7486. const body = document.querySelector("body");
  7487. body.setAttribute("data-pdfjsprinting", true);
  7488. const {
  7489. width,
  7490. height
  7491. } = this.pagesOverview[0];
  7492. const hasEqualPageSizes = this.pagesOverview.every(size => size.width === width && size.height === height);
  7493. if (!hasEqualPageSizes) {
  7494. console.warn("Not all pages have the same size. The printed result may be incorrect!");
  7495. }
  7496. this.pageStyleSheet = document.createElement("style");
  7497. this.pageStyleSheet.textContent = `@page { size: ${width}pt ${height}pt;}`;
  7498. body.append(this.pageStyleSheet);
  7499. }
  7500. destroy() {
  7501. if (activeService !== this) {
  7502. return;
  7503. }
  7504. this.printContainer.textContent = "";
  7505. const body = document.querySelector("body");
  7506. body.removeAttribute("data-pdfjsprinting");
  7507. if (this.pageStyleSheet) {
  7508. this.pageStyleSheet.remove();
  7509. this.pageStyleSheet = null;
  7510. }
  7511. this.scratchCanvas.width = this.scratchCanvas.height = 0;
  7512. this.scratchCanvas = null;
  7513. activeService = null;
  7514. ensureOverlay().then(function () {
  7515. overlayManager.closeIfActive(dialog);
  7516. });
  7517. }
  7518. renderPages() {
  7519. if (this.pdfDocument.isPureXfa) {
  7520. getXfaHtmlForPrinting(this.printContainer, this.pdfDocument);
  7521. return Promise.resolve();
  7522. }
  7523. const pageCount = this.pagesOverview.length;
  7524. const renderNextPage = (resolve, reject) => {
  7525. this.throwIfInactive();
  7526. if (++this.currentPage >= pageCount) {
  7527. renderProgress(pageCount, pageCount);
  7528. resolve();
  7529. return;
  7530. }
  7531. const index = this.currentPage;
  7532. renderProgress(index, pageCount);
  7533. renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index], this._printResolution, this._optionalContentConfigPromise, this._printAnnotationStoragePromise).then(this.useRenderedPage.bind(this)).then(function () {
  7534. renderNextPage(resolve, reject);
  7535. }, reject);
  7536. };
  7537. return new Promise(renderNextPage);
  7538. }
  7539. useRenderedPage() {
  7540. this.throwIfInactive();
  7541. const img = document.createElement("img");
  7542. this.scratchCanvas.toBlob(blob => {
  7543. img.src = URL.createObjectURL(blob);
  7544. });
  7545. const wrapper = document.createElement("div");
  7546. wrapper.className = "printedPage";
  7547. wrapper.append(img);
  7548. this.printContainer.append(wrapper);
  7549. const {
  7550. promise,
  7551. resolve,
  7552. reject
  7553. } = Promise.withResolvers();
  7554. img.onload = resolve;
  7555. img.onerror = reject;
  7556. promise.catch(() => {}).then(() => {
  7557. URL.revokeObjectURL(img.src);
  7558. });
  7559. return promise;
  7560. }
  7561. performPrint() {
  7562. this.throwIfInactive();
  7563. return new Promise(resolve => {
  7564. setTimeout(() => {
  7565. if (!this.active) {
  7566. resolve();
  7567. return;
  7568. }
  7569. print.call(window);
  7570. setTimeout(resolve, 20);
  7571. }, 0);
  7572. });
  7573. }
  7574. get active() {
  7575. return this === activeService;
  7576. }
  7577. throwIfInactive() {
  7578. if (!this.active) {
  7579. throw new Error("This print request was cancelled or completed.");
  7580. }
  7581. }
  7582. }
  7583. const print = window.print;
  7584. window.print = function () {
  7585. if (activeService) {
  7586. console.warn("Ignored window.print() because of a pending print job.");
  7587. return;
  7588. }
  7589. ensureOverlay().then(function () {
  7590. if (activeService) {
  7591. overlayManager.open(dialog);
  7592. }
  7593. });
  7594. try {
  7595. dispatchEvent("beforeprint");
  7596. } finally {
  7597. if (!activeService) {
  7598. console.error("Expected print service to be initialized.");
  7599. ensureOverlay().then(function () {
  7600. overlayManager.closeIfActive(dialog);
  7601. });
  7602. } else {
  7603. const activeServiceOnEntry = activeService;
  7604. activeService.renderPages().then(() => activeServiceOnEntry.performPrint()).catch(() => {}).then(() => {
  7605. if (activeServiceOnEntry.active) {
  7606. abort();
  7607. }
  7608. });
  7609. }
  7610. }
  7611. };
  7612. function dispatchEvent(eventType) {
  7613. const event = new CustomEvent(eventType, {
  7614. bubbles: false,
  7615. cancelable: false,
  7616. detail: "custom"
  7617. });
  7618. window.dispatchEvent(event);
  7619. }
  7620. function abort() {
  7621. if (activeService) {
  7622. activeService.destroy();
  7623. dispatchEvent("afterprint");
  7624. }
  7625. }
  7626. function renderProgress(index, total) {
  7627. dialog ||= document.getElementById("printServiceDialog");
  7628. const progress = Math.round(100 * index / total);
  7629. const progressBar = dialog.querySelector("progress");
  7630. const progressPerc = dialog.querySelector(".relative-progress");
  7631. progressBar.value = progress;
  7632. progressPerc.setAttribute("data-l10n-args", JSON.stringify({
  7633. progress
  7634. }));
  7635. }
  7636. window.addEventListener("keydown", function (event) {
  7637. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  7638. window.print();
  7639. event.preventDefault();
  7640. event.stopImmediatePropagation();
  7641. }
  7642. }, true);
  7643. if ("onbeforeprint" in window) {
  7644. const stopPropagationIfNeeded = function (event) {
  7645. if (event.detail !== "custom") {
  7646. event.stopImmediatePropagation();
  7647. }
  7648. };
  7649. window.addEventListener("beforeprint", stopPropagationIfNeeded);
  7650. window.addEventListener("afterprint", stopPropagationIfNeeded);
  7651. }
  7652. let overlayPromise;
  7653. function ensureOverlay() {
  7654. if (!overlayPromise) {
  7655. overlayManager = viewerApp.overlayManager;
  7656. if (!overlayManager) {
  7657. throw new Error("The overlay manager has not yet been initialized.");
  7658. }
  7659. dialog ||= document.getElementById("printServiceDialog");
  7660. overlayPromise = overlayManager.register(dialog, true);
  7661. document.getElementById("printCancel").onclick = abort;
  7662. dialog.addEventListener("close", abort);
  7663. }
  7664. return overlayPromise;
  7665. }
  7666. class PDFPrintServiceFactory {
  7667. static initGlobals(app) {
  7668. viewerApp = app;
  7669. }
  7670. static get supportsPrinting() {
  7671. return shadow(this, "supportsPrinting", true);
  7672. }
  7673. static createPrintService(params) {
  7674. if (activeService) {
  7675. throw new Error("The print service is created and active.");
  7676. }
  7677. return activeService = new PDFPrintService(params);
  7678. }
  7679. }
  7680. ;// ./web/pdf_rendering_queue.js
  7681. const CLEANUP_TIMEOUT = 30000;
  7682. class PDFRenderingQueue {
  7683. constructor() {
  7684. this.pdfViewer = null;
  7685. this.pdfThumbnailViewer = null;
  7686. this.onIdle = null;
  7687. this.highestPriorityPage = null;
  7688. this.idleTimeout = null;
  7689. this.printing = false;
  7690. this.isThumbnailViewEnabled = false;
  7691. Object.defineProperty(this, "hasViewer", {
  7692. value: () => !!this.pdfViewer
  7693. });
  7694. }
  7695. setViewer(pdfViewer) {
  7696. this.pdfViewer = pdfViewer;
  7697. }
  7698. setThumbnailViewer(pdfThumbnailViewer) {
  7699. this.pdfThumbnailViewer = pdfThumbnailViewer;
  7700. }
  7701. isHighestPriority(view) {
  7702. return this.highestPriorityPage === view.renderingId;
  7703. }
  7704. renderHighestPriority(currentlyVisiblePages) {
  7705. if (this.idleTimeout) {
  7706. clearTimeout(this.idleTimeout);
  7707. this.idleTimeout = null;
  7708. }
  7709. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  7710. return;
  7711. }
  7712. if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) {
  7713. return;
  7714. }
  7715. if (this.printing) {
  7716. return;
  7717. }
  7718. if (this.onIdle) {
  7719. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  7720. }
  7721. }
  7722. getHighestPriority(visible, views, scrolledDown, preRenderExtra = false, ignoreDetailViews = false) {
  7723. const visibleViews = visible.views,
  7724. numVisible = visibleViews.length;
  7725. if (numVisible === 0) {
  7726. return null;
  7727. }
  7728. for (let i = 0; i < numVisible; i++) {
  7729. const view = visibleViews[i].view;
  7730. if (!this.isViewFinished(view)) {
  7731. return view;
  7732. }
  7733. }
  7734. if (!ignoreDetailViews) {
  7735. for (let i = 0; i < numVisible; i++) {
  7736. const {
  7737. detailView
  7738. } = visibleViews[i].view;
  7739. if (detailView && !this.isViewFinished(detailView)) {
  7740. return detailView;
  7741. }
  7742. }
  7743. }
  7744. const firstId = visible.first.id,
  7745. lastId = visible.last.id;
  7746. if (lastId - firstId + 1 > numVisible) {
  7747. const visibleIds = visible.ids;
  7748. for (let i = 1, ii = lastId - firstId; i < ii; i++) {
  7749. const holeId = scrolledDown ? firstId + i : lastId - i;
  7750. if (visibleIds.has(holeId)) {
  7751. continue;
  7752. }
  7753. const holeView = views[holeId - 1];
  7754. if (!this.isViewFinished(holeView)) {
  7755. return holeView;
  7756. }
  7757. }
  7758. }
  7759. let preRenderIndex = scrolledDown ? lastId : firstId - 2;
  7760. let preRenderView = views[preRenderIndex];
  7761. if (preRenderView && !this.isViewFinished(preRenderView)) {
  7762. return preRenderView;
  7763. }
  7764. if (preRenderExtra) {
  7765. preRenderIndex += scrolledDown ? 1 : -1;
  7766. preRenderView = views[preRenderIndex];
  7767. if (preRenderView && !this.isViewFinished(preRenderView)) {
  7768. return preRenderView;
  7769. }
  7770. }
  7771. return null;
  7772. }
  7773. isViewFinished(view) {
  7774. return view.renderingState === RenderingStates.FINISHED;
  7775. }
  7776. renderView(view) {
  7777. switch (view.renderingState) {
  7778. case RenderingStates.FINISHED:
  7779. return false;
  7780. case RenderingStates.PAUSED:
  7781. this.highestPriorityPage = view.renderingId;
  7782. view.resume();
  7783. break;
  7784. case RenderingStates.RUNNING:
  7785. this.highestPriorityPage = view.renderingId;
  7786. break;
  7787. case RenderingStates.INITIAL:
  7788. this.highestPriorityPage = view.renderingId;
  7789. view.draw().finally(() => {
  7790. this.renderHighestPriority();
  7791. }).catch(reason => {
  7792. if (reason instanceof RenderingCancelledException) {
  7793. return;
  7794. }
  7795. console.error("renderView:", reason);
  7796. });
  7797. break;
  7798. }
  7799. return true;
  7800. }
  7801. }
  7802. ;// ./web/pdf_scripting_manager.js
  7803. class PDFScriptingManager {
  7804. #closeCapability = null;
  7805. #destroyCapability = null;
  7806. #docProperties = null;
  7807. #eventAbortController = null;
  7808. #eventBus = null;
  7809. #externalServices = null;
  7810. #pdfDocument = null;
  7811. #pdfViewer = null;
  7812. #ready = false;
  7813. #scripting = null;
  7814. #willPrintCapability = null;
  7815. constructor({
  7816. eventBus,
  7817. externalServices = null,
  7818. docProperties = null
  7819. }) {
  7820. this.#eventBus = eventBus;
  7821. this.#externalServices = externalServices;
  7822. this.#docProperties = docProperties;
  7823. }
  7824. setViewer(pdfViewer) {
  7825. this.#pdfViewer = pdfViewer;
  7826. }
  7827. async setDocument(pdfDocument) {
  7828. if (this.#pdfDocument) {
  7829. await this.#destroyScripting();
  7830. }
  7831. this.#pdfDocument = pdfDocument;
  7832. if (!pdfDocument) {
  7833. return;
  7834. }
  7835. const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]);
  7836. if (!objects && !docActions) {
  7837. await this.#destroyScripting();
  7838. return;
  7839. }
  7840. if (pdfDocument !== this.#pdfDocument) {
  7841. return;
  7842. }
  7843. try {
  7844. this.#scripting = this.#initScripting();
  7845. } catch (error) {
  7846. console.error("setDocument:", error);
  7847. await this.#destroyScripting();
  7848. return;
  7849. }
  7850. const eventBus = this.#eventBus;
  7851. this.#eventAbortController = new AbortController();
  7852. const {
  7853. signal
  7854. } = this.#eventAbortController;
  7855. eventBus._on("updatefromsandbox", event => {
  7856. if (event?.source === window) {
  7857. this.#updateFromSandbox(event.detail);
  7858. }
  7859. }, {
  7860. signal
  7861. });
  7862. eventBus._on("dispatcheventinsandbox", event => {
  7863. this.#scripting?.dispatchEventInSandbox(event.detail);
  7864. }, {
  7865. signal
  7866. });
  7867. eventBus._on("pagechanging", ({
  7868. pageNumber,
  7869. previous
  7870. }) => {
  7871. if (pageNumber === previous) {
  7872. return;
  7873. }
  7874. this.#dispatchPageClose(previous);
  7875. this.#dispatchPageOpen(pageNumber);
  7876. }, {
  7877. signal
  7878. });
  7879. eventBus._on("pagerendered", ({
  7880. pageNumber
  7881. }) => {
  7882. if (!this._pageOpenPending.has(pageNumber)) {
  7883. return;
  7884. }
  7885. if (pageNumber !== this.#pdfViewer.currentPageNumber) {
  7886. return;
  7887. }
  7888. this.#dispatchPageOpen(pageNumber);
  7889. }, {
  7890. signal
  7891. });
  7892. eventBus._on("pagesdestroy", async () => {
  7893. await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber);
  7894. await this.#scripting?.dispatchEventInSandbox({
  7895. id: "doc",
  7896. name: "WillClose"
  7897. });
  7898. this.#closeCapability?.resolve();
  7899. }, {
  7900. signal
  7901. });
  7902. try {
  7903. const docProperties = await this.#docProperties(pdfDocument);
  7904. if (pdfDocument !== this.#pdfDocument) {
  7905. return;
  7906. }
  7907. await this.#scripting.createSandbox({
  7908. objects,
  7909. calculationOrder,
  7910. appInfo: {
  7911. platform: navigator.platform,
  7912. language: navigator.language
  7913. },
  7914. docInfo: {
  7915. ...docProperties,
  7916. actions: docActions
  7917. }
  7918. });
  7919. eventBus.dispatch("sandboxcreated", {
  7920. source: this
  7921. });
  7922. } catch (error) {
  7923. console.error("setDocument:", error);
  7924. await this.#destroyScripting();
  7925. return;
  7926. }
  7927. await this.#scripting?.dispatchEventInSandbox({
  7928. id: "doc",
  7929. name: "Open"
  7930. });
  7931. await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true);
  7932. Promise.resolve().then(() => {
  7933. if (pdfDocument === this.#pdfDocument) {
  7934. this.#ready = true;
  7935. }
  7936. });
  7937. }
  7938. async dispatchWillSave() {
  7939. return this.#scripting?.dispatchEventInSandbox({
  7940. id: "doc",
  7941. name: "WillSave"
  7942. });
  7943. }
  7944. async dispatchDidSave() {
  7945. return this.#scripting?.dispatchEventInSandbox({
  7946. id: "doc",
  7947. name: "DidSave"
  7948. });
  7949. }
  7950. async dispatchWillPrint() {
  7951. if (!this.#scripting) {
  7952. return;
  7953. }
  7954. await this.#willPrintCapability?.promise;
  7955. this.#willPrintCapability = Promise.withResolvers();
  7956. try {
  7957. await this.#scripting.dispatchEventInSandbox({
  7958. id: "doc",
  7959. name: "WillPrint"
  7960. });
  7961. } catch (ex) {
  7962. this.#willPrintCapability.resolve();
  7963. this.#willPrintCapability = null;
  7964. throw ex;
  7965. }
  7966. await this.#willPrintCapability.promise;
  7967. }
  7968. async dispatchDidPrint() {
  7969. return this.#scripting?.dispatchEventInSandbox({
  7970. id: "doc",
  7971. name: "DidPrint"
  7972. });
  7973. }
  7974. get destroyPromise() {
  7975. return this.#destroyCapability?.promise || null;
  7976. }
  7977. get ready() {
  7978. return this.#ready;
  7979. }
  7980. get _pageOpenPending() {
  7981. return shadow(this, "_pageOpenPending", new Set());
  7982. }
  7983. get _visitedPages() {
  7984. return shadow(this, "_visitedPages", new Map());
  7985. }
  7986. async #updateFromSandbox(detail) {
  7987. const pdfViewer = this.#pdfViewer;
  7988. const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode;
  7989. const {
  7990. id,
  7991. siblings,
  7992. command,
  7993. value
  7994. } = detail;
  7995. if (!id) {
  7996. switch (command) {
  7997. case "clear":
  7998. console.clear();
  7999. break;
  8000. case "error":
  8001. console.error(value);
  8002. break;
  8003. case "layout":
  8004. if (!isInPresentationMode) {
  8005. const modes = apiPageLayoutToViewerModes(value);
  8006. pdfViewer.spreadMode = modes.spreadMode;
  8007. }
  8008. break;
  8009. case "page-num":
  8010. pdfViewer.currentPageNumber = value + 1;
  8011. break;
  8012. case "print":
  8013. await pdfViewer.pagesPromise;
  8014. this.#eventBus.dispatch("print", {
  8015. source: this
  8016. });
  8017. break;
  8018. case "println":
  8019. console.log(value);
  8020. break;
  8021. case "zoom":
  8022. if (!isInPresentationMode) {
  8023. pdfViewer.currentScaleValue = value;
  8024. }
  8025. break;
  8026. case "SaveAs":
  8027. this.#eventBus.dispatch("download", {
  8028. source: this
  8029. });
  8030. break;
  8031. case "FirstPage":
  8032. pdfViewer.currentPageNumber = 1;
  8033. break;
  8034. case "LastPage":
  8035. pdfViewer.currentPageNumber = pdfViewer.pagesCount;
  8036. break;
  8037. case "NextPage":
  8038. pdfViewer.nextPage();
  8039. break;
  8040. case "PrevPage":
  8041. pdfViewer.previousPage();
  8042. break;
  8043. case "ZoomViewIn":
  8044. if (!isInPresentationMode) {
  8045. pdfViewer.increaseScale();
  8046. }
  8047. break;
  8048. case "ZoomViewOut":
  8049. if (!isInPresentationMode) {
  8050. pdfViewer.decreaseScale();
  8051. }
  8052. break;
  8053. case "WillPrintFinished":
  8054. this.#willPrintCapability?.resolve();
  8055. this.#willPrintCapability = null;
  8056. break;
  8057. }
  8058. return;
  8059. }
  8060. if (isInPresentationMode && detail.focus) {
  8061. return;
  8062. }
  8063. delete detail.id;
  8064. delete detail.siblings;
  8065. const ids = siblings ? [id, ...siblings] : [id];
  8066. for (const elementId of ids) {
  8067. const element = document.querySelector(`[data-element-id="${elementId}"]`);
  8068. if (element) {
  8069. element.dispatchEvent(new CustomEvent("updatefromsandbox", {
  8070. detail
  8071. }));
  8072. } else {
  8073. this.#pdfDocument?.annotationStorage.setValue(elementId, detail);
  8074. }
  8075. }
  8076. }
  8077. async #dispatchPageOpen(pageNumber, initialize = false) {
  8078. const pdfDocument = this.#pdfDocument,
  8079. visitedPages = this._visitedPages;
  8080. if (initialize) {
  8081. this.#closeCapability = Promise.withResolvers();
  8082. }
  8083. if (!this.#closeCapability) {
  8084. return;
  8085. }
  8086. const pageView = this.#pdfViewer.getPageView(pageNumber - 1);
  8087. if (pageView?.renderingState !== RenderingStates.FINISHED) {
  8088. this._pageOpenPending.add(pageNumber);
  8089. return;
  8090. }
  8091. this._pageOpenPending.delete(pageNumber);
  8092. const actionsPromise = (async () => {
  8093. const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null);
  8094. if (pdfDocument !== this.#pdfDocument) {
  8095. return;
  8096. }
  8097. await this.#scripting?.dispatchEventInSandbox({
  8098. id: "page",
  8099. name: "PageOpen",
  8100. pageNumber,
  8101. actions
  8102. });
  8103. })();
  8104. visitedPages.set(pageNumber, actionsPromise);
  8105. }
  8106. async #dispatchPageClose(pageNumber) {
  8107. const pdfDocument = this.#pdfDocument,
  8108. visitedPages = this._visitedPages;
  8109. if (!this.#closeCapability) {
  8110. return;
  8111. }
  8112. if (this._pageOpenPending.has(pageNumber)) {
  8113. return;
  8114. }
  8115. const actionsPromise = visitedPages.get(pageNumber);
  8116. if (!actionsPromise) {
  8117. return;
  8118. }
  8119. visitedPages.set(pageNumber, null);
  8120. await actionsPromise;
  8121. if (pdfDocument !== this.#pdfDocument) {
  8122. return;
  8123. }
  8124. await this.#scripting?.dispatchEventInSandbox({
  8125. id: "page",
  8126. name: "PageClose",
  8127. pageNumber
  8128. });
  8129. }
  8130. #initScripting() {
  8131. this.#destroyCapability = Promise.withResolvers();
  8132. if (this.#scripting) {
  8133. throw new Error("#initScripting: Scripting already exists.");
  8134. }
  8135. return this.#externalServices.createScripting();
  8136. }
  8137. async #destroyScripting() {
  8138. if (!this.#scripting) {
  8139. this.#pdfDocument = null;
  8140. this.#destroyCapability?.resolve();
  8141. return;
  8142. }
  8143. if (this.#closeCapability) {
  8144. await Promise.race([this.#closeCapability.promise, new Promise(resolve => {
  8145. setTimeout(resolve, 1000);
  8146. })]).catch(() => {});
  8147. this.#closeCapability = null;
  8148. }
  8149. this.#pdfDocument = null;
  8150. try {
  8151. await this.#scripting.destroySandbox();
  8152. } catch {}
  8153. this.#willPrintCapability?.reject(new Error("Scripting destroyed."));
  8154. this.#willPrintCapability = null;
  8155. this.#eventAbortController?.abort();
  8156. this.#eventAbortController = null;
  8157. this._pageOpenPending.clear();
  8158. this._visitedPages.clear();
  8159. this.#scripting = null;
  8160. this.#ready = false;
  8161. this.#destroyCapability?.resolve();
  8162. }
  8163. }
  8164. ;// ./web/pdf_sidebar.js
  8165. const SIDEBAR_WIDTH_VAR = "--sidebar-width";
  8166. const SIDEBAR_MIN_WIDTH = 200;
  8167. const SIDEBAR_RESIZING_CLASS = "sidebarResizing";
  8168. const UI_NOTIFICATION_CLASS = "pdfSidebarNotification";
  8169. class PDFSidebar {
  8170. #isRTL = false;
  8171. #mouseAC = null;
  8172. #outerContainerWidth = null;
  8173. #width = null;
  8174. constructor({
  8175. elements,
  8176. eventBus,
  8177. l10n
  8178. }) {
  8179. this.isOpen = false;
  8180. this.active = SidebarView.THUMBS;
  8181. this.isInitialViewSet = false;
  8182. this.isInitialEventDispatched = false;
  8183. this.onToggled = null;
  8184. this.onUpdateThumbnails = null;
  8185. this.outerContainer = elements.outerContainer;
  8186. this.sidebarContainer = elements.sidebarContainer;
  8187. this.toggleButton = elements.toggleButton;
  8188. this.resizer = elements.resizer;
  8189. this.thumbnailButton = elements.thumbnailButton;
  8190. this.outlineButton = elements.outlineButton;
  8191. this.attachmentsButton = elements.attachmentsButton;
  8192. this.layersButton = elements.layersButton;
  8193. this.thumbnailView = elements.thumbnailView;
  8194. this.outlineView = elements.outlineView;
  8195. this.attachmentsView = elements.attachmentsView;
  8196. this.layersView = elements.layersView;
  8197. this._currentOutlineItemButton = elements.currentOutlineItemButton;
  8198. this.eventBus = eventBus;
  8199. this.#isRTL = l10n.getDirection() === "rtl";
  8200. this.#addEventListeners();
  8201. }
  8202. reset() {
  8203. this.isInitialViewSet = false;
  8204. this.isInitialEventDispatched = false;
  8205. this.#hideUINotification(true);
  8206. this.switchView(SidebarView.THUMBS);
  8207. this.outlineButton.disabled = false;
  8208. this.attachmentsButton.disabled = false;
  8209. this.layersButton.disabled = false;
  8210. this._currentOutlineItemButton.disabled = true;
  8211. }
  8212. get visibleView() {
  8213. return this.isOpen ? this.active : SidebarView.NONE;
  8214. }
  8215. setInitialView(view = SidebarView.NONE) {
  8216. if (this.isInitialViewSet) {
  8217. return;
  8218. }
  8219. this.isInitialViewSet = true;
  8220. if (view === SidebarView.NONE || view === SidebarView.UNKNOWN) {
  8221. this.#dispatchEvent();
  8222. return;
  8223. }
  8224. this.switchView(view, true);
  8225. if (!this.isInitialEventDispatched) {
  8226. this.#dispatchEvent();
  8227. }
  8228. }
  8229. switchView(view, forceOpen = false) {
  8230. const isViewChanged = view !== this.active;
  8231. let forceRendering = false;
  8232. switch (view) {
  8233. case SidebarView.NONE:
  8234. if (this.isOpen) {
  8235. this.close();
  8236. }
  8237. return;
  8238. case SidebarView.THUMBS:
  8239. if (this.isOpen && isViewChanged) {
  8240. forceRendering = true;
  8241. }
  8242. break;
  8243. case SidebarView.OUTLINE:
  8244. if (this.outlineButton.disabled) {
  8245. return;
  8246. }
  8247. break;
  8248. case SidebarView.ATTACHMENTS:
  8249. if (this.attachmentsButton.disabled) {
  8250. return;
  8251. }
  8252. break;
  8253. case SidebarView.LAYERS:
  8254. if (this.layersButton.disabled) {
  8255. return;
  8256. }
  8257. break;
  8258. default:
  8259. console.error(`PDFSidebar.switchView: "${view}" is not a valid view.`);
  8260. return;
  8261. }
  8262. this.active = view;
  8263. toggleCheckedBtn(this.thumbnailButton, view === SidebarView.THUMBS, this.thumbnailView);
  8264. toggleCheckedBtn(this.outlineButton, view === SidebarView.OUTLINE, this.outlineView);
  8265. toggleCheckedBtn(this.attachmentsButton, view === SidebarView.ATTACHMENTS, this.attachmentsView);
  8266. toggleCheckedBtn(this.layersButton, view === SidebarView.LAYERS, this.layersView);
  8267. if (forceOpen && !this.isOpen) {
  8268. this.open();
  8269. return;
  8270. }
  8271. if (forceRendering) {
  8272. this.onUpdateThumbnails();
  8273. this.onToggled();
  8274. }
  8275. if (isViewChanged) {
  8276. this.#dispatchEvent();
  8277. }
  8278. }
  8279. open() {
  8280. if (this.isOpen) {
  8281. return;
  8282. }
  8283. this.isOpen = true;
  8284. toggleExpandedBtn(this.toggleButton, true);
  8285. this.outerContainer.classList.add("sidebarMoving", "sidebarOpen");
  8286. if (this.active === SidebarView.THUMBS) {
  8287. this.onUpdateThumbnails();
  8288. }
  8289. this.onToggled();
  8290. this.#dispatchEvent();
  8291. this.#hideUINotification();
  8292. }
  8293. close(evt = null) {
  8294. if (!this.isOpen) {
  8295. return;
  8296. }
  8297. this.isOpen = false;
  8298. toggleExpandedBtn(this.toggleButton, false);
  8299. this.outerContainer.classList.add("sidebarMoving");
  8300. this.outerContainer.classList.remove("sidebarOpen");
  8301. this.onToggled();
  8302. this.#dispatchEvent();
  8303. if (evt?.detail > 0) {
  8304. this.toggleButton.blur();
  8305. }
  8306. }
  8307. toggle(evt = null) {
  8308. if (this.isOpen) {
  8309. this.close(evt);
  8310. } else {
  8311. this.open();
  8312. }
  8313. }
  8314. #dispatchEvent() {
  8315. if (this.isInitialViewSet) {
  8316. this.isInitialEventDispatched ||= true;
  8317. }
  8318. this.eventBus.dispatch("sidebarviewchanged", {
  8319. source: this,
  8320. view: this.visibleView
  8321. });
  8322. }
  8323. #showUINotification() {
  8324. this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-notification-button");
  8325. if (!this.isOpen) {
  8326. this.toggleButton.classList.add(UI_NOTIFICATION_CLASS);
  8327. }
  8328. }
  8329. #hideUINotification(reset = false) {
  8330. if (this.isOpen || reset) {
  8331. this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS);
  8332. }
  8333. if (reset) {
  8334. this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-button");
  8335. }
  8336. }
  8337. #addEventListeners() {
  8338. const {
  8339. eventBus,
  8340. outerContainer
  8341. } = this;
  8342. this.sidebarContainer.addEventListener("transitionend", evt => {
  8343. if (evt.target === this.sidebarContainer) {
  8344. outerContainer.classList.remove("sidebarMoving");
  8345. eventBus.dispatch("resize", {
  8346. source: this
  8347. });
  8348. }
  8349. });
  8350. this.toggleButton.addEventListener("click", evt => {
  8351. this.toggle(evt);
  8352. });
  8353. this.thumbnailButton.addEventListener("click", () => {
  8354. this.switchView(SidebarView.THUMBS);
  8355. });
  8356. this.outlineButton.addEventListener("click", () => {
  8357. this.switchView(SidebarView.OUTLINE);
  8358. });
  8359. this.outlineButton.addEventListener("dblclick", () => {
  8360. eventBus.dispatch("toggleoutlinetree", {
  8361. source: this
  8362. });
  8363. });
  8364. this.attachmentsButton.addEventListener("click", () => {
  8365. this.switchView(SidebarView.ATTACHMENTS);
  8366. });
  8367. this.layersButton.addEventListener("click", () => {
  8368. this.switchView(SidebarView.LAYERS);
  8369. });
  8370. this.layersButton.addEventListener("dblclick", () => {
  8371. eventBus.dispatch("resetlayers", {
  8372. source: this
  8373. });
  8374. });
  8375. this._currentOutlineItemButton.addEventListener("click", () => {
  8376. eventBus.dispatch("currentoutlineitem", {
  8377. source: this
  8378. });
  8379. });
  8380. const onTreeLoaded = (count, button, view) => {
  8381. button.disabled = !count;
  8382. if (count) {
  8383. this.#showUINotification();
  8384. } else if (this.active === view) {
  8385. this.switchView(SidebarView.THUMBS);
  8386. }
  8387. };
  8388. eventBus._on("outlineloaded", evt => {
  8389. onTreeLoaded(evt.outlineCount, this.outlineButton, SidebarView.OUTLINE);
  8390. evt.currentOutlineItemPromise.then(enabled => {
  8391. if (!this.isInitialViewSet) {
  8392. return;
  8393. }
  8394. this._currentOutlineItemButton.disabled = !enabled;
  8395. });
  8396. });
  8397. eventBus._on("attachmentsloaded", evt => {
  8398. onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, SidebarView.ATTACHMENTS);
  8399. });
  8400. eventBus._on("layersloaded", evt => {
  8401. onTreeLoaded(evt.layersCount, this.layersButton, SidebarView.LAYERS);
  8402. });
  8403. eventBus._on("presentationmodechanged", evt => {
  8404. if (evt.state === PresentationModeState.NORMAL && this.visibleView === SidebarView.THUMBS) {
  8405. this.onUpdateThumbnails();
  8406. }
  8407. });
  8408. this.resizer.addEventListener("mousedown", evt => {
  8409. if (evt.button !== 0) {
  8410. return;
  8411. }
  8412. outerContainer.classList.add(SIDEBAR_RESIZING_CLASS);
  8413. this.#mouseAC = new AbortController();
  8414. const opts = {
  8415. signal: this.#mouseAC.signal
  8416. };
  8417. window.addEventListener("mousemove", this.#mouseMove.bind(this), opts);
  8418. window.addEventListener("mouseup", this.#mouseUp.bind(this), opts);
  8419. window.addEventListener("blur", this.#mouseUp.bind(this), opts);
  8420. });
  8421. eventBus._on("resize", evt => {
  8422. if (evt.source !== window) {
  8423. return;
  8424. }
  8425. this.#outerContainerWidth = null;
  8426. if (!this.#width) {
  8427. return;
  8428. }
  8429. if (!this.isOpen) {
  8430. this.#updateWidth(this.#width);
  8431. return;
  8432. }
  8433. outerContainer.classList.add(SIDEBAR_RESIZING_CLASS);
  8434. const updated = this.#updateWidth(this.#width);
  8435. Promise.resolve().then(() => {
  8436. outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS);
  8437. if (updated) {
  8438. eventBus.dispatch("resize", {
  8439. source: this
  8440. });
  8441. }
  8442. });
  8443. });
  8444. }
  8445. get outerContainerWidth() {
  8446. return this.#outerContainerWidth ||= this.outerContainer.clientWidth;
  8447. }
  8448. #updateWidth(width = 0) {
  8449. const maxWidth = Math.floor(this.outerContainerWidth / 2);
  8450. if (width > maxWidth) {
  8451. width = maxWidth;
  8452. }
  8453. if (width < SIDEBAR_MIN_WIDTH) {
  8454. width = SIDEBAR_MIN_WIDTH;
  8455. }
  8456. if (width === this.#width) {
  8457. return false;
  8458. }
  8459. this.#width = width;
  8460. docStyle.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`);
  8461. return true;
  8462. }
  8463. #mouseMove(evt) {
  8464. let width = evt.clientX;
  8465. if (this.#isRTL) {
  8466. width = this.outerContainerWidth - width;
  8467. }
  8468. this.#updateWidth(width);
  8469. }
  8470. #mouseUp(evt) {
  8471. this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS);
  8472. this.eventBus.dispatch("resize", {
  8473. source: this
  8474. });
  8475. this.#mouseAC?.abort();
  8476. this.#mouseAC = null;
  8477. }
  8478. }
  8479. ;// ./web/pdf_thumbnail_view.js
  8480. const DRAW_UPSCALE_FACTOR = 2;
  8481. const MAX_NUM_SCALING_STEPS = 3;
  8482. const THUMBNAIL_WIDTH = 98;
  8483. function zeroCanvas(c) {
  8484. c.width = 0;
  8485. c.height = 0;
  8486. }
  8487. class TempImageFactory {
  8488. static #tempCanvas = null;
  8489. static getCanvas(width, height) {
  8490. const tempCanvas = this.#tempCanvas ||= document.createElement("canvas");
  8491. tempCanvas.width = width;
  8492. tempCanvas.height = height;
  8493. const ctx = tempCanvas.getContext("2d", {
  8494. alpha: false
  8495. });
  8496. ctx.save();
  8497. ctx.fillStyle = "rgb(255, 255, 255)";
  8498. ctx.fillRect(0, 0, width, height);
  8499. ctx.restore();
  8500. return [tempCanvas, tempCanvas.getContext("2d")];
  8501. }
  8502. static destroyCanvas() {
  8503. if (this.#tempCanvas) {
  8504. zeroCanvas(this.#tempCanvas);
  8505. }
  8506. this.#tempCanvas = null;
  8507. }
  8508. }
  8509. class PDFThumbnailView {
  8510. constructor({
  8511. container,
  8512. eventBus,
  8513. id,
  8514. defaultViewport,
  8515. optionalContentConfigPromise,
  8516. linkService,
  8517. renderingQueue,
  8518. maxCanvasPixels,
  8519. maxCanvasDim,
  8520. pageColors,
  8521. enableHWA
  8522. }) {
  8523. this.id = id;
  8524. this.renderingId = "thumbnail" + id;
  8525. this.pageLabel = null;
  8526. this.pdfPage = null;
  8527. this.rotation = 0;
  8528. this.viewport = defaultViewport;
  8529. this.pdfPageRotate = defaultViewport.rotation;
  8530. this._optionalContentConfigPromise = optionalContentConfigPromise || null;
  8531. this.maxCanvasPixels = maxCanvasPixels ?? AppOptions.get("maxCanvasPixels");
  8532. this.maxCanvasDim = maxCanvasDim || AppOptions.get("maxCanvasDim");
  8533. this.pageColors = pageColors || null;
  8534. this.enableHWA = enableHWA || false;
  8535. this.eventBus = eventBus;
  8536. this.linkService = linkService;
  8537. this.renderingQueue = renderingQueue;
  8538. this.renderTask = null;
  8539. this.renderingState = RenderingStates.INITIAL;
  8540. this.resume = null;
  8541. const anchor = document.createElement("a");
  8542. anchor.href = linkService.getAnchorUrl("#page=" + id);
  8543. anchor.setAttribute("data-l10n-id", "pdfjs-thumb-page-title");
  8544. anchor.setAttribute("data-l10n-args", this.#pageL10nArgs);
  8545. anchor.onclick = function () {
  8546. linkService.goToPage(id);
  8547. return false;
  8548. };
  8549. this.anchor = anchor;
  8550. const div = document.createElement("div");
  8551. div.className = "thumbnail";
  8552. div.setAttribute("data-page-number", this.id);
  8553. this.div = div;
  8554. this.#updateDims();
  8555. const img = document.createElement("div");
  8556. img.className = "thumbnailImage";
  8557. this._placeholderImg = img;
  8558. div.append(img);
  8559. anchor.append(div);
  8560. container.append(anchor);
  8561. }
  8562. #updateDims() {
  8563. const {
  8564. width,
  8565. height
  8566. } = this.viewport;
  8567. const ratio = width / height;
  8568. this.canvasWidth = THUMBNAIL_WIDTH;
  8569. this.canvasHeight = this.canvasWidth / ratio | 0;
  8570. this.scale = this.canvasWidth / width;
  8571. const {
  8572. style
  8573. } = this.div;
  8574. style.setProperty("--thumbnail-width", `${this.canvasWidth}px`);
  8575. style.setProperty("--thumbnail-height", `${this.canvasHeight}px`);
  8576. }
  8577. setPdfPage(pdfPage) {
  8578. this.pdfPage = pdfPage;
  8579. this.pdfPageRotate = pdfPage.rotate;
  8580. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  8581. this.viewport = pdfPage.getViewport({
  8582. scale: 1,
  8583. rotation: totalRotation
  8584. });
  8585. this.reset();
  8586. }
  8587. reset() {
  8588. this.cancelRendering();
  8589. this.renderingState = RenderingStates.INITIAL;
  8590. this.div.removeAttribute("data-loaded");
  8591. this.image?.replaceWith(this._placeholderImg);
  8592. this.#updateDims();
  8593. if (this.image) {
  8594. this.image.removeAttribute("src");
  8595. delete this.image;
  8596. }
  8597. }
  8598. update({
  8599. rotation = null
  8600. }) {
  8601. if (typeof rotation === "number") {
  8602. this.rotation = rotation;
  8603. }
  8604. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  8605. this.viewport = this.viewport.clone({
  8606. scale: 1,
  8607. rotation: totalRotation
  8608. });
  8609. this.reset();
  8610. }
  8611. cancelRendering() {
  8612. if (this.renderTask) {
  8613. this.renderTask.cancel();
  8614. this.renderTask = null;
  8615. }
  8616. this.resume = null;
  8617. }
  8618. #getPageDrawContext(upscaleFactor = 1, enableHWA = this.enableHWA) {
  8619. const canvas = document.createElement("canvas");
  8620. const ctx = canvas.getContext("2d", {
  8621. alpha: false,
  8622. willReadFrequently: !enableHWA
  8623. });
  8624. const outputScale = new OutputScale();
  8625. const width = upscaleFactor * this.canvasWidth,
  8626. height = upscaleFactor * this.canvasHeight;
  8627. outputScale.limitCanvas(width, height, this.maxCanvasPixels, this.maxCanvasDim);
  8628. canvas.width = width * outputScale.sx | 0;
  8629. canvas.height = height * outputScale.sy | 0;
  8630. const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null;
  8631. return {
  8632. ctx,
  8633. canvas,
  8634. transform
  8635. };
  8636. }
  8637. #convertCanvasToImage(canvas) {
  8638. if (this.renderingState !== RenderingStates.FINISHED) {
  8639. throw new Error("#convertCanvasToImage: Rendering has not finished.");
  8640. }
  8641. const reducedCanvas = this.#reduceImage(canvas);
  8642. const image = document.createElement("img");
  8643. image.className = "thumbnailImage";
  8644. image.setAttribute("data-l10n-id", "pdfjs-thumb-page-canvas");
  8645. image.setAttribute("data-l10n-args", this.#pageL10nArgs);
  8646. image.src = reducedCanvas.toDataURL();
  8647. this.image = image;
  8648. this.div.setAttribute("data-loaded", true);
  8649. this._placeholderImg.replaceWith(image);
  8650. zeroCanvas(reducedCanvas);
  8651. }
  8652. async draw() {
  8653. if (this.renderingState !== RenderingStates.INITIAL) {
  8654. console.error("Must be in new state before drawing");
  8655. return;
  8656. }
  8657. const {
  8658. pageColors,
  8659. pdfPage
  8660. } = this;
  8661. if (!pdfPage) {
  8662. this.renderingState = RenderingStates.FINISHED;
  8663. throw new Error("pdfPage is not loaded");
  8664. }
  8665. this.renderingState = RenderingStates.RUNNING;
  8666. const {
  8667. ctx,
  8668. canvas,
  8669. transform
  8670. } = this.#getPageDrawContext(DRAW_UPSCALE_FACTOR);
  8671. const drawViewport = this.viewport.clone({
  8672. scale: DRAW_UPSCALE_FACTOR * this.scale
  8673. });
  8674. const renderContinueCallback = cont => {
  8675. if (!this.renderingQueue.isHighestPriority(this)) {
  8676. this.renderingState = RenderingStates.PAUSED;
  8677. this.resume = () => {
  8678. this.renderingState = RenderingStates.RUNNING;
  8679. cont();
  8680. };
  8681. return;
  8682. }
  8683. cont();
  8684. };
  8685. const renderContext = {
  8686. canvasContext: ctx,
  8687. transform,
  8688. viewport: drawViewport,
  8689. optionalContentConfigPromise: this._optionalContentConfigPromise,
  8690. pageColors
  8691. };
  8692. const renderTask = this.renderTask = pdfPage.render(renderContext);
  8693. renderTask.onContinue = renderContinueCallback;
  8694. let error = null;
  8695. try {
  8696. await renderTask.promise;
  8697. } catch (e) {
  8698. if (e instanceof RenderingCancelledException) {
  8699. zeroCanvas(canvas);
  8700. return;
  8701. }
  8702. error = e;
  8703. } finally {
  8704. if (renderTask === this.renderTask) {
  8705. this.renderTask = null;
  8706. }
  8707. }
  8708. this.renderingState = RenderingStates.FINISHED;
  8709. this.#convertCanvasToImage(canvas);
  8710. zeroCanvas(canvas);
  8711. this.eventBus.dispatch("thumbnailrendered", {
  8712. source: this,
  8713. pageNumber: this.id,
  8714. pdfPage
  8715. });
  8716. if (error) {
  8717. throw error;
  8718. }
  8719. }
  8720. setImage(pageView) {
  8721. if (this.renderingState !== RenderingStates.INITIAL) {
  8722. return;
  8723. }
  8724. const {
  8725. thumbnailCanvas: canvas,
  8726. pdfPage,
  8727. scale
  8728. } = pageView;
  8729. if (!canvas) {
  8730. return;
  8731. }
  8732. if (!this.pdfPage) {
  8733. this.setPdfPage(pdfPage);
  8734. }
  8735. if (scale < this.scale) {
  8736. return;
  8737. }
  8738. this.renderingState = RenderingStates.FINISHED;
  8739. this.#convertCanvasToImage(canvas);
  8740. }
  8741. #getReducedImageDims(canvas) {
  8742. const width = canvas.width << MAX_NUM_SCALING_STEPS,
  8743. height = canvas.height << MAX_NUM_SCALING_STEPS;
  8744. const outputScale = new OutputScale();
  8745. outputScale.sx = outputScale.sy = 1;
  8746. outputScale.limitCanvas(width, height, this.maxCanvasPixels, this.maxCanvasDim);
  8747. return [width * outputScale.sx | 0, height * outputScale.sy | 0];
  8748. }
  8749. #reduceImage(img) {
  8750. const {
  8751. ctx,
  8752. canvas
  8753. } = this.#getPageDrawContext(1, true);
  8754. if (img.width <= 2 * canvas.width) {
  8755. ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
  8756. return canvas;
  8757. }
  8758. let [reducedWidth, reducedHeight] = this.#getReducedImageDims(canvas);
  8759. const [reducedImage, reducedImageCtx] = TempImageFactory.getCanvas(reducedWidth, reducedHeight);
  8760. while (reducedWidth > img.width || reducedHeight > img.height) {
  8761. reducedWidth >>= 1;
  8762. reducedHeight >>= 1;
  8763. }
  8764. reducedImageCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, reducedWidth, reducedHeight);
  8765. while (reducedWidth > 2 * canvas.width) {
  8766. reducedImageCtx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, reducedWidth >> 1, reducedHeight >> 1);
  8767. reducedWidth >>= 1;
  8768. reducedHeight >>= 1;
  8769. }
  8770. ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height);
  8771. return canvas;
  8772. }
  8773. get #pageL10nArgs() {
  8774. return JSON.stringify({
  8775. page: this.pageLabel ?? this.id
  8776. });
  8777. }
  8778. setPageLabel(label) {
  8779. this.pageLabel = typeof label === "string" ? label : null;
  8780. this.anchor.setAttribute("data-l10n-args", this.#pageL10nArgs);
  8781. if (this.renderingState !== RenderingStates.FINISHED) {
  8782. return;
  8783. }
  8784. this.image?.setAttribute("data-l10n-args", this.#pageL10nArgs);
  8785. }
  8786. }
  8787. ;// ./web/pdf_thumbnail_viewer.js
  8788. const THUMBNAIL_SCROLL_MARGIN = -19;
  8789. const THUMBNAIL_SELECTED_CLASS = "selected";
  8790. class PDFThumbnailViewer {
  8791. constructor({
  8792. container,
  8793. eventBus,
  8794. linkService,
  8795. renderingQueue,
  8796. maxCanvasPixels,
  8797. maxCanvasDim,
  8798. pageColors,
  8799. abortSignal,
  8800. enableHWA
  8801. }) {
  8802. this.container = container;
  8803. this.eventBus = eventBus;
  8804. this.linkService = linkService;
  8805. this.renderingQueue = renderingQueue;
  8806. this.maxCanvasPixels = maxCanvasPixels;
  8807. this.maxCanvasDim = maxCanvasDim;
  8808. this.pageColors = pageColors || null;
  8809. this.enableHWA = enableHWA || false;
  8810. this.scroll = watchScroll(this.container, this.#scrollUpdated.bind(this), abortSignal);
  8811. this.#resetView();
  8812. }
  8813. #scrollUpdated() {
  8814. this.renderingQueue.renderHighestPriority();
  8815. }
  8816. getThumbnail(index) {
  8817. return this._thumbnails[index];
  8818. }
  8819. #getVisibleThumbs() {
  8820. return getVisibleElements({
  8821. scrollEl: this.container,
  8822. views: this._thumbnails
  8823. });
  8824. }
  8825. scrollThumbnailIntoView(pageNumber) {
  8826. if (!this.pdfDocument) {
  8827. return;
  8828. }
  8829. const thumbnailView = this._thumbnails[pageNumber - 1];
  8830. if (!thumbnailView) {
  8831. console.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.');
  8832. return;
  8833. }
  8834. if (pageNumber !== this._currentPageNumber) {
  8835. const prevThumbnailView = this._thumbnails[this._currentPageNumber - 1];
  8836. prevThumbnailView.div.classList.remove(THUMBNAIL_SELECTED_CLASS);
  8837. thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS);
  8838. }
  8839. const {
  8840. first,
  8841. last,
  8842. views
  8843. } = this.#getVisibleThumbs();
  8844. if (views.length > 0) {
  8845. let shouldScroll = false;
  8846. if (pageNumber <= first.id || pageNumber >= last.id) {
  8847. shouldScroll = true;
  8848. } else {
  8849. for (const {
  8850. id,
  8851. percent
  8852. } of views) {
  8853. if (id !== pageNumber) {
  8854. continue;
  8855. }
  8856. shouldScroll = percent < 100;
  8857. break;
  8858. }
  8859. }
  8860. if (shouldScroll) {
  8861. scrollIntoView(thumbnailView.div, {
  8862. top: THUMBNAIL_SCROLL_MARGIN
  8863. });
  8864. }
  8865. }
  8866. this._currentPageNumber = pageNumber;
  8867. }
  8868. get pagesRotation() {
  8869. return this._pagesRotation;
  8870. }
  8871. set pagesRotation(rotation) {
  8872. if (!isValidRotation(rotation)) {
  8873. throw new Error("Invalid thumbnails rotation angle.");
  8874. }
  8875. if (!this.pdfDocument) {
  8876. return;
  8877. }
  8878. if (this._pagesRotation === rotation) {
  8879. return;
  8880. }
  8881. this._pagesRotation = rotation;
  8882. const updateArgs = {
  8883. rotation
  8884. };
  8885. for (const thumbnail of this._thumbnails) {
  8886. thumbnail.update(updateArgs);
  8887. }
  8888. }
  8889. cleanup() {
  8890. for (const thumbnail of this._thumbnails) {
  8891. if (thumbnail.renderingState !== RenderingStates.FINISHED) {
  8892. thumbnail.reset();
  8893. }
  8894. }
  8895. TempImageFactory.destroyCanvas();
  8896. }
  8897. #resetView() {
  8898. this._thumbnails = [];
  8899. this._currentPageNumber = 1;
  8900. this._pageLabels = null;
  8901. this._pagesRotation = 0;
  8902. this.container.textContent = "";
  8903. }
  8904. setDocument(pdfDocument) {
  8905. if (this.pdfDocument) {
  8906. this.#cancelRendering();
  8907. this.#resetView();
  8908. }
  8909. this.pdfDocument = pdfDocument;
  8910. if (!pdfDocument) {
  8911. return;
  8912. }
  8913. const firstPagePromise = pdfDocument.getPage(1);
  8914. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({
  8915. intent: "display"
  8916. });
  8917. firstPagePromise.then(firstPdfPage => {
  8918. const pagesCount = pdfDocument.numPages;
  8919. const viewport = firstPdfPage.getViewport({
  8920. scale: 1
  8921. });
  8922. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  8923. const thumbnail = new PDFThumbnailView({
  8924. container: this.container,
  8925. eventBus: this.eventBus,
  8926. id: pageNum,
  8927. defaultViewport: viewport.clone(),
  8928. optionalContentConfigPromise,
  8929. linkService: this.linkService,
  8930. renderingQueue: this.renderingQueue,
  8931. maxCanvasPixels: this.maxCanvasPixels,
  8932. maxCanvasDim: this.maxCanvasDim,
  8933. pageColors: this.pageColors,
  8934. enableHWA: this.enableHWA
  8935. });
  8936. this._thumbnails.push(thumbnail);
  8937. }
  8938. this._thumbnails[0]?.setPdfPage(firstPdfPage);
  8939. const thumbnailView = this._thumbnails[this._currentPageNumber - 1];
  8940. thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS);
  8941. }).catch(reason => {
  8942. console.error("Unable to initialize thumbnail viewer", reason);
  8943. });
  8944. }
  8945. #cancelRendering() {
  8946. for (const thumbnail of this._thumbnails) {
  8947. thumbnail.cancelRendering();
  8948. }
  8949. }
  8950. setPageLabels(labels) {
  8951. if (!this.pdfDocument) {
  8952. return;
  8953. }
  8954. if (!labels) {
  8955. this._pageLabels = null;
  8956. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  8957. this._pageLabels = null;
  8958. console.error("PDFThumbnailViewer_setPageLabels: Invalid page labels.");
  8959. } else {
  8960. this._pageLabels = labels;
  8961. }
  8962. for (let i = 0, ii = this._thumbnails.length; i < ii; i++) {
  8963. this._thumbnails[i].setPageLabel(this._pageLabels?.[i] ?? null);
  8964. }
  8965. }
  8966. async #ensurePdfPageLoaded(thumbView) {
  8967. if (thumbView.pdfPage) {
  8968. return thumbView.pdfPage;
  8969. }
  8970. try {
  8971. const pdfPage = await this.pdfDocument.getPage(thumbView.id);
  8972. if (!thumbView.pdfPage) {
  8973. thumbView.setPdfPage(pdfPage);
  8974. }
  8975. return pdfPage;
  8976. } catch (reason) {
  8977. console.error("Unable to get page for thumb view", reason);
  8978. return null;
  8979. }
  8980. }
  8981. #getScrollAhead(visible) {
  8982. if (visible.first?.id === 1) {
  8983. return true;
  8984. } else if (visible.last?.id === this._thumbnails.length) {
  8985. return false;
  8986. }
  8987. return this.scroll.down;
  8988. }
  8989. forceRendering() {
  8990. const visibleThumbs = this.#getVisibleThumbs();
  8991. const scrollAhead = this.#getScrollAhead(visibleThumbs);
  8992. const thumbView = this.renderingQueue.getHighestPriority(visibleThumbs, this._thumbnails, scrollAhead, false, true);
  8993. if (thumbView) {
  8994. this.#ensurePdfPageLoaded(thumbView).then(() => {
  8995. this.renderingQueue.renderView(thumbView);
  8996. });
  8997. return true;
  8998. }
  8999. return false;
  9000. }
  9001. }
  9002. ;// ./web/annotation_editor_layer_builder.js
  9003. class AnnotationEditorLayerBuilder {
  9004. #annotationLayer = null;
  9005. #drawLayer = null;
  9006. #onAppend = null;
  9007. #structTreeLayer = null;
  9008. #textLayer = null;
  9009. #uiManager;
  9010. constructor(options) {
  9011. this.pdfPage = options.pdfPage;
  9012. this.accessibilityManager = options.accessibilityManager;
  9013. this.l10n = options.l10n;
  9014. this.l10n ||= new genericl10n_GenericL10n();
  9015. this.annotationEditorLayer = null;
  9016. this.div = null;
  9017. this._cancelled = false;
  9018. this.#uiManager = options.uiManager;
  9019. this.#annotationLayer = options.annotationLayer || null;
  9020. this.#textLayer = options.textLayer || null;
  9021. this.#drawLayer = options.drawLayer || null;
  9022. this.#onAppend = options.onAppend || null;
  9023. this.#structTreeLayer = options.structTreeLayer || null;
  9024. }
  9025. async render({
  9026. viewport,
  9027. intent = "display"
  9028. }) {
  9029. if (intent !== "display") {
  9030. return;
  9031. }
  9032. if (this._cancelled) {
  9033. return;
  9034. }
  9035. const clonedViewport = viewport.clone({
  9036. dontFlip: true
  9037. });
  9038. if (this.div) {
  9039. this.annotationEditorLayer.update({
  9040. viewport: clonedViewport
  9041. });
  9042. this.show();
  9043. return;
  9044. }
  9045. const div = this.div = document.createElement("div");
  9046. div.className = "annotationEditorLayer";
  9047. div.hidden = true;
  9048. div.dir = this.#uiManager.direction;
  9049. this.#onAppend?.(div);
  9050. this.annotationEditorLayer = new AnnotationEditorLayer({
  9051. uiManager: this.#uiManager,
  9052. div,
  9053. structTreeLayer: this.#structTreeLayer,
  9054. accessibilityManager: this.accessibilityManager,
  9055. pageIndex: this.pdfPage.pageNumber - 1,
  9056. l10n: this.l10n,
  9057. viewport: clonedViewport,
  9058. annotationLayer: this.#annotationLayer,
  9059. textLayer: this.#textLayer,
  9060. drawLayer: this.#drawLayer
  9061. });
  9062. const parameters = {
  9063. viewport: clonedViewport,
  9064. div,
  9065. annotations: null,
  9066. intent
  9067. };
  9068. this.annotationEditorLayer.render(parameters);
  9069. this.show();
  9070. }
  9071. cancel() {
  9072. this._cancelled = true;
  9073. if (!this.div) {
  9074. return;
  9075. }
  9076. this.annotationEditorLayer.destroy();
  9077. }
  9078. hide() {
  9079. if (!this.div) {
  9080. return;
  9081. }
  9082. this.annotationEditorLayer.pause(true);
  9083. this.div.hidden = true;
  9084. }
  9085. show() {
  9086. if (!this.div || this.annotationEditorLayer.isInvisible) {
  9087. return;
  9088. }
  9089. this.div.hidden = false;
  9090. this.annotationEditorLayer.pause(false);
  9091. }
  9092. }
  9093. ;// ./web/annotation_layer_builder.js
  9094. class AnnotationLayerBuilder {
  9095. #annotations = null;
  9096. #externalHide = false;
  9097. #onAppend = null;
  9098. #eventAbortController = null;
  9099. #linksInjected = false;
  9100. constructor({
  9101. pdfPage,
  9102. linkService,
  9103. downloadManager,
  9104. annotationStorage = null,
  9105. imageResourcesPath = "",
  9106. renderForms = true,
  9107. enableScripting = false,
  9108. hasJSActionsPromise = null,
  9109. fieldObjectsPromise = null,
  9110. annotationCanvasMap = null,
  9111. accessibilityManager = null,
  9112. annotationEditorUIManager = null,
  9113. onAppend = null
  9114. }) {
  9115. this.pdfPage = pdfPage;
  9116. this.linkService = linkService;
  9117. this.downloadManager = downloadManager;
  9118. this.imageResourcesPath = imageResourcesPath;
  9119. this.renderForms = renderForms;
  9120. this.annotationStorage = annotationStorage;
  9121. this.enableScripting = enableScripting;
  9122. this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false);
  9123. this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null);
  9124. this._annotationCanvasMap = annotationCanvasMap;
  9125. this._accessibilityManager = accessibilityManager;
  9126. this._annotationEditorUIManager = annotationEditorUIManager;
  9127. this.#onAppend = onAppend;
  9128. this.annotationLayer = null;
  9129. this.div = null;
  9130. this._cancelled = false;
  9131. this._eventBus = linkService.eventBus;
  9132. }
  9133. async render({
  9134. viewport,
  9135. intent = "display",
  9136. structTreeLayer = null
  9137. }) {
  9138. if (this.div) {
  9139. if (this._cancelled || !this.annotationLayer) {
  9140. return;
  9141. }
  9142. this.annotationLayer.update({
  9143. viewport: viewport.clone({
  9144. dontFlip: true
  9145. })
  9146. });
  9147. return;
  9148. }
  9149. const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({
  9150. intent
  9151. }), this._hasJSActionsPromise, this._fieldObjectsPromise]);
  9152. if (this._cancelled) {
  9153. return;
  9154. }
  9155. const div = this.div = document.createElement("div");
  9156. div.className = "annotationLayer";
  9157. this.#onAppend?.(div);
  9158. if (annotations.length === 0) {
  9159. this.#annotations = annotations;
  9160. this.hide(true);
  9161. return;
  9162. }
  9163. this.#initAnnotationLayer(viewport, structTreeLayer);
  9164. await this.annotationLayer.render({
  9165. annotations,
  9166. imageResourcesPath: this.imageResourcesPath,
  9167. renderForms: this.renderForms,
  9168. linkService: this.linkService,
  9169. downloadManager: this.downloadManager,
  9170. annotationStorage: this.annotationStorage,
  9171. enableScripting: this.enableScripting,
  9172. hasJSActions,
  9173. fieldObjects
  9174. });
  9175. this.#annotations = annotations;
  9176. if (this.linkService.isInPresentationMode) {
  9177. this.#updatePresentationModeState(PresentationModeState.FULLSCREEN);
  9178. }
  9179. if (!this.#eventAbortController) {
  9180. this.#eventAbortController = new AbortController();
  9181. this._eventBus?._on("presentationmodechanged", evt => {
  9182. this.#updatePresentationModeState(evt.state);
  9183. }, {
  9184. signal: this.#eventAbortController.signal
  9185. });
  9186. }
  9187. }
  9188. #initAnnotationLayer(viewport, structTreeLayer) {
  9189. this.annotationLayer = new AnnotationLayer({
  9190. div: this.div,
  9191. accessibilityManager: this._accessibilityManager,
  9192. annotationCanvasMap: this._annotationCanvasMap,
  9193. annotationEditorUIManager: this._annotationEditorUIManager,
  9194. page: this.pdfPage,
  9195. viewport: viewport.clone({
  9196. dontFlip: true
  9197. }),
  9198. structTreeLayer
  9199. });
  9200. }
  9201. cancel() {
  9202. this._cancelled = true;
  9203. this.#eventAbortController?.abort();
  9204. this.#eventAbortController = null;
  9205. }
  9206. hide(internal = false) {
  9207. this.#externalHide = !internal;
  9208. if (!this.div) {
  9209. return;
  9210. }
  9211. this.div.hidden = true;
  9212. }
  9213. hasEditableAnnotations() {
  9214. return !!this.annotationLayer?.hasEditableAnnotations();
  9215. }
  9216. async injectLinkAnnotations({
  9217. inferredLinks,
  9218. viewport,
  9219. structTreeLayer = null
  9220. }) {
  9221. if (this.#annotations === null) {
  9222. throw new Error("`render` method must be called before `injectLinkAnnotations`.");
  9223. }
  9224. if (this._cancelled || this.#linksInjected) {
  9225. return;
  9226. }
  9227. this.#linksInjected = true;
  9228. const newLinks = this.#annotations.length ? this.#checkInferredLinks(inferredLinks) : inferredLinks;
  9229. if (!newLinks.length) {
  9230. return;
  9231. }
  9232. if (!this.annotationLayer) {
  9233. this.#initAnnotationLayer(viewport, structTreeLayer);
  9234. setLayerDimensions(this.div, viewport);
  9235. }
  9236. await this.annotationLayer.addLinkAnnotations(newLinks, this.linkService);
  9237. if (!this.#externalHide) {
  9238. this.div.hidden = false;
  9239. }
  9240. }
  9241. #updatePresentationModeState(state) {
  9242. if (!this.div) {
  9243. return;
  9244. }
  9245. let disableFormElements = false;
  9246. switch (state) {
  9247. case PresentationModeState.FULLSCREEN:
  9248. disableFormElements = true;
  9249. break;
  9250. case PresentationModeState.NORMAL:
  9251. break;
  9252. default:
  9253. return;
  9254. }
  9255. for (const section of this.div.childNodes) {
  9256. if (section.hasAttribute("data-internal-link")) {
  9257. continue;
  9258. }
  9259. section.inert = disableFormElements;
  9260. }
  9261. }
  9262. #checkInferredLinks(inferredLinks) {
  9263. function annotationRects(annot) {
  9264. if (!annot.quadPoints) {
  9265. return [annot.rect];
  9266. }
  9267. const rects = [];
  9268. for (let i = 2, ii = annot.quadPoints.length; i < ii; i += 8) {
  9269. const trX = annot.quadPoints[i];
  9270. const trY = annot.quadPoints[i + 1];
  9271. const blX = annot.quadPoints[i + 2];
  9272. const blY = annot.quadPoints[i + 3];
  9273. rects.push([blX, blY, trX, trY]);
  9274. }
  9275. return rects;
  9276. }
  9277. function intersectAnnotations(annot1, annot2) {
  9278. const intersections = [];
  9279. const annot1Rects = annotationRects(annot1);
  9280. const annot2Rects = annotationRects(annot2);
  9281. for (const rect1 of annot1Rects) {
  9282. for (const rect2 of annot2Rects) {
  9283. const intersection = Util.intersect(rect1, rect2);
  9284. if (intersection) {
  9285. intersections.push(intersection);
  9286. }
  9287. }
  9288. }
  9289. return intersections;
  9290. }
  9291. function areaRects(rects) {
  9292. let totalArea = 0;
  9293. for (const rect of rects) {
  9294. totalArea += Math.abs((rect[2] - rect[0]) * (rect[3] - rect[1]));
  9295. }
  9296. return totalArea;
  9297. }
  9298. return inferredLinks.filter(link => {
  9299. let linkAreaRects;
  9300. for (const annotation of this.#annotations) {
  9301. if (annotation.annotationType !== AnnotationType.LINK || !annotation.url) {
  9302. continue;
  9303. }
  9304. const intersections = intersectAnnotations(annotation, link);
  9305. if (intersections.length === 0) {
  9306. continue;
  9307. }
  9308. linkAreaRects ??= areaRects(annotationRects(link));
  9309. if (areaRects(intersections) / linkAreaRects > 0.5) {
  9310. return false;
  9311. }
  9312. }
  9313. return true;
  9314. });
  9315. }
  9316. }
  9317. ;// ./web/autolinker.js
  9318. function DOMRectToPDF({
  9319. width,
  9320. height,
  9321. left,
  9322. top
  9323. }, pdfPageView) {
  9324. if (width === 0 || height === 0) {
  9325. return null;
  9326. }
  9327. const pageBox = pdfPageView.textLayer.div.getBoundingClientRect();
  9328. const bottomLeft = pdfPageView.getPagePoint(left - pageBox.left, top - pageBox.top);
  9329. const topRight = pdfPageView.getPagePoint(left - pageBox.left + width, top - pageBox.top + height);
  9330. return Util.normalizeRect([bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]]);
  9331. }
  9332. function calculateLinkPosition(range, pdfPageView) {
  9333. const rangeRects = range.getClientRects();
  9334. if (rangeRects.length === 1) {
  9335. return {
  9336. rect: DOMRectToPDF(rangeRects[0], pdfPageView)
  9337. };
  9338. }
  9339. const rect = [Infinity, Infinity, -Infinity, -Infinity];
  9340. const quadPoints = [];
  9341. let i = 0;
  9342. for (const domRect of rangeRects) {
  9343. const normalized = DOMRectToPDF(domRect, pdfPageView);
  9344. if (normalized === null) {
  9345. continue;
  9346. }
  9347. quadPoints[i] = quadPoints[i + 4] = normalized[0];
  9348. quadPoints[i + 1] = quadPoints[i + 3] = normalized[3];
  9349. quadPoints[i + 2] = quadPoints[i + 6] = normalized[2];
  9350. quadPoints[i + 5] = quadPoints[i + 7] = normalized[1];
  9351. Util.rectBoundingBox(...normalized, rect);
  9352. i += 8;
  9353. }
  9354. return {
  9355. quadPoints,
  9356. rect
  9357. };
  9358. }
  9359. function textPosition(container, offset) {
  9360. let currentContainer = container;
  9361. do {
  9362. if (currentContainer.nodeType === Node.TEXT_NODE) {
  9363. const currentLength = currentContainer.textContent.length;
  9364. if (offset <= currentLength) {
  9365. return [currentContainer, offset];
  9366. }
  9367. offset -= currentLength;
  9368. } else if (currentContainer.firstChild) {
  9369. currentContainer = currentContainer.firstChild;
  9370. continue;
  9371. }
  9372. while (!currentContainer.nextSibling && currentContainer !== container) {
  9373. currentContainer = currentContainer.parentNode;
  9374. }
  9375. if (currentContainer !== container) {
  9376. currentContainer = currentContainer.nextSibling;
  9377. }
  9378. } while (currentContainer !== container);
  9379. throw new Error("Offset is bigger than container's contents length.");
  9380. }
  9381. function createLinkAnnotation({
  9382. url,
  9383. index,
  9384. length
  9385. }, pdfPageView, id) {
  9386. const highlighter = pdfPageView._textHighlighter;
  9387. const [{
  9388. begin,
  9389. end
  9390. }] = highlighter._convertMatches([index], [length]);
  9391. const range = new Range();
  9392. range.setStart(...textPosition(highlighter.textDivs[begin.divIdx], begin.offset));
  9393. range.setEnd(...textPosition(highlighter.textDivs[end.divIdx], end.offset));
  9394. return {
  9395. id: `inferred_link_${id}`,
  9396. unsafeUrl: url,
  9397. url,
  9398. annotationType: AnnotationType.LINK,
  9399. rotation: 0,
  9400. ...calculateLinkPosition(range, pdfPageView),
  9401. borderStyle: null
  9402. };
  9403. }
  9404. class Autolinker {
  9405. static #index = 0;
  9406. static #regex;
  9407. static findLinks(text) {
  9408. this.#regex ??= /\b(?:https?:\/\/|mailto:|www\.)(?:[\S--[\p{P}<>]]|\/|[\S--[\[\]]]+[\S--[\p{P}<>]])+|\b[\S--[@\p{Ps}\p{Pe}<>]]+@([\S--[\p{P}<>]]+(?:\.[\S--[\p{P}<>]]+)+)/gmv;
  9409. const [normalizedText, diffs] = normalize(text);
  9410. const matches = normalizedText.matchAll(this.#regex);
  9411. const links = [];
  9412. for (const match of matches) {
  9413. const [url, emailDomain] = match;
  9414. let raw;
  9415. if (url.startsWith("www.") || url.startsWith("http://") || url.startsWith("https://")) {
  9416. raw = url;
  9417. } else if (URL.canParse(`http://${emailDomain}`)) {
  9418. raw = url.startsWith("mailto:") ? url : `mailto:${url}`;
  9419. } else {
  9420. continue;
  9421. }
  9422. const absoluteURL = createValidAbsoluteUrl(raw, null, {
  9423. addDefaultProtocol: true
  9424. });
  9425. if (absoluteURL) {
  9426. const [index, length] = getOriginalIndex(diffs, match.index, url.length);
  9427. links.push({
  9428. url: absoluteURL.href,
  9429. index,
  9430. length
  9431. });
  9432. }
  9433. }
  9434. return links;
  9435. }
  9436. static processLinks(pdfPageView) {
  9437. return this.findLinks(pdfPageView._textHighlighter.textContentItemsStr.join("\n")).map(link => createLinkAnnotation(link, pdfPageView, this.#index++));
  9438. }
  9439. }
  9440. ;// ./web/base_pdf_page_view.js
  9441. class BasePDFPageView {
  9442. #enableHWA = false;
  9443. #loadingId = null;
  9444. #renderError = null;
  9445. #renderingState = RenderingStates.INITIAL;
  9446. #showCanvas = null;
  9447. canvas = null;
  9448. div = null;
  9449. eventBus = null;
  9450. id = null;
  9451. pageColors = null;
  9452. renderingQueue = null;
  9453. renderTask = null;
  9454. resume = null;
  9455. constructor(options) {
  9456. this.#enableHWA = #enableHWA in options ? options.#enableHWA : options.enableHWA || false;
  9457. this.eventBus = options.eventBus;
  9458. this.id = options.id;
  9459. this.pageColors = options.pageColors || null;
  9460. this.renderingQueue = options.renderingQueue;
  9461. }
  9462. get renderingState() {
  9463. return this.#renderingState;
  9464. }
  9465. set renderingState(state) {
  9466. if (state === this.#renderingState) {
  9467. return;
  9468. }
  9469. this.#renderingState = state;
  9470. if (this.#loadingId) {
  9471. clearTimeout(this.#loadingId);
  9472. this.#loadingId = null;
  9473. }
  9474. switch (state) {
  9475. case RenderingStates.PAUSED:
  9476. this.div.classList.remove("loading");
  9477. break;
  9478. case RenderingStates.RUNNING:
  9479. this.div.classList.add("loadingIcon");
  9480. this.#loadingId = setTimeout(() => {
  9481. this.div.classList.add("loading");
  9482. this.#loadingId = null;
  9483. }, 0);
  9484. break;
  9485. case RenderingStates.INITIAL:
  9486. case RenderingStates.FINISHED:
  9487. this.div.classList.remove("loadingIcon", "loading");
  9488. break;
  9489. }
  9490. }
  9491. _createCanvas(onShow, hideUntilComplete = false) {
  9492. const {
  9493. pageColors
  9494. } = this;
  9495. const hasHCM = !!(pageColors?.background && pageColors?.foreground);
  9496. const prevCanvas = this.canvas;
  9497. const updateOnFirstShow = !prevCanvas && !hasHCM && !hideUntilComplete;
  9498. const canvas = this.canvas = document.createElement("canvas");
  9499. this.#showCanvas = isLastShow => {
  9500. if (updateOnFirstShow) {
  9501. onShow(canvas);
  9502. this.#showCanvas = null;
  9503. return;
  9504. }
  9505. if (!isLastShow) {
  9506. return;
  9507. }
  9508. if (prevCanvas) {
  9509. prevCanvas.replaceWith(canvas);
  9510. prevCanvas.width = prevCanvas.height = 0;
  9511. } else {
  9512. onShow(canvas);
  9513. }
  9514. };
  9515. const ctx = canvas.getContext("2d", {
  9516. alpha: false,
  9517. willReadFrequently: !this.#enableHWA
  9518. });
  9519. return {
  9520. canvas,
  9521. prevCanvas,
  9522. ctx
  9523. };
  9524. }
  9525. #renderContinueCallback = cont => {
  9526. this.#showCanvas?.(false);
  9527. if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) {
  9528. this.renderingState = RenderingStates.PAUSED;
  9529. this.resume = () => {
  9530. this.renderingState = RenderingStates.RUNNING;
  9531. cont();
  9532. };
  9533. return;
  9534. }
  9535. cont();
  9536. };
  9537. _resetCanvas() {
  9538. const {
  9539. canvas
  9540. } = this;
  9541. if (!canvas) {
  9542. return;
  9543. }
  9544. canvas.remove();
  9545. canvas.width = canvas.height = 0;
  9546. this.canvas = null;
  9547. }
  9548. async _drawCanvas(options, onCancel, onFinish) {
  9549. const renderTask = this.renderTask = this.pdfPage.render(options);
  9550. renderTask.onContinue = this.#renderContinueCallback;
  9551. renderTask.onError = error => {
  9552. if (error instanceof RenderingCancelledException) {
  9553. onCancel();
  9554. this.#renderError = null;
  9555. }
  9556. };
  9557. let error = null;
  9558. try {
  9559. await renderTask.promise;
  9560. this.#showCanvas?.(true);
  9561. } catch (e) {
  9562. if (e instanceof RenderingCancelledException) {
  9563. return;
  9564. }
  9565. error = e;
  9566. this.#showCanvas?.(true);
  9567. } finally {
  9568. this.#renderError = error;
  9569. if (renderTask === this.renderTask) {
  9570. this.renderTask = null;
  9571. }
  9572. }
  9573. this.renderingState = RenderingStates.FINISHED;
  9574. onFinish(renderTask);
  9575. if (error) {
  9576. throw error;
  9577. }
  9578. }
  9579. cancelRendering({
  9580. cancelExtraDelay = 0
  9581. } = {}) {
  9582. if (this.renderTask) {
  9583. this.renderTask.cancel(cancelExtraDelay);
  9584. this.renderTask = null;
  9585. }
  9586. this.resume = null;
  9587. }
  9588. dispatchPageRender() {
  9589. this.eventBus.dispatch("pagerender", {
  9590. source: this,
  9591. pageNumber: this.id
  9592. });
  9593. }
  9594. dispatchPageRendered(cssTransform, isDetailView) {
  9595. this.eventBus.dispatch("pagerendered", {
  9596. source: this,
  9597. pageNumber: this.id,
  9598. cssTransform,
  9599. isDetailView,
  9600. timestamp: performance.now(),
  9601. error: this.#renderError
  9602. });
  9603. }
  9604. }
  9605. ;// ./web/draw_layer_builder.js
  9606. class DrawLayerBuilder {
  9607. #drawLayer = null;
  9608. constructor(options) {
  9609. this.pageIndex = options.pageIndex;
  9610. }
  9611. async render({
  9612. intent = "display"
  9613. }) {
  9614. if (intent !== "display" || this.#drawLayer || this._cancelled) {
  9615. return;
  9616. }
  9617. this.#drawLayer = new DrawLayer({
  9618. pageIndex: this.pageIndex
  9619. });
  9620. }
  9621. cancel() {
  9622. this._cancelled = true;
  9623. if (!this.#drawLayer) {
  9624. return;
  9625. }
  9626. this.#drawLayer.destroy();
  9627. this.#drawLayer = null;
  9628. }
  9629. setParent(parent) {
  9630. this.#drawLayer?.setParent(parent);
  9631. }
  9632. getDrawLayer() {
  9633. return this.#drawLayer;
  9634. }
  9635. }
  9636. ;// ./web/pdf_page_detail_view.js
  9637. class PDFPageDetailView extends BasePDFPageView {
  9638. #detailArea = null;
  9639. renderingCancelled = false;
  9640. constructor({
  9641. pageView
  9642. }) {
  9643. super(pageView);
  9644. this.pageView = pageView;
  9645. this.renderingId = "detail" + this.id;
  9646. this.div = pageView.div;
  9647. }
  9648. setPdfPage(pdfPage) {
  9649. this.pageView.setPdfPage(pdfPage);
  9650. }
  9651. get pdfPage() {
  9652. return this.pageView.pdfPage;
  9653. }
  9654. get renderingState() {
  9655. return super.renderingState;
  9656. }
  9657. set renderingState(value) {
  9658. this.renderingCancelled = false;
  9659. super.renderingState = value;
  9660. }
  9661. reset({
  9662. keepCanvas = false
  9663. } = {}) {
  9664. const renderingCancelled = this.renderingCancelled || this.renderingState === RenderingStates.RUNNING || this.renderingState === RenderingStates.PAUSED;
  9665. this.cancelRendering();
  9666. this.renderingState = RenderingStates.INITIAL;
  9667. this.renderingCancelled = renderingCancelled;
  9668. if (!keepCanvas) {
  9669. this._resetCanvas();
  9670. }
  9671. }
  9672. #shouldRenderDifferentArea(visibleArea) {
  9673. if (!this.#detailArea) {
  9674. return true;
  9675. }
  9676. const minDetailX = this.#detailArea.minX;
  9677. const minDetailY = this.#detailArea.minY;
  9678. const maxDetailX = this.#detailArea.width + minDetailX;
  9679. const maxDetailY = this.#detailArea.height + minDetailY;
  9680. if (visibleArea.minX < minDetailX || visibleArea.minY < minDetailY || visibleArea.maxX > maxDetailX || visibleArea.maxY > maxDetailY) {
  9681. return true;
  9682. }
  9683. const {
  9684. width: maxWidth,
  9685. height: maxHeight,
  9686. scale
  9687. } = this.pageView.viewport;
  9688. if (this.#detailArea.scale !== scale) {
  9689. return true;
  9690. }
  9691. const paddingLeftSize = visibleArea.minX - minDetailX;
  9692. const paddingRightSize = maxDetailX - visibleArea.maxX;
  9693. const paddingTopSize = visibleArea.minY - minDetailY;
  9694. const paddingBottomSize = maxDetailY - visibleArea.maxY;
  9695. const MOVEMENT_THRESHOLD = 0.5;
  9696. const ratio = (1 + MOVEMENT_THRESHOLD) / MOVEMENT_THRESHOLD;
  9697. if (minDetailX > 0 && paddingRightSize / paddingLeftSize > ratio || maxDetailX < maxWidth && paddingLeftSize / paddingRightSize > ratio || minDetailY > 0 && paddingBottomSize / paddingTopSize > ratio || maxDetailY < maxHeight && paddingTopSize / paddingBottomSize > ratio) {
  9698. return true;
  9699. }
  9700. return false;
  9701. }
  9702. update({
  9703. visibleArea = null,
  9704. underlyingViewUpdated = false
  9705. } = {}) {
  9706. if (underlyingViewUpdated) {
  9707. this.cancelRendering();
  9708. this.renderingState = RenderingStates.INITIAL;
  9709. return;
  9710. }
  9711. if (!this.#shouldRenderDifferentArea(visibleArea)) {
  9712. return;
  9713. }
  9714. const {
  9715. viewport,
  9716. maxCanvasPixels
  9717. } = this.pageView;
  9718. const visibleWidth = visibleArea.maxX - visibleArea.minX;
  9719. const visibleHeight = visibleArea.maxY - visibleArea.minY;
  9720. const visiblePixels = visibleWidth * visibleHeight * OutputScale.pixelRatio ** 2;
  9721. const maxDetailToVisibleLinearRatio = Math.sqrt(maxCanvasPixels / visiblePixels);
  9722. const maxOverflowScale = (maxDetailToVisibleLinearRatio - 1) / 2;
  9723. let overflowScale = Math.min(1, maxOverflowScale);
  9724. if (overflowScale < 0) {
  9725. overflowScale = 0;
  9726. }
  9727. const overflowWidth = visibleWidth * overflowScale;
  9728. const overflowHeight = visibleHeight * overflowScale;
  9729. const minX = Math.max(0, visibleArea.minX - overflowWidth);
  9730. const maxX = Math.min(viewport.width, visibleArea.maxX + overflowWidth);
  9731. const minY = Math.max(0, visibleArea.minY - overflowHeight);
  9732. const maxY = Math.min(viewport.height, visibleArea.maxY + overflowHeight);
  9733. const width = maxX - minX;
  9734. const height = maxY - minY;
  9735. this.#detailArea = {
  9736. minX,
  9737. minY,
  9738. width,
  9739. height,
  9740. scale: viewport.scale
  9741. };
  9742. this.reset({
  9743. keepCanvas: true
  9744. });
  9745. }
  9746. async draw() {
  9747. if (this.pageView.detailView !== this) {
  9748. return undefined;
  9749. }
  9750. const hideUntilComplete = this.pageView.renderingState === RenderingStates.FINISHED || this.renderingState === RenderingStates.FINISHED;
  9751. if (this.renderingState !== RenderingStates.INITIAL) {
  9752. console.error("Must be in new state before drawing");
  9753. this.reset();
  9754. }
  9755. const {
  9756. div,
  9757. pdfPage,
  9758. viewport
  9759. } = this.pageView;
  9760. if (!pdfPage) {
  9761. this.renderingState = RenderingStates.FINISHED;
  9762. throw new Error("pdfPage is not loaded");
  9763. }
  9764. this.renderingState = RenderingStates.RUNNING;
  9765. const canvasWrapper = this.pageView._ensureCanvasWrapper();
  9766. const {
  9767. canvas,
  9768. prevCanvas,
  9769. ctx
  9770. } = this._createCanvas(newCanvas => {
  9771. if (canvasWrapper.firstElementChild?.tagName === "CANVAS") {
  9772. canvasWrapper.firstElementChild.after(newCanvas);
  9773. } else {
  9774. canvasWrapper.prepend(newCanvas);
  9775. }
  9776. }, hideUntilComplete);
  9777. canvas.setAttribute("aria-hidden", "true");
  9778. const {
  9779. width,
  9780. height
  9781. } = viewport;
  9782. const area = this.#detailArea;
  9783. const {
  9784. pixelRatio
  9785. } = OutputScale;
  9786. const transform = [pixelRatio, 0, 0, pixelRatio, -area.minX * pixelRatio, -area.minY * pixelRatio];
  9787. canvas.width = area.width * pixelRatio;
  9788. canvas.height = area.height * pixelRatio;
  9789. const {
  9790. style
  9791. } = canvas;
  9792. style.width = `${area.width * 100 / width}%`;
  9793. style.height = `${area.height * 100 / height}%`;
  9794. style.top = `${area.minY * 100 / height}%`;
  9795. style.left = `${area.minX * 100 / width}%`;
  9796. const renderingPromise = this._drawCanvas(this.pageView._getRenderingContext(ctx, transform), () => {
  9797. this.canvas?.remove();
  9798. this.canvas = prevCanvas;
  9799. }, () => {
  9800. this.dispatchPageRendered(false, true);
  9801. });
  9802. div.setAttribute("data-loaded", true);
  9803. this.dispatchPageRender();
  9804. return renderingPromise;
  9805. }
  9806. }
  9807. ;// ./web/struct_tree_layer_builder.js
  9808. const PDF_ROLE_TO_HTML_ROLE = {
  9809. Document: null,
  9810. DocumentFragment: null,
  9811. Part: "group",
  9812. Sect: "group",
  9813. Div: "group",
  9814. Aside: "note",
  9815. NonStruct: "none",
  9816. P: null,
  9817. H: "heading",
  9818. Title: null,
  9819. FENote: "note",
  9820. Sub: "group",
  9821. Lbl: null,
  9822. Span: null,
  9823. Em: null,
  9824. Strong: null,
  9825. Link: "link",
  9826. Annot: "note",
  9827. Form: "form",
  9828. Ruby: null,
  9829. RB: null,
  9830. RT: null,
  9831. RP: null,
  9832. Warichu: null,
  9833. WT: null,
  9834. WP: null,
  9835. L: "list",
  9836. LI: "listitem",
  9837. LBody: null,
  9838. Table: "table",
  9839. TR: "row",
  9840. TH: "columnheader",
  9841. TD: "cell",
  9842. THead: "columnheader",
  9843. TBody: null,
  9844. TFoot: null,
  9845. Caption: null,
  9846. Figure: "figure",
  9847. Formula: null,
  9848. Artifact: null
  9849. };
  9850. const HEADING_PATTERN = /^H(\d+)$/;
  9851. class StructTreeLayerBuilder {
  9852. #promise;
  9853. #treeDom = null;
  9854. #treePromise;
  9855. #elementAttributes = new Map();
  9856. #rawDims;
  9857. #elementsToAddToTextLayer = null;
  9858. constructor(pdfPage, rawDims) {
  9859. this.#promise = pdfPage.getStructTree();
  9860. this.#rawDims = rawDims;
  9861. }
  9862. async render() {
  9863. if (this.#treePromise) {
  9864. return this.#treePromise;
  9865. }
  9866. const {
  9867. promise,
  9868. resolve,
  9869. reject
  9870. } = Promise.withResolvers();
  9871. this.#treePromise = promise;
  9872. try {
  9873. this.#treeDom = this.#walk(await this.#promise);
  9874. } catch (ex) {
  9875. reject(ex);
  9876. }
  9877. this.#promise = null;
  9878. this.#treeDom?.classList.add("structTree");
  9879. resolve(this.#treeDom);
  9880. return promise;
  9881. }
  9882. async getAriaAttributes(annotationId) {
  9883. try {
  9884. await this.render();
  9885. return this.#elementAttributes.get(annotationId);
  9886. } catch {}
  9887. return null;
  9888. }
  9889. hide() {
  9890. if (this.#treeDom && !this.#treeDom.hidden) {
  9891. this.#treeDom.hidden = true;
  9892. }
  9893. }
  9894. show() {
  9895. if (this.#treeDom?.hidden) {
  9896. this.#treeDom.hidden = false;
  9897. }
  9898. }
  9899. #setAttributes(structElement, htmlElement) {
  9900. const {
  9901. alt,
  9902. id,
  9903. lang
  9904. } = structElement;
  9905. if (alt !== undefined) {
  9906. let added = false;
  9907. const label = removeNullCharacters(alt);
  9908. for (const child of structElement.children) {
  9909. if (child.type === "annotation") {
  9910. let attrs = this.#elementAttributes.get(child.id);
  9911. if (!attrs) {
  9912. attrs = new Map();
  9913. this.#elementAttributes.set(child.id, attrs);
  9914. }
  9915. attrs.set("aria-label", label);
  9916. added = true;
  9917. }
  9918. }
  9919. if (!added) {
  9920. htmlElement.setAttribute("aria-label", label);
  9921. }
  9922. }
  9923. if (id !== undefined) {
  9924. htmlElement.setAttribute("aria-owns", id);
  9925. }
  9926. if (lang !== undefined) {
  9927. htmlElement.setAttribute("lang", removeNullCharacters(lang, true));
  9928. }
  9929. }
  9930. #addImageInTextLayer(node, element) {
  9931. const {
  9932. alt,
  9933. bbox,
  9934. children
  9935. } = node;
  9936. const child = children?.[0];
  9937. if (!this.#rawDims || !alt || !bbox || child?.type !== "content") {
  9938. return false;
  9939. }
  9940. const {
  9941. id
  9942. } = child;
  9943. if (!id) {
  9944. return false;
  9945. }
  9946. element.setAttribute("aria-owns", id);
  9947. const img = document.createElement("span");
  9948. (this.#elementsToAddToTextLayer ||= new Map()).set(id, img);
  9949. img.setAttribute("role", "img");
  9950. img.setAttribute("aria-label", removeNullCharacters(alt));
  9951. const {
  9952. pageHeight,
  9953. pageX,
  9954. pageY
  9955. } = this.#rawDims;
  9956. const calc = "calc(var(--total-scale-factor) *";
  9957. const {
  9958. style
  9959. } = img;
  9960. style.width = `${calc}${bbox[2] - bbox[0]}px)`;
  9961. style.height = `${calc}${bbox[3] - bbox[1]}px)`;
  9962. style.left = `${calc}${bbox[0] - pageX}px)`;
  9963. style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`;
  9964. return true;
  9965. }
  9966. addElementsToTextLayer() {
  9967. if (!this.#elementsToAddToTextLayer) {
  9968. return;
  9969. }
  9970. for (const [id, img] of this.#elementsToAddToTextLayer) {
  9971. document.getElementById(id)?.append(img);
  9972. }
  9973. this.#elementsToAddToTextLayer.clear();
  9974. this.#elementsToAddToTextLayer = null;
  9975. }
  9976. #walk(node) {
  9977. if (!node) {
  9978. return null;
  9979. }
  9980. const element = document.createElement("span");
  9981. if ("role" in node) {
  9982. const {
  9983. role
  9984. } = node;
  9985. const match = role.match(HEADING_PATTERN);
  9986. if (match) {
  9987. element.setAttribute("role", "heading");
  9988. element.setAttribute("aria-level", match[1]);
  9989. } else if (PDF_ROLE_TO_HTML_ROLE[role]) {
  9990. element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]);
  9991. }
  9992. if (role === "Figure" && this.#addImageInTextLayer(node, element)) {
  9993. return element;
  9994. }
  9995. }
  9996. this.#setAttributes(node, element);
  9997. if (node.children) {
  9998. if (node.children.length === 1 && "id" in node.children[0]) {
  9999. this.#setAttributes(node.children[0], element);
  10000. } else {
  10001. for (const kid of node.children) {
  10002. element.append(this.#walk(kid));
  10003. }
  10004. }
  10005. }
  10006. return element;
  10007. }
  10008. }
  10009. ;// ./web/text_accessibility.js
  10010. class TextAccessibilityManager {
  10011. #enabled = false;
  10012. #textChildren = null;
  10013. #textNodes = new Map();
  10014. #waitingElements = new Map();
  10015. setTextMapping(textDivs) {
  10016. this.#textChildren = textDivs;
  10017. }
  10018. static #compareElementPositions(e1, e2) {
  10019. const rect1 = e1.getBoundingClientRect();
  10020. const rect2 = e2.getBoundingClientRect();
  10021. if (rect1.width === 0 && rect1.height === 0) {
  10022. return +1;
  10023. }
  10024. if (rect2.width === 0 && rect2.height === 0) {
  10025. return -1;
  10026. }
  10027. const top1 = rect1.y;
  10028. const bot1 = rect1.y + rect1.height;
  10029. const mid1 = rect1.y + rect1.height / 2;
  10030. const top2 = rect2.y;
  10031. const bot2 = rect2.y + rect2.height;
  10032. const mid2 = rect2.y + rect2.height / 2;
  10033. if (mid1 <= top2 && mid2 >= bot1) {
  10034. return -1;
  10035. }
  10036. if (mid2 <= top1 && mid1 >= bot2) {
  10037. return +1;
  10038. }
  10039. const centerX1 = rect1.x + rect1.width / 2;
  10040. const centerX2 = rect2.x + rect2.width / 2;
  10041. return centerX1 - centerX2;
  10042. }
  10043. enable() {
  10044. if (this.#enabled) {
  10045. throw new Error("TextAccessibilityManager is already enabled.");
  10046. }
  10047. if (!this.#textChildren) {
  10048. throw new Error("Text divs and strings have not been set.");
  10049. }
  10050. this.#enabled = true;
  10051. this.#textChildren = this.#textChildren.slice();
  10052. this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions);
  10053. if (this.#textNodes.size > 0) {
  10054. const textChildren = this.#textChildren;
  10055. for (const [id, nodeIndex] of this.#textNodes) {
  10056. const element = document.getElementById(id);
  10057. if (!element) {
  10058. this.#textNodes.delete(id);
  10059. continue;
  10060. }
  10061. this.#addIdToAriaOwns(id, textChildren[nodeIndex]);
  10062. }
  10063. }
  10064. for (const [element, isRemovable] of this.#waitingElements) {
  10065. this.addPointerInTextLayer(element, isRemovable);
  10066. }
  10067. this.#waitingElements.clear();
  10068. }
  10069. disable() {
  10070. if (!this.#enabled) {
  10071. return;
  10072. }
  10073. this.#waitingElements.clear();
  10074. this.#textChildren = null;
  10075. this.#enabled = false;
  10076. }
  10077. removePointerInTextLayer(element) {
  10078. if (!this.#enabled) {
  10079. this.#waitingElements.delete(element);
  10080. return;
  10081. }
  10082. const children = this.#textChildren;
  10083. if (!children || children.length === 0) {
  10084. return;
  10085. }
  10086. const {
  10087. id
  10088. } = element;
  10089. const nodeIndex = this.#textNodes.get(id);
  10090. if (nodeIndex === undefined) {
  10091. return;
  10092. }
  10093. const node = children[nodeIndex];
  10094. this.#textNodes.delete(id);
  10095. let owns = node.getAttribute("aria-owns");
  10096. if (owns?.includes(id)) {
  10097. owns = owns.split(" ").filter(x => x !== id).join(" ");
  10098. if (owns) {
  10099. node.setAttribute("aria-owns", owns);
  10100. } else {
  10101. node.removeAttribute("aria-owns");
  10102. node.setAttribute("role", "presentation");
  10103. }
  10104. }
  10105. }
  10106. #addIdToAriaOwns(id, node) {
  10107. const owns = node.getAttribute("aria-owns");
  10108. if (!owns?.includes(id)) {
  10109. node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id);
  10110. }
  10111. node.removeAttribute("role");
  10112. }
  10113. addPointerInTextLayer(element, isRemovable) {
  10114. const {
  10115. id
  10116. } = element;
  10117. if (!id) {
  10118. return null;
  10119. }
  10120. if (!this.#enabled) {
  10121. this.#waitingElements.set(element, isRemovable);
  10122. return null;
  10123. }
  10124. if (isRemovable) {
  10125. this.removePointerInTextLayer(element);
  10126. }
  10127. const children = this.#textChildren;
  10128. if (!children || children.length === 0) {
  10129. return null;
  10130. }
  10131. const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0);
  10132. const nodeIndex = Math.max(0, index - 1);
  10133. const child = children[nodeIndex];
  10134. this.#addIdToAriaOwns(id, child);
  10135. this.#textNodes.set(id, nodeIndex);
  10136. const parent = child.parentNode;
  10137. return parent?.classList.contains("markedContent") ? parent.id : null;
  10138. }
  10139. moveElementInDOM(container, element, contentElement, isRemovable) {
  10140. const id = this.addPointerInTextLayer(contentElement, isRemovable);
  10141. if (!container.hasChildNodes()) {
  10142. container.append(element);
  10143. return id;
  10144. }
  10145. const children = Array.from(container.childNodes).filter(node => node !== element);
  10146. if (children.length === 0) {
  10147. return id;
  10148. }
  10149. const elementToCompare = contentElement || element;
  10150. const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0);
  10151. if (index === 0) {
  10152. children[0].before(element);
  10153. } else {
  10154. children[index - 1].after(element);
  10155. }
  10156. return id;
  10157. }
  10158. }
  10159. ;// ./web/text_highlighter.js
  10160. class TextHighlighter {
  10161. #eventAbortController = null;
  10162. constructor({
  10163. findController,
  10164. eventBus,
  10165. pageIndex
  10166. }) {
  10167. this.findController = findController;
  10168. this.matches = [];
  10169. this.eventBus = eventBus;
  10170. this.pageIdx = pageIndex;
  10171. this.textDivs = null;
  10172. this.textContentItemsStr = null;
  10173. this.enabled = false;
  10174. }
  10175. setTextMapping(divs, texts) {
  10176. this.textDivs = divs;
  10177. this.textContentItemsStr = texts;
  10178. }
  10179. enable() {
  10180. if (!this.textDivs || !this.textContentItemsStr) {
  10181. throw new Error("Text divs and strings have not been set.");
  10182. }
  10183. if (this.enabled) {
  10184. throw new Error("TextHighlighter is already enabled.");
  10185. }
  10186. this.enabled = true;
  10187. if (!this.#eventAbortController) {
  10188. this.#eventAbortController = new AbortController();
  10189. this.eventBus._on("updatetextlayermatches", evt => {
  10190. if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) {
  10191. this._updateMatches();
  10192. }
  10193. }, {
  10194. signal: this.#eventAbortController.signal
  10195. });
  10196. }
  10197. this._updateMatches();
  10198. }
  10199. disable() {
  10200. if (!this.enabled) {
  10201. return;
  10202. }
  10203. this.enabled = false;
  10204. this.#eventAbortController?.abort();
  10205. this.#eventAbortController = null;
  10206. this._updateMatches(true);
  10207. }
  10208. _convertMatches(matches, matchesLength) {
  10209. if (!matches) {
  10210. return [];
  10211. }
  10212. const {
  10213. textContentItemsStr
  10214. } = this;
  10215. let i = 0,
  10216. iIndex = 0;
  10217. const end = textContentItemsStr.length - 1;
  10218. const result = [];
  10219. for (let m = 0, mm = matches.length; m < mm; m++) {
  10220. let matchIdx = matches[m];
  10221. while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) {
  10222. iIndex += textContentItemsStr[i].length;
  10223. i++;
  10224. }
  10225. if (i === textContentItemsStr.length) {
  10226. console.error("Could not find a matching mapping");
  10227. }
  10228. const match = {
  10229. begin: {
  10230. divIdx: i,
  10231. offset: matchIdx - iIndex
  10232. }
  10233. };
  10234. matchIdx += matchesLength[m];
  10235. while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) {
  10236. iIndex += textContentItemsStr[i].length;
  10237. i++;
  10238. }
  10239. match.end = {
  10240. divIdx: i,
  10241. offset: matchIdx - iIndex
  10242. };
  10243. result.push(match);
  10244. }
  10245. return result;
  10246. }
  10247. _renderMatches(matches) {
  10248. if (matches.length === 0) {
  10249. return;
  10250. }
  10251. const {
  10252. findController,
  10253. pageIdx
  10254. } = this;
  10255. const {
  10256. textContentItemsStr,
  10257. textDivs
  10258. } = this;
  10259. const isSelectedPage = pageIdx === findController.selected.pageIdx;
  10260. const selectedMatchIdx = findController.selected.matchIdx;
  10261. const highlightAll = findController.state.highlightAll;
  10262. let prevEnd = null;
  10263. const infinity = {
  10264. divIdx: -1,
  10265. offset: undefined
  10266. };
  10267. function beginText(begin, className) {
  10268. const divIdx = begin.divIdx;
  10269. textDivs[divIdx].textContent = "";
  10270. return appendTextToDiv(divIdx, 0, begin.offset, className);
  10271. }
  10272. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  10273. let div = textDivs[divIdx];
  10274. if (div.nodeType === Node.TEXT_NODE) {
  10275. const span = document.createElement("span");
  10276. div.before(span);
  10277. span.append(div);
  10278. textDivs[divIdx] = span;
  10279. div = span;
  10280. }
  10281. const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
  10282. const node = document.createTextNode(content);
  10283. if (className) {
  10284. const span = document.createElement("span");
  10285. span.className = `${className} appended`;
  10286. span.append(node);
  10287. div.append(span);
  10288. if (className.includes("selected")) {
  10289. const {
  10290. left
  10291. } = span.getClientRects()[0];
  10292. const parentLeft = div.getBoundingClientRect().left;
  10293. return left - parentLeft;
  10294. }
  10295. return 0;
  10296. }
  10297. div.append(node);
  10298. return 0;
  10299. }
  10300. let i0 = selectedMatchIdx,
  10301. i1 = i0 + 1;
  10302. if (highlightAll) {
  10303. i0 = 0;
  10304. i1 = matches.length;
  10305. } else if (!isSelectedPage) {
  10306. return;
  10307. }
  10308. let lastDivIdx = -1;
  10309. let lastOffset = -1;
  10310. for (let i = i0; i < i1; i++) {
  10311. const match = matches[i];
  10312. const begin = match.begin;
  10313. if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) {
  10314. continue;
  10315. }
  10316. lastDivIdx = begin.divIdx;
  10317. lastOffset = begin.offset;
  10318. const end = match.end;
  10319. const isSelected = isSelectedPage && i === selectedMatchIdx;
  10320. const highlightSuffix = isSelected ? " selected" : "";
  10321. let selectedLeft = 0;
  10322. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  10323. if (prevEnd !== null) {
  10324. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  10325. }
  10326. beginText(begin);
  10327. } else {
  10328. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  10329. }
  10330. if (begin.divIdx === end.divIdx) {
  10331. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix);
  10332. } else {
  10333. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix);
  10334. for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  10335. textDivs[n0].className = "highlight middle" + highlightSuffix;
  10336. }
  10337. beginText(end, "highlight end" + highlightSuffix);
  10338. }
  10339. prevEnd = end;
  10340. if (isSelected) {
  10341. findController.scrollMatchIntoView({
  10342. element: textDivs[begin.divIdx],
  10343. selectedLeft,
  10344. pageIndex: pageIdx,
  10345. matchIndex: selectedMatchIdx
  10346. });
  10347. }
  10348. }
  10349. if (prevEnd) {
  10350. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  10351. }
  10352. }
  10353. _updateMatches(reset = false) {
  10354. if (!this.enabled && !reset) {
  10355. return;
  10356. }
  10357. const {
  10358. findController,
  10359. matches,
  10360. pageIdx
  10361. } = this;
  10362. const {
  10363. textContentItemsStr,
  10364. textDivs
  10365. } = this;
  10366. let clearedUntilDivIdx = -1;
  10367. for (const match of matches) {
  10368. const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  10369. for (let n = begin, end = match.end.divIdx; n <= end; n++) {
  10370. const div = textDivs[n];
  10371. div.textContent = textContentItemsStr[n];
  10372. div.className = "";
  10373. }
  10374. clearedUntilDivIdx = match.end.divIdx + 1;
  10375. }
  10376. if (!findController?.highlightMatches || reset) {
  10377. return;
  10378. }
  10379. const pageMatches = findController.pageMatches[pageIdx] || null;
  10380. const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null;
  10381. this.matches = this._convertMatches(pageMatches, pageMatchesLength);
  10382. this._renderMatches(this.matches);
  10383. }
  10384. }
  10385. ;// ./web/text_layer_builder.js
  10386. class TextLayerBuilder {
  10387. #enablePermissions = false;
  10388. #onAppend = null;
  10389. #renderingDone = false;
  10390. #textLayer = null;
  10391. static #textLayers = new Map();
  10392. static #selectionChangeAbortController = null;
  10393. constructor({
  10394. pdfPage,
  10395. highlighter = null,
  10396. accessibilityManager = null,
  10397. enablePermissions = false,
  10398. onAppend = null
  10399. }) {
  10400. this.pdfPage = pdfPage;
  10401. this.highlighter = highlighter;
  10402. this.accessibilityManager = accessibilityManager;
  10403. this.#enablePermissions = enablePermissions === true;
  10404. this.#onAppend = onAppend;
  10405. this.div = document.createElement("div");
  10406. this.div.tabIndex = 0;
  10407. this.div.className = "textLayer";
  10408. }
  10409. async render({
  10410. viewport,
  10411. textContentParams = null
  10412. }) {
  10413. if (this.#renderingDone && this.#textLayer) {
  10414. this.#textLayer.update({
  10415. viewport,
  10416. onBefore: this.hide.bind(this)
  10417. });
  10418. this.show();
  10419. return;
  10420. }
  10421. this.cancel();
  10422. this.#textLayer = new TextLayer({
  10423. textContentSource: this.pdfPage.streamTextContent(textContentParams || {
  10424. includeMarkedContent: true,
  10425. disableNormalization: true
  10426. }),
  10427. container: this.div,
  10428. viewport
  10429. });
  10430. const {
  10431. textDivs,
  10432. textContentItemsStr
  10433. } = this.#textLayer;
  10434. this.highlighter?.setTextMapping(textDivs, textContentItemsStr);
  10435. this.accessibilityManager?.setTextMapping(textDivs);
  10436. await this.#textLayer.render();
  10437. this.#renderingDone = true;
  10438. const endOfContent = document.createElement("div");
  10439. endOfContent.className = "endOfContent";
  10440. this.div.append(endOfContent);
  10441. this.#bindMouse(endOfContent);
  10442. this.#onAppend?.(this.div);
  10443. this.highlighter?.enable();
  10444. this.accessibilityManager?.enable();
  10445. }
  10446. hide() {
  10447. if (!this.div.hidden && this.#renderingDone) {
  10448. this.highlighter?.disable();
  10449. this.div.hidden = true;
  10450. }
  10451. }
  10452. show() {
  10453. if (this.div.hidden && this.#renderingDone) {
  10454. this.div.hidden = false;
  10455. this.highlighter?.enable();
  10456. }
  10457. }
  10458. cancel() {
  10459. this.#textLayer?.cancel();
  10460. this.#textLayer = null;
  10461. this.highlighter?.disable();
  10462. this.accessibilityManager?.disable();
  10463. TextLayerBuilder.#removeGlobalSelectionListener(this.div);
  10464. }
  10465. #bindMouse(end) {
  10466. const {
  10467. div
  10468. } = this;
  10469. div.addEventListener("mousedown", () => {
  10470. div.classList.add("selecting");
  10471. });
  10472. div.addEventListener("copy", event => {
  10473. if (!this.#enablePermissions) {
  10474. const selection = document.getSelection();
  10475. event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString())));
  10476. }
  10477. stopEvent(event);
  10478. });
  10479. TextLayerBuilder.#textLayers.set(div, end);
  10480. TextLayerBuilder.#enableGlobalSelectionListener();
  10481. }
  10482. static #removeGlobalSelectionListener(textLayerDiv) {
  10483. this.#textLayers.delete(textLayerDiv);
  10484. if (this.#textLayers.size === 0) {
  10485. this.#selectionChangeAbortController?.abort();
  10486. this.#selectionChangeAbortController = null;
  10487. }
  10488. }
  10489. static #enableGlobalSelectionListener() {
  10490. if (this.#selectionChangeAbortController) {
  10491. return;
  10492. }
  10493. this.#selectionChangeAbortController = new AbortController();
  10494. const {
  10495. signal
  10496. } = this.#selectionChangeAbortController;
  10497. const reset = (end, textLayer) => {
  10498. textLayer.append(end);
  10499. end.style.width = "";
  10500. end.style.height = "";
  10501. textLayer.classList.remove("selecting");
  10502. };
  10503. let isPointerDown = false;
  10504. document.addEventListener("pointerdown", () => {
  10505. isPointerDown = true;
  10506. }, {
  10507. signal
  10508. });
  10509. document.addEventListener("pointerup", () => {
  10510. isPointerDown = false;
  10511. this.#textLayers.forEach(reset);
  10512. }, {
  10513. signal
  10514. });
  10515. window.addEventListener("blur", () => {
  10516. isPointerDown = false;
  10517. this.#textLayers.forEach(reset);
  10518. }, {
  10519. signal
  10520. });
  10521. document.addEventListener("keyup", () => {
  10522. if (!isPointerDown) {
  10523. this.#textLayers.forEach(reset);
  10524. }
  10525. }, {
  10526. signal
  10527. });
  10528. var isFirefox, prevRange;
  10529. document.addEventListener("selectionchange", () => {
  10530. const selection = document.getSelection();
  10531. if (selection.rangeCount === 0) {
  10532. this.#textLayers.forEach(reset);
  10533. return;
  10534. }
  10535. const activeTextLayers = new Set();
  10536. for (let i = 0; i < selection.rangeCount; i++) {
  10537. const range = selection.getRangeAt(i);
  10538. for (const textLayerDiv of this.#textLayers.keys()) {
  10539. if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) {
  10540. activeTextLayers.add(textLayerDiv);
  10541. }
  10542. }
  10543. }
  10544. for (const [textLayerDiv, endDiv] of this.#textLayers) {
  10545. if (activeTextLayers.has(textLayerDiv)) {
  10546. textLayerDiv.classList.add("selecting");
  10547. } else {
  10548. reset(endDiv, textLayerDiv);
  10549. }
  10550. }
  10551. isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none";
  10552. if (isFirefox) {
  10553. return;
  10554. }
  10555. const range = selection.getRangeAt(0);
  10556. const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0);
  10557. let anchor = modifyStart ? range.startContainer : range.endContainer;
  10558. if (anchor.nodeType === Node.TEXT_NODE) {
  10559. anchor = anchor.parentNode;
  10560. }
  10561. if (!modifyStart && range.endOffset === 0) {
  10562. do {
  10563. while (!anchor.previousSibling) {
  10564. anchor = anchor.parentNode;
  10565. }
  10566. anchor = anchor.previousSibling;
  10567. } while (!anchor.childNodes.length);
  10568. }
  10569. const parentTextLayer = anchor.parentElement?.closest(".textLayer");
  10570. const endDiv = this.#textLayers.get(parentTextLayer);
  10571. if (endDiv) {
  10572. endDiv.style.width = parentTextLayer.style.width;
  10573. endDiv.style.height = parentTextLayer.style.height;
  10574. anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling);
  10575. }
  10576. prevRange = range.cloneRange();
  10577. }, {
  10578. signal
  10579. });
  10580. }
  10581. }
  10582. ;// ./web/pdf_page_view.js
  10583. const DEFAULT_LAYER_PROPERTIES = null;
  10584. const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]);
  10585. class PDFPageView extends BasePDFPageView {
  10586. #annotationMode = AnnotationMode.ENABLE_FORMS;
  10587. #canvasWrapper = null;
  10588. #enableAutoLinking = true;
  10589. #hasRestrictedScaling = false;
  10590. #isEditing = false;
  10591. #layerProperties = null;
  10592. #needsRestrictedScaling = false;
  10593. #originalViewport = null;
  10594. #previousRotation = null;
  10595. #scaleRoundX = 1;
  10596. #scaleRoundY = 1;
  10597. #textLayerMode = TextLayerMode.ENABLE;
  10598. #userUnit = 1;
  10599. #useThumbnailCanvas = {
  10600. directDrawing: true,
  10601. initialOptionalContent: true,
  10602. regularAnnotations: true
  10603. };
  10604. #layers = [null, null, null, null];
  10605. constructor(options) {
  10606. super(options);
  10607. const container = options.container;
  10608. const defaultViewport = options.defaultViewport;
  10609. this.renderingId = "page" + this.id;
  10610. this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES;
  10611. this.pdfPage = null;
  10612. this.pageLabel = null;
  10613. this.rotation = 0;
  10614. this.scale = options.scale || DEFAULT_SCALE;
  10615. this.viewport = defaultViewport;
  10616. this.pdfPageRotate = defaultViewport.rotation;
  10617. this._optionalContentConfigPromise = options.optionalContentConfigPromise || null;
  10618. this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE;
  10619. this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS;
  10620. this.imageResourcesPath = options.imageResourcesPath || "";
  10621. this.enableDetailCanvas = options.enableDetailCanvas ?? true;
  10622. this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels");
  10623. this.maxCanvasDim = options.maxCanvasDim || AppOptions.get("maxCanvasDim");
  10624. this.#enableAutoLinking = options.enableAutoLinking !== false;
  10625. this.l10n = options.l10n;
  10626. this.l10n ||= new genericl10n_GenericL10n();
  10627. this._isStandalone = !this.renderingQueue?.hasViewer();
  10628. this._container = container;
  10629. this._annotationCanvasMap = null;
  10630. this.annotationLayer = null;
  10631. this.annotationEditorLayer = null;
  10632. this.textLayer = null;
  10633. this.xfaLayer = null;
  10634. this.structTreeLayer = null;
  10635. this.drawLayer = null;
  10636. this.detailView = null;
  10637. const div = document.createElement("div");
  10638. div.className = "page";
  10639. div.setAttribute("data-page-number", this.id);
  10640. div.setAttribute("role", "region");
  10641. div.setAttribute("data-l10n-id", "pdfjs-page-landmark");
  10642. div.setAttribute("data-l10n-args", JSON.stringify({
  10643. page: this.id
  10644. }));
  10645. this.div = div;
  10646. this.#setDimensions();
  10647. container?.append(div);
  10648. if (this._isStandalone) {
  10649. container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS);
  10650. if (this.pageColors?.background) {
  10651. container?.style.setProperty("--page-bg-color", this.pageColors.background);
  10652. }
  10653. const {
  10654. optionalContentConfigPromise
  10655. } = options;
  10656. if (optionalContentConfigPromise) {
  10657. optionalContentConfigPromise.then(optionalContentConfig => {
  10658. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  10659. return;
  10660. }
  10661. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  10662. });
  10663. }
  10664. if (!options.l10n) {
  10665. this.l10n.translate(this.div);
  10666. }
  10667. }
  10668. }
  10669. #addLayer(div, name) {
  10670. const pos = LAYERS_ORDER.get(name);
  10671. const oldDiv = this.#layers[pos];
  10672. this.#layers[pos] = div;
  10673. if (oldDiv) {
  10674. oldDiv.replaceWith(div);
  10675. return;
  10676. }
  10677. for (let i = pos - 1; i >= 0; i--) {
  10678. const layer = this.#layers[i];
  10679. if (layer) {
  10680. layer.after(div);
  10681. return;
  10682. }
  10683. }
  10684. this.div.prepend(div);
  10685. }
  10686. #setDimensions() {
  10687. const {
  10688. div,
  10689. viewport
  10690. } = this;
  10691. if (viewport.userUnit !== this.#userUnit) {
  10692. if (viewport.userUnit !== 1) {
  10693. div.style.setProperty("--user-unit", viewport.userUnit);
  10694. } else {
  10695. div.style.removeProperty("--user-unit");
  10696. }
  10697. this.#userUnit = viewport.userUnit;
  10698. }
  10699. if (this.pdfPage) {
  10700. if (this.#previousRotation === viewport.rotation) {
  10701. return;
  10702. }
  10703. this.#previousRotation = viewport.rotation;
  10704. }
  10705. setLayerDimensions(div, viewport, true, false);
  10706. }
  10707. setPdfPage(pdfPage) {
  10708. if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) {
  10709. this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight"));
  10710. this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight"));
  10711. }
  10712. this.pdfPage = pdfPage;
  10713. this.pdfPageRotate = pdfPage.rotate;
  10714. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  10715. this.viewport = pdfPage.getViewport({
  10716. scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS,
  10717. rotation: totalRotation
  10718. });
  10719. this.#setDimensions();
  10720. this.reset();
  10721. }
  10722. destroy() {
  10723. this.reset();
  10724. this.pdfPage?.cleanup();
  10725. }
  10726. hasEditableAnnotations() {
  10727. return !!this.annotationLayer?.hasEditableAnnotations();
  10728. }
  10729. get _textHighlighter() {
  10730. return shadow(this, "_textHighlighter", new TextHighlighter({
  10731. pageIndex: this.id - 1,
  10732. eventBus: this.eventBus,
  10733. findController: this.#layerProperties.findController
  10734. }));
  10735. }
  10736. #dispatchLayerRendered(name, error) {
  10737. this.eventBus.dispatch(name, {
  10738. source: this,
  10739. pageNumber: this.id,
  10740. error
  10741. });
  10742. }
  10743. async #renderAnnotationLayer() {
  10744. let error = null;
  10745. try {
  10746. await this.annotationLayer.render({
  10747. viewport: this.viewport,
  10748. intent: "display",
  10749. structTreeLayer: this.structTreeLayer
  10750. });
  10751. } catch (ex) {
  10752. console.error("#renderAnnotationLayer:", ex);
  10753. error = ex;
  10754. } finally {
  10755. this.#dispatchLayerRendered("annotationlayerrendered", error);
  10756. }
  10757. }
  10758. async #renderAnnotationEditorLayer() {
  10759. let error = null;
  10760. try {
  10761. await this.annotationEditorLayer.render({
  10762. viewport: this.viewport,
  10763. intent: "display"
  10764. });
  10765. } catch (ex) {
  10766. console.error("#renderAnnotationEditorLayer:", ex);
  10767. error = ex;
  10768. } finally {
  10769. this.#dispatchLayerRendered("annotationeditorlayerrendered", error);
  10770. }
  10771. }
  10772. async #renderDrawLayer() {
  10773. try {
  10774. await this.drawLayer.render({
  10775. intent: "display"
  10776. });
  10777. } catch (ex) {
  10778. console.error("#renderDrawLayer:", ex);
  10779. }
  10780. }
  10781. async #renderXfaLayer() {
  10782. let error = null;
  10783. try {
  10784. const result = await this.xfaLayer.render({
  10785. viewport: this.viewport,
  10786. intent: "display"
  10787. });
  10788. if (result?.textDivs && this._textHighlighter) {
  10789. this.#buildXfaTextContentItems(result.textDivs);
  10790. }
  10791. } catch (ex) {
  10792. console.error("#renderXfaLayer:", ex);
  10793. error = ex;
  10794. } finally {
  10795. if (this.xfaLayer?.div) {
  10796. this.l10n.pause();
  10797. this.#addLayer(this.xfaLayer.div, "xfaLayer");
  10798. this.l10n.resume();
  10799. }
  10800. this.#dispatchLayerRendered("xfalayerrendered", error);
  10801. }
  10802. }
  10803. async #renderTextLayer() {
  10804. if (!this.textLayer) {
  10805. return;
  10806. }
  10807. let error = null;
  10808. try {
  10809. await this.textLayer.render({
  10810. viewport: this.viewport
  10811. });
  10812. } catch (ex) {
  10813. if (ex instanceof AbortException) {
  10814. return;
  10815. }
  10816. console.error("#renderTextLayer:", ex);
  10817. error = ex;
  10818. }
  10819. this.#dispatchLayerRendered("textlayerrendered", error);
  10820. this.#renderStructTreeLayer();
  10821. }
  10822. async #renderStructTreeLayer() {
  10823. if (!this.textLayer) {
  10824. return;
  10825. }
  10826. const treeDom = await this.structTreeLayer?.render();
  10827. if (treeDom) {
  10828. this.l10n.pause();
  10829. this.structTreeLayer?.addElementsToTextLayer();
  10830. if (this.canvas && treeDom.parentNode !== this.canvas) {
  10831. this.canvas.append(treeDom);
  10832. }
  10833. this.l10n.resume();
  10834. }
  10835. this.structTreeLayer?.show();
  10836. }
  10837. async #buildXfaTextContentItems(textDivs) {
  10838. const text = await this.pdfPage.getTextContent();
  10839. const items = [];
  10840. for (const item of text.items) {
  10841. items.push(item.str);
  10842. }
  10843. this._textHighlighter.setTextMapping(textDivs, items);
  10844. this._textHighlighter.enable();
  10845. }
  10846. async #injectLinkAnnotations(textLayerPromise) {
  10847. let error = null;
  10848. try {
  10849. await textLayerPromise;
  10850. if (!this.annotationLayer) {
  10851. return;
  10852. }
  10853. await this.annotationLayer.injectLinkAnnotations({
  10854. inferredLinks: Autolinker.processLinks(this),
  10855. viewport: this.viewport,
  10856. structTreeLayer: this.structTreeLayer
  10857. });
  10858. } catch (ex) {
  10859. console.error("#injectLinkAnnotations:", ex);
  10860. error = ex;
  10861. }
  10862. }
  10863. _resetCanvas() {
  10864. super._resetCanvas();
  10865. this.#originalViewport = null;
  10866. }
  10867. reset({
  10868. keepAnnotationLayer = false,
  10869. keepAnnotationEditorLayer = false,
  10870. keepXfaLayer = false,
  10871. keepTextLayer = false,
  10872. keepCanvasWrapper = false,
  10873. preserveDetailViewState = false
  10874. } = {}) {
  10875. this.cancelRendering({
  10876. keepAnnotationLayer,
  10877. keepAnnotationEditorLayer,
  10878. keepXfaLayer,
  10879. keepTextLayer
  10880. });
  10881. this.renderingState = RenderingStates.INITIAL;
  10882. const div = this.div;
  10883. const childNodes = div.childNodes,
  10884. annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null,
  10885. annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null,
  10886. xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null,
  10887. textLayerNode = keepTextLayer && this.textLayer?.div || null,
  10888. canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null;
  10889. for (let i = childNodes.length - 1; i >= 0; i--) {
  10890. const node = childNodes[i];
  10891. switch (node) {
  10892. case annotationLayerNode:
  10893. case annotationEditorLayerNode:
  10894. case xfaLayerNode:
  10895. case textLayerNode:
  10896. case canvasWrapperNode:
  10897. continue;
  10898. }
  10899. node.remove();
  10900. const layerIndex = this.#layers.indexOf(node);
  10901. if (layerIndex >= 0) {
  10902. this.#layers[layerIndex] = null;
  10903. }
  10904. }
  10905. div.removeAttribute("data-loaded");
  10906. if (annotationLayerNode) {
  10907. this.annotationLayer.hide();
  10908. }
  10909. if (annotationEditorLayerNode) {
  10910. this.annotationEditorLayer.hide();
  10911. }
  10912. if (xfaLayerNode) {
  10913. this.xfaLayer.hide();
  10914. }
  10915. if (textLayerNode) {
  10916. this.textLayer.hide();
  10917. }
  10918. this.structTreeLayer?.hide();
  10919. if (!keepCanvasWrapper && this.#canvasWrapper) {
  10920. this.#canvasWrapper = null;
  10921. this._resetCanvas();
  10922. }
  10923. if (!preserveDetailViewState) {
  10924. this.detailView?.reset({
  10925. keepCanvas: keepCanvasWrapper
  10926. });
  10927. if (!keepCanvasWrapper) {
  10928. this.detailView = null;
  10929. }
  10930. }
  10931. }
  10932. toggleEditingMode(isEditing) {
  10933. this.#isEditing = isEditing;
  10934. if (!this.hasEditableAnnotations()) {
  10935. return;
  10936. }
  10937. this.reset({
  10938. keepAnnotationLayer: true,
  10939. keepAnnotationEditorLayer: true,
  10940. keepXfaLayer: true,
  10941. keepTextLayer: true,
  10942. keepCanvasWrapper: true
  10943. });
  10944. }
  10945. updateVisibleArea(visibleArea) {
  10946. if (this.enableDetailCanvas) {
  10947. if (this.#needsRestrictedScaling && this.maxCanvasPixels > 0 && visibleArea) {
  10948. this.detailView ??= new PDFPageDetailView({
  10949. pageView: this
  10950. });
  10951. this.detailView.update({
  10952. visibleArea
  10953. });
  10954. } else if (this.detailView) {
  10955. this.detailView.reset();
  10956. this.detailView = null;
  10957. }
  10958. }
  10959. }
  10960. update({
  10961. scale = 0,
  10962. rotation = null,
  10963. optionalContentConfigPromise = null,
  10964. drawingDelay = -1
  10965. }) {
  10966. this.scale = scale || this.scale;
  10967. if (typeof rotation === "number") {
  10968. this.rotation = rotation;
  10969. }
  10970. if (optionalContentConfigPromise instanceof Promise) {
  10971. this._optionalContentConfigPromise = optionalContentConfigPromise;
  10972. optionalContentConfigPromise.then(optionalContentConfig => {
  10973. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  10974. return;
  10975. }
  10976. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  10977. });
  10978. }
  10979. this.#useThumbnailCanvas.directDrawing = true;
  10980. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  10981. this.viewport = this.viewport.clone({
  10982. scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS,
  10983. rotation: totalRotation
  10984. });
  10985. this.#setDimensions();
  10986. if (this._isStandalone) {
  10987. this._container?.style.setProperty("--scale-factor", this.viewport.scale);
  10988. }
  10989. this.#computeScale();
  10990. if (this.canvas) {
  10991. const onlyCssZoom = this.#hasRestrictedScaling && this.#needsRestrictedScaling;
  10992. const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000;
  10993. if (postponeDrawing || onlyCssZoom) {
  10994. if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) {
  10995. this.cancelRendering({
  10996. keepAnnotationLayer: true,
  10997. keepAnnotationEditorLayer: true,
  10998. keepXfaLayer: true,
  10999. keepTextLayer: true,
  11000. cancelExtraDelay: drawingDelay
  11001. });
  11002. this.renderingState = RenderingStates.FINISHED;
  11003. this.#useThumbnailCanvas.directDrawing = false;
  11004. }
  11005. this.cssTransform({
  11006. redrawAnnotationLayer: true,
  11007. redrawAnnotationEditorLayer: true,
  11008. redrawXfaLayer: true,
  11009. redrawTextLayer: !postponeDrawing,
  11010. hideTextLayer: postponeDrawing
  11011. });
  11012. if (!postponeDrawing) {
  11013. this.detailView?.update({
  11014. underlyingViewUpdated: true
  11015. });
  11016. this.dispatchPageRendered(true, false);
  11017. }
  11018. return;
  11019. }
  11020. }
  11021. this.cssTransform({});
  11022. this.reset({
  11023. keepAnnotationLayer: true,
  11024. keepAnnotationEditorLayer: true,
  11025. keepXfaLayer: true,
  11026. keepTextLayer: true,
  11027. keepCanvasWrapper: true,
  11028. preserveDetailViewState: true
  11029. });
  11030. this.detailView?.update({
  11031. underlyingViewUpdated: true
  11032. });
  11033. }
  11034. #computeScale() {
  11035. const {
  11036. width,
  11037. height
  11038. } = this.viewport;
  11039. const outputScale = this.outputScale = new OutputScale();
  11040. if (this.maxCanvasPixels === 0) {
  11041. const invScale = 1 / this.scale;
  11042. outputScale.sx *= invScale;
  11043. outputScale.sy *= invScale;
  11044. this.#needsRestrictedScaling = true;
  11045. } else {
  11046. this.#needsRestrictedScaling = outputScale.limitCanvas(width, height, this.maxCanvasPixels, this.maxCanvasDim);
  11047. }
  11048. }
  11049. cancelRendering({
  11050. keepAnnotationLayer = false,
  11051. keepAnnotationEditorLayer = false,
  11052. keepXfaLayer = false,
  11053. keepTextLayer = false,
  11054. cancelExtraDelay = 0
  11055. } = {}) {
  11056. super.cancelRendering({
  11057. cancelExtraDelay
  11058. });
  11059. if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) {
  11060. this.textLayer.cancel();
  11061. this.textLayer = null;
  11062. }
  11063. if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) {
  11064. this.annotationLayer.cancel();
  11065. this.annotationLayer = null;
  11066. this._annotationCanvasMap = null;
  11067. }
  11068. if (this.structTreeLayer && !this.textLayer) {
  11069. this.structTreeLayer = null;
  11070. }
  11071. if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) {
  11072. if (this.drawLayer) {
  11073. this.drawLayer.cancel();
  11074. this.drawLayer = null;
  11075. }
  11076. this.annotationEditorLayer.cancel();
  11077. this.annotationEditorLayer = null;
  11078. }
  11079. if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) {
  11080. this.xfaLayer.cancel();
  11081. this.xfaLayer = null;
  11082. this._textHighlighter?.disable();
  11083. }
  11084. }
  11085. cssTransform({
  11086. redrawAnnotationLayer = false,
  11087. redrawAnnotationEditorLayer = false,
  11088. redrawXfaLayer = false,
  11089. redrawTextLayer = false,
  11090. hideTextLayer = false
  11091. }) {
  11092. const {
  11093. canvas
  11094. } = this;
  11095. if (!canvas) {
  11096. return;
  11097. }
  11098. const originalViewport = this.#originalViewport;
  11099. if (this.viewport !== originalViewport) {
  11100. const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360;
  11101. if (relativeRotation === 90 || relativeRotation === 270) {
  11102. const {
  11103. width,
  11104. height
  11105. } = this.viewport;
  11106. const scaleX = height / width;
  11107. const scaleY = width / height;
  11108. canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`;
  11109. } else {
  11110. canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`;
  11111. }
  11112. }
  11113. if (redrawAnnotationLayer && this.annotationLayer) {
  11114. this.#renderAnnotationLayer();
  11115. }
  11116. if (redrawAnnotationEditorLayer && this.annotationEditorLayer) {
  11117. if (this.drawLayer) {
  11118. this.#renderDrawLayer();
  11119. }
  11120. this.#renderAnnotationEditorLayer();
  11121. }
  11122. if (redrawXfaLayer && this.xfaLayer) {
  11123. this.#renderXfaLayer();
  11124. }
  11125. if (this.textLayer) {
  11126. if (hideTextLayer) {
  11127. this.textLayer.hide();
  11128. this.structTreeLayer?.hide();
  11129. } else if (redrawTextLayer) {
  11130. this.#renderTextLayer();
  11131. }
  11132. }
  11133. }
  11134. get width() {
  11135. return this.viewport.width;
  11136. }
  11137. get height() {
  11138. return this.viewport.height;
  11139. }
  11140. getPagePoint(x, y) {
  11141. return this.viewport.convertToPdfPoint(x, y);
  11142. }
  11143. _ensureCanvasWrapper() {
  11144. let canvasWrapper = this.#canvasWrapper;
  11145. if (!canvasWrapper) {
  11146. canvasWrapper = this.#canvasWrapper = document.createElement("div");
  11147. canvasWrapper.classList.add("canvasWrapper");
  11148. this.#addLayer(canvasWrapper, "canvasWrapper");
  11149. }
  11150. return canvasWrapper;
  11151. }
  11152. _getRenderingContext(canvasContext, transform) {
  11153. return {
  11154. canvasContext,
  11155. transform,
  11156. viewport: this.viewport,
  11157. annotationMode: this.#annotationMode,
  11158. optionalContentConfigPromise: this._optionalContentConfigPromise,
  11159. annotationCanvasMap: this._annotationCanvasMap,
  11160. pageColors: this.pageColors,
  11161. isEditing: this.#isEditing
  11162. };
  11163. }
  11164. async draw() {
  11165. if (this.renderingState !== RenderingStates.INITIAL) {
  11166. console.error("Must be in new state before drawing");
  11167. this.reset();
  11168. }
  11169. const {
  11170. div,
  11171. l10n,
  11172. pdfPage,
  11173. viewport
  11174. } = this;
  11175. if (!pdfPage) {
  11176. this.renderingState = RenderingStates.FINISHED;
  11177. throw new Error("pdfPage is not loaded");
  11178. }
  11179. this.renderingState = RenderingStates.RUNNING;
  11180. const canvasWrapper = this._ensureCanvasWrapper();
  11181. if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) {
  11182. this._accessibilityManager ||= new TextAccessibilityManager();
  11183. this.textLayer = new TextLayerBuilder({
  11184. pdfPage,
  11185. highlighter: this._textHighlighter,
  11186. accessibilityManager: this._accessibilityManager,
  11187. enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS,
  11188. onAppend: textLayerDiv => {
  11189. this.l10n.pause();
  11190. this.#addLayer(textLayerDiv, "textLayer");
  11191. this.l10n.resume();
  11192. }
  11193. });
  11194. }
  11195. if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) {
  11196. const {
  11197. annotationStorage,
  11198. annotationEditorUIManager,
  11199. downloadManager,
  11200. enableScripting,
  11201. fieldObjectsPromise,
  11202. hasJSActionsPromise,
  11203. linkService
  11204. } = this.#layerProperties;
  11205. this._annotationCanvasMap ||= new Map();
  11206. this.annotationLayer = new AnnotationLayerBuilder({
  11207. pdfPage,
  11208. annotationStorage,
  11209. imageResourcesPath: this.imageResourcesPath,
  11210. renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS,
  11211. linkService,
  11212. downloadManager,
  11213. enableScripting,
  11214. hasJSActionsPromise,
  11215. fieldObjectsPromise,
  11216. annotationCanvasMap: this._annotationCanvasMap,
  11217. accessibilityManager: this._accessibilityManager,
  11218. annotationEditorUIManager,
  11219. onAppend: annotationLayerDiv => {
  11220. this.#addLayer(annotationLayerDiv, "annotationLayer");
  11221. }
  11222. });
  11223. }
  11224. const {
  11225. width,
  11226. height
  11227. } = viewport;
  11228. this.#originalViewport = viewport;
  11229. const {
  11230. canvas,
  11231. prevCanvas,
  11232. ctx
  11233. } = this._createCanvas(newCanvas => {
  11234. canvasWrapper.prepend(newCanvas);
  11235. });
  11236. canvas.setAttribute("role", "presentation");
  11237. if (!this.outputScale) {
  11238. this.#computeScale();
  11239. }
  11240. const {
  11241. outputScale
  11242. } = this;
  11243. this.#hasRestrictedScaling = this.#needsRestrictedScaling;
  11244. const sfx = approximateFraction(outputScale.sx);
  11245. const sfy = approximateFraction(outputScale.sy);
  11246. const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]);
  11247. const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]);
  11248. const pageWidth = floorToDivide(calcRound(width), sfx[1]);
  11249. const pageHeight = floorToDivide(calcRound(height), sfy[1]);
  11250. outputScale.sx = canvasWidth / pageWidth;
  11251. outputScale.sy = canvasHeight / pageHeight;
  11252. if (this.#scaleRoundX !== sfx[1]) {
  11253. div.style.setProperty("--scale-round-x", `${sfx[1]}px`);
  11254. this.#scaleRoundX = sfx[1];
  11255. }
  11256. if (this.#scaleRoundY !== sfy[1]) {
  11257. div.style.setProperty("--scale-round-y", `${sfy[1]}px`);
  11258. this.#scaleRoundY = sfy[1];
  11259. }
  11260. const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null;
  11261. const resultPromise = this._drawCanvas(this._getRenderingContext(ctx, transform), () => {
  11262. prevCanvas?.remove();
  11263. this._resetCanvas();
  11264. }, renderTask => {
  11265. this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots;
  11266. this.dispatchPageRendered(false, false);
  11267. }).then(async () => {
  11268. this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims);
  11269. const textLayerPromise = this.#renderTextLayer();
  11270. if (this.annotationLayer) {
  11271. await this.#renderAnnotationLayer();
  11272. if (this.#enableAutoLinking && this.annotationLayer && this.textLayer) {
  11273. await this.#injectLinkAnnotations(textLayerPromise);
  11274. }
  11275. }
  11276. const {
  11277. annotationEditorUIManager
  11278. } = this.#layerProperties;
  11279. if (!annotationEditorUIManager) {
  11280. return;
  11281. }
  11282. this.drawLayer ||= new DrawLayerBuilder({
  11283. pageIndex: this.id
  11284. });
  11285. await this.#renderDrawLayer();
  11286. this.drawLayer.setParent(canvasWrapper);
  11287. this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({
  11288. uiManager: annotationEditorUIManager,
  11289. pdfPage,
  11290. l10n,
  11291. structTreeLayer: this.structTreeLayer,
  11292. accessibilityManager: this._accessibilityManager,
  11293. annotationLayer: this.annotationLayer?.annotationLayer,
  11294. textLayer: this.textLayer,
  11295. drawLayer: this.drawLayer.getDrawLayer(),
  11296. onAppend: annotationEditorLayerDiv => {
  11297. this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer");
  11298. }
  11299. });
  11300. this.#renderAnnotationEditorLayer();
  11301. });
  11302. if (pdfPage.isPureXfa) {
  11303. if (!this.xfaLayer) {
  11304. const {
  11305. annotationStorage,
  11306. linkService
  11307. } = this.#layerProperties;
  11308. this.xfaLayer = new XfaLayerBuilder({
  11309. pdfPage,
  11310. annotationStorage,
  11311. linkService
  11312. });
  11313. }
  11314. this.#renderXfaLayer();
  11315. }
  11316. div.setAttribute("data-loaded", true);
  11317. this.dispatchPageRender();
  11318. return resultPromise;
  11319. }
  11320. setPageLabel(label) {
  11321. this.pageLabel = typeof label === "string" ? label : null;
  11322. this.div.setAttribute("data-l10n-args", JSON.stringify({
  11323. page: this.pageLabel ?? this.id
  11324. }));
  11325. if (this.pageLabel !== null) {
  11326. this.div.setAttribute("data-page-label", this.pageLabel);
  11327. } else {
  11328. this.div.removeAttribute("data-page-label");
  11329. }
  11330. }
  11331. get thumbnailCanvas() {
  11332. const {
  11333. directDrawing,
  11334. initialOptionalContent,
  11335. regularAnnotations
  11336. } = this.#useThumbnailCanvas;
  11337. return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null;
  11338. }
  11339. }
  11340. ;// ./web/pdf_viewer.js
  11341. const DEFAULT_CACHE_SIZE = 10;
  11342. const PagesCountLimit = {
  11343. FORCE_SCROLL_MODE_PAGE: 10000,
  11344. FORCE_LAZY_PAGE_INIT: 5000,
  11345. PAUSE_EAGER_PAGE_INIT: 250
  11346. };
  11347. function isValidAnnotationEditorMode(mode) {
  11348. return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE;
  11349. }
  11350. class PDFPageViewBuffer {
  11351. #buf = new Set();
  11352. #size = 0;
  11353. constructor(size) {
  11354. this.#size = size;
  11355. }
  11356. push(view) {
  11357. const buf = this.#buf;
  11358. if (buf.has(view)) {
  11359. buf.delete(view);
  11360. }
  11361. buf.add(view);
  11362. if (buf.size > this.#size) {
  11363. this.#destroyFirstView();
  11364. }
  11365. }
  11366. resize(newSize, idsToKeep = null) {
  11367. this.#size = newSize;
  11368. const buf = this.#buf;
  11369. if (idsToKeep) {
  11370. const ii = buf.size;
  11371. let i = 1;
  11372. for (const view of buf) {
  11373. if (idsToKeep.has(view.id)) {
  11374. buf.delete(view);
  11375. buf.add(view);
  11376. }
  11377. if (++i > ii) {
  11378. break;
  11379. }
  11380. }
  11381. }
  11382. while (buf.size > this.#size) {
  11383. this.#destroyFirstView();
  11384. }
  11385. }
  11386. has(view) {
  11387. return this.#buf.has(view);
  11388. }
  11389. [Symbol.iterator]() {
  11390. return this.#buf.keys();
  11391. }
  11392. #destroyFirstView() {
  11393. const firstView = this.#buf.keys().next().value;
  11394. firstView?.destroy();
  11395. this.#buf.delete(firstView);
  11396. }
  11397. }
  11398. class PDFViewer {
  11399. #buffer = null;
  11400. #altTextManager = null;
  11401. #annotationEditorHighlightColors = null;
  11402. #annotationEditorMode = AnnotationEditorType.NONE;
  11403. #annotationEditorUIManager = null;
  11404. #annotationMode = AnnotationMode.ENABLE_FORMS;
  11405. #containerTopLeft = null;
  11406. #editorUndoBar = null;
  11407. #enableHWA = false;
  11408. #enableHighlightFloatingButton = false;
  11409. #enablePermissions = false;
  11410. #enableUpdatedAddImage = false;
  11411. #enableNewAltTextWhenAddingImage = false;
  11412. #enableAutoLinking = true;
  11413. #eventAbortController = null;
  11414. #mlManager = null;
  11415. #scrollTimeoutId = null;
  11416. #switchAnnotationEditorModeAC = null;
  11417. #switchAnnotationEditorModeTimeoutId = null;
  11418. #getAllTextInProgress = false;
  11419. #hiddenCopyElement = null;
  11420. #interruptCopyCondition = false;
  11421. #previousContainerHeight = 0;
  11422. #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this));
  11423. #scrollModePageState = null;
  11424. #scaleTimeoutId = null;
  11425. #signatureManager = null;
  11426. #supportsPinchToZoom = true;
  11427. #textLayerMode = TextLayerMode.ENABLE;
  11428. constructor(options) {
  11429. const viewerVersion = "5.2.133";
  11430. if (version !== viewerVersion) {
  11431. throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`);
  11432. }
  11433. this.container = options.container;
  11434. this.viewer = options.viewer || options.container.firstElementChild;
  11435. if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") {
  11436. throw new Error("Invalid `container` and/or `viewer` option.");
  11437. }
  11438. if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") {
  11439. throw new Error("The `container` must be absolutely positioned.");
  11440. }
  11441. this.#resizeObserver.observe(this.container);
  11442. this.eventBus = options.eventBus;
  11443. this.linkService = options.linkService || new SimpleLinkService();
  11444. this.downloadManager = options.downloadManager || null;
  11445. this.findController = options.findController || null;
  11446. this.#altTextManager = options.altTextManager || null;
  11447. this.#signatureManager = options.signatureManager || null;
  11448. this.#editorUndoBar = options.editorUndoBar || null;
  11449. if (this.findController) {
  11450. this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber);
  11451. }
  11452. this._scriptingManager = options.scriptingManager || null;
  11453. this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE;
  11454. this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS;
  11455. this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE;
  11456. this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null;
  11457. this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true;
  11458. this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true;
  11459. this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true;
  11460. this.imageResourcesPath = options.imageResourcesPath || "";
  11461. this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;
  11462. this.removePageBorders = options.removePageBorders || false;
  11463. this.maxCanvasPixels = options.maxCanvasPixels;
  11464. this.maxCanvasDim = options.maxCanvasDim;
  11465. this.enableDetailCanvas = options.enableDetailCanvas ?? true;
  11466. this.l10n = options.l10n;
  11467. this.l10n ||= new genericl10n_GenericL10n();
  11468. this.#enablePermissions = options.enablePermissions || false;
  11469. this.pageColors = options.pageColors || null;
  11470. this.#mlManager = options.mlManager || null;
  11471. this.#enableHWA = options.enableHWA || false;
  11472. this.#supportsPinchToZoom = options.supportsPinchToZoom !== false;
  11473. this.#enableAutoLinking = options.enableAutoLinking !== false;
  11474. this.defaultRenderingQueue = !options.renderingQueue;
  11475. if (this.defaultRenderingQueue) {
  11476. this.renderingQueue = new PDFRenderingQueue();
  11477. this.renderingQueue.setViewer(this);
  11478. } else {
  11479. this.renderingQueue = options.renderingQueue;
  11480. }
  11481. const {
  11482. abortSignal
  11483. } = options;
  11484. abortSignal?.addEventListener("abort", () => {
  11485. this.#resizeObserver.disconnect();
  11486. this.#resizeObserver = null;
  11487. }, {
  11488. once: true
  11489. });
  11490. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal);
  11491. this.presentationModeState = PresentationModeState.UNKNOWN;
  11492. this._resetView();
  11493. if (this.removePageBorders) {
  11494. this.viewer.classList.add("removePageBorders");
  11495. }
  11496. this.#updateContainerHeightCss();
  11497. this.eventBus._on("thumbnailrendered", ({
  11498. pageNumber,
  11499. pdfPage
  11500. }) => {
  11501. const pageView = this._pages[pageNumber - 1];
  11502. if (!this.#buffer.has(pageView)) {
  11503. pdfPage?.cleanup();
  11504. }
  11505. });
  11506. if (!options.l10n) {
  11507. this.l10n.translate(this.container);
  11508. }
  11509. }
  11510. get pagesCount() {
  11511. return this._pages.length;
  11512. }
  11513. getPageView(index) {
  11514. return this._pages[index];
  11515. }
  11516. getCachedPageViews() {
  11517. return new Set(this.#buffer);
  11518. }
  11519. get pageViewsReady() {
  11520. return this._pages.every(pageView => pageView?.pdfPage);
  11521. }
  11522. get renderForms() {
  11523. return this.#annotationMode === AnnotationMode.ENABLE_FORMS;
  11524. }
  11525. get enableScripting() {
  11526. return !!this._scriptingManager;
  11527. }
  11528. get currentPageNumber() {
  11529. return this._currentPageNumber;
  11530. }
  11531. set currentPageNumber(val) {
  11532. if (!Number.isInteger(val)) {
  11533. throw new Error("Invalid page number.");
  11534. }
  11535. if (!this.pdfDocument) {
  11536. return;
  11537. }
  11538. if (!this._setCurrentPageNumber(val, true)) {
  11539. console.error(`currentPageNumber: "${val}" is not a valid page.`);
  11540. }
  11541. }
  11542. _setCurrentPageNumber(val, resetCurrentPageView = false) {
  11543. if (this._currentPageNumber === val) {
  11544. if (resetCurrentPageView) {
  11545. this.#resetCurrentPageView();
  11546. }
  11547. return true;
  11548. }
  11549. if (!(0 < val && val <= this.pagesCount)) {
  11550. return false;
  11551. }
  11552. const previous = this._currentPageNumber;
  11553. this._currentPageNumber = val;
  11554. this.eventBus.dispatch("pagechanging", {
  11555. source: this,
  11556. pageNumber: val,
  11557. pageLabel: this._pageLabels?.[val - 1] ?? null,
  11558. previous
  11559. });
  11560. if (resetCurrentPageView) {
  11561. this.#resetCurrentPageView();
  11562. }
  11563. return true;
  11564. }
  11565. get currentPageLabel() {
  11566. return this._pageLabels?.[this._currentPageNumber - 1] ?? null;
  11567. }
  11568. set currentPageLabel(val) {
  11569. if (!this.pdfDocument) {
  11570. return;
  11571. }
  11572. let page = val | 0;
  11573. if (this._pageLabels) {
  11574. const i = this._pageLabels.indexOf(val);
  11575. if (i >= 0) {
  11576. page = i + 1;
  11577. }
  11578. }
  11579. if (!this._setCurrentPageNumber(page, true)) {
  11580. console.error(`currentPageLabel: "${val}" is not a valid page.`);
  11581. }
  11582. }
  11583. get currentScale() {
  11584. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE;
  11585. }
  11586. set currentScale(val) {
  11587. if (isNaN(val)) {
  11588. throw new Error("Invalid numeric scale.");
  11589. }
  11590. if (!this.pdfDocument) {
  11591. return;
  11592. }
  11593. this.#setScale(val, {
  11594. noScroll: false
  11595. });
  11596. }
  11597. get currentScaleValue() {
  11598. return this._currentScaleValue;
  11599. }
  11600. set currentScaleValue(val) {
  11601. if (!this.pdfDocument) {
  11602. return;
  11603. }
  11604. this.#setScale(val, {
  11605. noScroll: false
  11606. });
  11607. }
  11608. get pagesRotation() {
  11609. return this._pagesRotation;
  11610. }
  11611. set pagesRotation(rotation) {
  11612. if (!isValidRotation(rotation)) {
  11613. throw new Error("Invalid pages rotation angle.");
  11614. }
  11615. if (!this.pdfDocument) {
  11616. return;
  11617. }
  11618. rotation %= 360;
  11619. if (rotation < 0) {
  11620. rotation += 360;
  11621. }
  11622. if (this._pagesRotation === rotation) {
  11623. return;
  11624. }
  11625. this._pagesRotation = rotation;
  11626. const pageNumber = this._currentPageNumber;
  11627. this.refresh(true, {
  11628. rotation
  11629. });
  11630. if (this._currentScaleValue) {
  11631. this.#setScale(this._currentScaleValue, {
  11632. noScroll: true
  11633. });
  11634. }
  11635. this.eventBus.dispatch("rotationchanging", {
  11636. source: this,
  11637. pagesRotation: rotation,
  11638. pageNumber
  11639. });
  11640. if (this.defaultRenderingQueue) {
  11641. this.update();
  11642. }
  11643. }
  11644. get firstPagePromise() {
  11645. return this.pdfDocument ? this._firstPageCapability.promise : null;
  11646. }
  11647. get onePageRendered() {
  11648. return this.pdfDocument ? this._onePageRenderedCapability.promise : null;
  11649. }
  11650. get pagesPromise() {
  11651. return this.pdfDocument ? this._pagesCapability.promise : null;
  11652. }
  11653. get _layerProperties() {
  11654. const self = this;
  11655. return shadow(this, "_layerProperties", {
  11656. get annotationEditorUIManager() {
  11657. return self.#annotationEditorUIManager;
  11658. },
  11659. get annotationStorage() {
  11660. return self.pdfDocument?.annotationStorage;
  11661. },
  11662. get downloadManager() {
  11663. return self.downloadManager;
  11664. },
  11665. get enableScripting() {
  11666. return !!self._scriptingManager;
  11667. },
  11668. get fieldObjectsPromise() {
  11669. return self.pdfDocument?.getFieldObjects();
  11670. },
  11671. get findController() {
  11672. return self.findController;
  11673. },
  11674. get hasJSActionsPromise() {
  11675. return self.pdfDocument?.hasJSActions();
  11676. },
  11677. get linkService() {
  11678. return self.linkService;
  11679. }
  11680. });
  11681. }
  11682. #initializePermissions(permissions) {
  11683. const params = {
  11684. annotationEditorMode: this.#annotationEditorMode,
  11685. annotationMode: this.#annotationMode,
  11686. textLayerMode: this.#textLayerMode
  11687. };
  11688. if (!permissions) {
  11689. return params;
  11690. }
  11691. if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) {
  11692. params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS;
  11693. }
  11694. if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) {
  11695. params.annotationEditorMode = AnnotationEditorType.DISABLE;
  11696. }
  11697. if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) {
  11698. params.annotationMode = AnnotationMode.ENABLE;
  11699. }
  11700. return params;
  11701. }
  11702. async #onePageRenderedOrForceFetch(signal) {
  11703. if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) {
  11704. return;
  11705. }
  11706. const hiddenCapability = Promise.withResolvers(),
  11707. ac = new AbortController();
  11708. document.addEventListener("visibilitychange", () => {
  11709. if (document.visibilityState === "hidden") {
  11710. hiddenCapability.resolve();
  11711. }
  11712. }, {
  11713. signal: AbortSignal.any([signal, ac.signal])
  11714. });
  11715. await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]);
  11716. ac.abort();
  11717. }
  11718. async getAllText() {
  11719. const texts = [];
  11720. const buffer = [];
  11721. for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) {
  11722. if (this.#interruptCopyCondition) {
  11723. return null;
  11724. }
  11725. buffer.length = 0;
  11726. const page = await this.pdfDocument.getPage(pageNum);
  11727. const {
  11728. items
  11729. } = await page.getTextContent();
  11730. for (const item of items) {
  11731. if (item.str) {
  11732. buffer.push(item.str);
  11733. }
  11734. if (item.hasEOL) {
  11735. buffer.push("\n");
  11736. }
  11737. }
  11738. texts.push(removeNullCharacters(buffer.join("")));
  11739. }
  11740. return texts.join("\n");
  11741. }
  11742. #copyCallback(textLayerMode, event) {
  11743. const selection = document.getSelection();
  11744. const {
  11745. focusNode,
  11746. anchorNode
  11747. } = selection;
  11748. if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) {
  11749. if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) {
  11750. stopEvent(event);
  11751. return;
  11752. }
  11753. this.#getAllTextInProgress = true;
  11754. const {
  11755. classList
  11756. } = this.viewer;
  11757. classList.add("copyAll");
  11758. const ac = new AbortController();
  11759. window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", {
  11760. signal: ac.signal
  11761. });
  11762. this.getAllText().then(async text => {
  11763. if (text !== null) {
  11764. await navigator.clipboard.writeText(text);
  11765. }
  11766. }).catch(reason => {
  11767. console.warn(`Something goes wrong when extracting the text: ${reason.message}`);
  11768. }).finally(() => {
  11769. this.#getAllTextInProgress = false;
  11770. this.#interruptCopyCondition = false;
  11771. ac.abort();
  11772. classList.remove("copyAll");
  11773. });
  11774. stopEvent(event);
  11775. }
  11776. }
  11777. setDocument(pdfDocument) {
  11778. if (this.pdfDocument) {
  11779. this.eventBus.dispatch("pagesdestroy", {
  11780. source: this
  11781. });
  11782. this._cancelRendering();
  11783. this._resetView();
  11784. this.findController?.setDocument(null);
  11785. this._scriptingManager?.setDocument(null);
  11786. this.#annotationEditorUIManager?.destroy();
  11787. this.#annotationEditorUIManager = null;
  11788. }
  11789. this.pdfDocument = pdfDocument;
  11790. if (!pdfDocument) {
  11791. return;
  11792. }
  11793. const pagesCount = pdfDocument.numPages;
  11794. const firstPagePromise = pdfDocument.getPage(1);
  11795. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({
  11796. intent: "display"
  11797. });
  11798. const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve();
  11799. const {
  11800. eventBus,
  11801. pageColors,
  11802. viewer
  11803. } = this;
  11804. this.#eventAbortController = new AbortController();
  11805. const {
  11806. signal
  11807. } = this.#eventAbortController;
  11808. if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  11809. console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");
  11810. const mode = this._scrollMode = ScrollMode.PAGE;
  11811. eventBus.dispatch("scrollmodechanged", {
  11812. source: this,
  11813. mode
  11814. });
  11815. }
  11816. this._pagesCapability.promise.then(() => {
  11817. eventBus.dispatch("pagesloaded", {
  11818. source: this,
  11819. pagesCount
  11820. });
  11821. }, () => {});
  11822. const onBeforeDraw = evt => {
  11823. const pageView = this._pages[evt.pageNumber - 1];
  11824. if (!pageView) {
  11825. return;
  11826. }
  11827. this.#buffer.push(pageView);
  11828. };
  11829. eventBus._on("pagerender", onBeforeDraw, {
  11830. signal
  11831. });
  11832. const onAfterDraw = evt => {
  11833. if (evt.cssTransform || evt.isDetailView) {
  11834. return;
  11835. }
  11836. this._onePageRenderedCapability.resolve({
  11837. timestamp: evt.timestamp
  11838. });
  11839. eventBus._off("pagerendered", onAfterDraw);
  11840. };
  11841. eventBus._on("pagerendered", onAfterDraw, {
  11842. signal
  11843. });
  11844. Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => {
  11845. if (pdfDocument !== this.pdfDocument) {
  11846. return;
  11847. }
  11848. this._firstPageCapability.resolve(firstPdfPage);
  11849. this._optionalContentConfigPromise = optionalContentConfigPromise;
  11850. const {
  11851. annotationEditorMode,
  11852. annotationMode,
  11853. textLayerMode
  11854. } = this.#initializePermissions(permissions);
  11855. if (textLayerMode !== TextLayerMode.DISABLE) {
  11856. const element = this.#hiddenCopyElement = document.createElement("div");
  11857. element.id = "hiddenCopyElement";
  11858. viewer.before(element);
  11859. }
  11860. if (annotationEditorMode !== AnnotationEditorType.DISABLE) {
  11861. const mode = annotationEditorMode;
  11862. if (pdfDocument.isPureXfa) {
  11863. console.warn("Warning: XFA-editing is not implemented.");
  11864. } else if (isValidAnnotationEditorMode(mode)) {
  11865. this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, this.#signatureManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom);
  11866. eventBus.dispatch("annotationeditoruimanager", {
  11867. source: this,
  11868. uiManager: this.#annotationEditorUIManager
  11869. });
  11870. if (mode !== AnnotationEditorType.NONE) {
  11871. this.#preloadEditingData(mode);
  11872. this.#annotationEditorUIManager.updateMode(mode);
  11873. }
  11874. } else {
  11875. console.error(`Invalid AnnotationEditor mode: ${mode}`);
  11876. }
  11877. }
  11878. const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer;
  11879. const scale = this.currentScale;
  11880. const viewport = firstPdfPage.getViewport({
  11881. scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS
  11882. });
  11883. viewer.style.setProperty("--scale-factor", viewport.scale);
  11884. if (pageColors?.background) {
  11885. viewer.style.setProperty("--page-bg-color", pageColors.background);
  11886. }
  11887. if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") {
  11888. viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight"));
  11889. viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText"));
  11890. }
  11891. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  11892. const pageView = new PDFPageView({
  11893. container: viewerElement,
  11894. eventBus,
  11895. id: pageNum,
  11896. scale,
  11897. defaultViewport: viewport.clone(),
  11898. optionalContentConfigPromise,
  11899. renderingQueue: this.renderingQueue,
  11900. textLayerMode,
  11901. annotationMode,
  11902. imageResourcesPath: this.imageResourcesPath,
  11903. maxCanvasPixels: this.maxCanvasPixels,
  11904. maxCanvasDim: this.maxCanvasDim,
  11905. enableDetailCanvas: this.enableDetailCanvas,
  11906. pageColors,
  11907. l10n: this.l10n,
  11908. layerProperties: this._layerProperties,
  11909. enableHWA: this.#enableHWA,
  11910. enableAutoLinking: this.#enableAutoLinking
  11911. });
  11912. this._pages.push(pageView);
  11913. }
  11914. this._pages[0]?.setPdfPage(firstPdfPage);
  11915. if (this._scrollMode === ScrollMode.PAGE) {
  11916. this.#ensurePageViewVisible();
  11917. } else if (this._spreadMode !== SpreadMode.NONE) {
  11918. this._updateSpreadMode();
  11919. }
  11920. this.#onePageRenderedOrForceFetch(signal).then(async () => {
  11921. if (pdfDocument !== this.pdfDocument) {
  11922. return;
  11923. }
  11924. this.findController?.setDocument(pdfDocument);
  11925. this._scriptingManager?.setDocument(pdfDocument);
  11926. if (this.#hiddenCopyElement) {
  11927. document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), {
  11928. signal
  11929. });
  11930. }
  11931. if (this.#annotationEditorUIManager) {
  11932. eventBus.dispatch("annotationeditormodechanged", {
  11933. source: this,
  11934. mode: this.#annotationEditorMode
  11935. });
  11936. }
  11937. if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) {
  11938. this._pagesCapability.resolve();
  11939. return;
  11940. }
  11941. let getPagesLeft = pagesCount - 1;
  11942. if (getPagesLeft <= 0) {
  11943. this._pagesCapability.resolve();
  11944. return;
  11945. }
  11946. for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) {
  11947. const promise = pdfDocument.getPage(pageNum).then(pdfPage => {
  11948. const pageView = this._pages[pageNum - 1];
  11949. if (!pageView.pdfPage) {
  11950. pageView.setPdfPage(pdfPage);
  11951. }
  11952. if (--getPagesLeft === 0) {
  11953. this._pagesCapability.resolve();
  11954. }
  11955. }, reason => {
  11956. console.error(`Unable to get page ${pageNum} to initialize viewer`, reason);
  11957. if (--getPagesLeft === 0) {
  11958. this._pagesCapability.resolve();
  11959. }
  11960. });
  11961. if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) {
  11962. await promise;
  11963. }
  11964. }
  11965. });
  11966. eventBus.dispatch("pagesinit", {
  11967. source: this
  11968. });
  11969. pdfDocument.getMetadata().then(({
  11970. info
  11971. }) => {
  11972. if (pdfDocument !== this.pdfDocument) {
  11973. return;
  11974. }
  11975. if (info.Language) {
  11976. viewer.lang = info.Language;
  11977. }
  11978. });
  11979. if (this.defaultRenderingQueue) {
  11980. this.update();
  11981. }
  11982. }).catch(reason => {
  11983. console.error("Unable to initialize viewer", reason);
  11984. this._pagesCapability.reject(reason);
  11985. });
  11986. }
  11987. setPageLabels(labels) {
  11988. if (!this.pdfDocument) {
  11989. return;
  11990. }
  11991. if (!labels) {
  11992. this._pageLabels = null;
  11993. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  11994. this._pageLabels = null;
  11995. console.error(`setPageLabels: Invalid page labels.`);
  11996. } else {
  11997. this._pageLabels = labels;
  11998. }
  11999. for (let i = 0, ii = this._pages.length; i < ii; i++) {
  12000. this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null);
  12001. }
  12002. }
  12003. _resetView() {
  12004. this._pages = [];
  12005. this._currentPageNumber = 1;
  12006. this._currentScale = UNKNOWN_SCALE;
  12007. this._currentScaleValue = null;
  12008. this._pageLabels = null;
  12009. this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  12010. this._location = null;
  12011. this._pagesRotation = 0;
  12012. this._optionalContentConfigPromise = null;
  12013. this._firstPageCapability = Promise.withResolvers();
  12014. this._onePageRenderedCapability = Promise.withResolvers();
  12015. this._pagesCapability = Promise.withResolvers();
  12016. this._scrollMode = ScrollMode.VERTICAL;
  12017. this._previousScrollMode = ScrollMode.UNKNOWN;
  12018. this._spreadMode = SpreadMode.NONE;
  12019. this.#scrollModePageState = {
  12020. previousPageNumber: 1,
  12021. scrollDown: true,
  12022. pages: []
  12023. };
  12024. this.#eventAbortController?.abort();
  12025. this.#eventAbortController = null;
  12026. this.viewer.textContent = "";
  12027. this._updateScrollMode();
  12028. this.viewer.removeAttribute("lang");
  12029. this.#hiddenCopyElement?.remove();
  12030. this.#hiddenCopyElement = null;
  12031. this.#cleanupTimeouts();
  12032. this.#cleanupSwitchAnnotationEditorMode();
  12033. }
  12034. #ensurePageViewVisible() {
  12035. if (this._scrollMode !== ScrollMode.PAGE) {
  12036. throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");
  12037. }
  12038. const pageNumber = this._currentPageNumber,
  12039. state = this.#scrollModePageState,
  12040. viewer = this.viewer;
  12041. viewer.textContent = "";
  12042. state.pages.length = 0;
  12043. if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) {
  12044. const pageView = this._pages[pageNumber - 1];
  12045. viewer.append(pageView.div);
  12046. state.pages.push(pageView);
  12047. } else {
  12048. const pageIndexSet = new Set(),
  12049. parity = this._spreadMode - 1;
  12050. if (parity === -1) {
  12051. pageIndexSet.add(pageNumber - 1);
  12052. } else if (pageNumber % 2 !== parity) {
  12053. pageIndexSet.add(pageNumber - 1);
  12054. pageIndexSet.add(pageNumber);
  12055. } else {
  12056. pageIndexSet.add(pageNumber - 2);
  12057. pageIndexSet.add(pageNumber - 1);
  12058. }
  12059. const spread = document.createElement("div");
  12060. spread.className = "spread";
  12061. if (this.isInPresentationMode) {
  12062. const dummyPage = document.createElement("div");
  12063. dummyPage.className = "dummyPage";
  12064. spread.append(dummyPage);
  12065. }
  12066. for (const i of pageIndexSet) {
  12067. const pageView = this._pages[i];
  12068. if (!pageView) {
  12069. continue;
  12070. }
  12071. spread.append(pageView.div);
  12072. state.pages.push(pageView);
  12073. }
  12074. viewer.append(spread);
  12075. }
  12076. state.scrollDown = pageNumber >= state.previousPageNumber;
  12077. state.previousPageNumber = pageNumber;
  12078. }
  12079. _scrollUpdate() {
  12080. if (this.pagesCount === 0) {
  12081. return;
  12082. }
  12083. if (this.#scrollTimeoutId) {
  12084. clearTimeout(this.#scrollTimeoutId);
  12085. }
  12086. this.#scrollTimeoutId = setTimeout(() => {
  12087. this.#scrollTimeoutId = null;
  12088. this.update();
  12089. }, 100);
  12090. this.update();
  12091. }
  12092. #scrollIntoView(pageView, pageSpot = null) {
  12093. const {
  12094. div,
  12095. id
  12096. } = pageView;
  12097. if (this._currentPageNumber !== id) {
  12098. this._setCurrentPageNumber(id);
  12099. }
  12100. if (this._scrollMode === ScrollMode.PAGE) {
  12101. this.#ensurePageViewVisible();
  12102. this.update();
  12103. }
  12104. if (!pageSpot && !this.isInPresentationMode) {
  12105. const left = div.offsetLeft + div.clientLeft,
  12106. right = left + div.clientWidth;
  12107. const {
  12108. scrollLeft,
  12109. clientWidth
  12110. } = this.container;
  12111. if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) {
  12112. pageSpot = {
  12113. left: 0,
  12114. top: 0
  12115. };
  12116. }
  12117. }
  12118. scrollIntoView(div, pageSpot);
  12119. if (!this._currentScaleValue && this._location) {
  12120. this._location = null;
  12121. }
  12122. }
  12123. #isSameScale(newScale) {
  12124. return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15;
  12125. }
  12126. #setScaleUpdatePages(newScale, newValue, {
  12127. noScroll = false,
  12128. preset = false,
  12129. drawingDelay = -1,
  12130. origin = null
  12131. }) {
  12132. this._currentScaleValue = newValue.toString();
  12133. if (this.#isSameScale(newScale)) {
  12134. if (preset) {
  12135. this.eventBus.dispatch("scalechanging", {
  12136. source: this,
  12137. scale: newScale,
  12138. presetValue: newValue
  12139. });
  12140. }
  12141. return;
  12142. }
  12143. this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS);
  12144. const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000;
  12145. this.refresh(true, {
  12146. scale: newScale,
  12147. drawingDelay: postponeDrawing ? drawingDelay : -1
  12148. });
  12149. if (postponeDrawing) {
  12150. this.#scaleTimeoutId = setTimeout(() => {
  12151. this.#scaleTimeoutId = null;
  12152. this.refresh();
  12153. }, drawingDelay);
  12154. }
  12155. const previousScale = this._currentScale;
  12156. this._currentScale = newScale;
  12157. if (!noScroll) {
  12158. let page = this._currentPageNumber,
  12159. dest;
  12160. if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  12161. page = this._location.pageNumber;
  12162. dest = [null, {
  12163. name: "XYZ"
  12164. }, this._location.left, this._location.top, null];
  12165. }
  12166. this.scrollPageIntoView({
  12167. pageNumber: page,
  12168. destArray: dest,
  12169. allowNegativeOffset: true
  12170. });
  12171. if (Array.isArray(origin)) {
  12172. const scaleDiff = newScale / previousScale - 1;
  12173. const [top, left] = this.containerTopLeft;
  12174. this.container.scrollLeft += (origin[0] - left) * scaleDiff;
  12175. this.container.scrollTop += (origin[1] - top) * scaleDiff;
  12176. }
  12177. }
  12178. this.eventBus.dispatch("scalechanging", {
  12179. source: this,
  12180. scale: newScale,
  12181. presetValue: preset ? newValue : undefined
  12182. });
  12183. if (this.defaultRenderingQueue) {
  12184. this.update();
  12185. }
  12186. }
  12187. get #pageWidthScaleFactor() {
  12188. if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) {
  12189. return 2;
  12190. }
  12191. return 1;
  12192. }
  12193. #setScale(value, options) {
  12194. let scale = parseFloat(value);
  12195. if (scale > 0) {
  12196. options.preset = false;
  12197. this.#setScaleUpdatePages(scale, value, options);
  12198. } else {
  12199. const currentPage = this._pages[this._currentPageNumber - 1];
  12200. if (!currentPage) {
  12201. return;
  12202. }
  12203. let hPadding = SCROLLBAR_PADDING,
  12204. vPadding = VERTICAL_PADDING;
  12205. if (this.isInPresentationMode) {
  12206. hPadding = vPadding = 4;
  12207. if (this._spreadMode !== SpreadMode.NONE) {
  12208. hPadding *= 2;
  12209. }
  12210. } else if (this.removePageBorders) {
  12211. hPadding = vPadding = 0;
  12212. } else if (this._scrollMode === ScrollMode.HORIZONTAL) {
  12213. [hPadding, vPadding] = [vPadding, hPadding];
  12214. }
  12215. const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor;
  12216. const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  12217. switch (value) {
  12218. case "page-actual":
  12219. scale = 1;
  12220. break;
  12221. case "page-width":
  12222. scale = pageWidthScale;
  12223. break;
  12224. case "page-height":
  12225. scale = pageHeightScale;
  12226. break;
  12227. case "page-fit":
  12228. scale = Math.min(pageWidthScale, pageHeightScale);
  12229. break;
  12230. case "auto":
  12231. const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale);
  12232. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  12233. break;
  12234. default:
  12235. console.error(`#setScale: "${value}" is an unknown zoom value.`);
  12236. return;
  12237. }
  12238. options.preset = true;
  12239. this.#setScaleUpdatePages(scale, value, options);
  12240. }
  12241. }
  12242. #resetCurrentPageView() {
  12243. const pageView = this._pages[this._currentPageNumber - 1];
  12244. if (this.isInPresentationMode) {
  12245. this.#setScale(this._currentScaleValue, {
  12246. noScroll: true
  12247. });
  12248. }
  12249. this.#scrollIntoView(pageView);
  12250. }
  12251. pageLabelToPageNumber(label) {
  12252. if (!this._pageLabels) {
  12253. return null;
  12254. }
  12255. const i = this._pageLabels.indexOf(label);
  12256. if (i < 0) {
  12257. return null;
  12258. }
  12259. return i + 1;
  12260. }
  12261. scrollPageIntoView({
  12262. pageNumber,
  12263. destArray = null,
  12264. allowNegativeOffset = false,
  12265. ignoreDestinationZoom = false
  12266. }) {
  12267. if (!this.pdfDocument) {
  12268. return;
  12269. }
  12270. const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1];
  12271. if (!pageView) {
  12272. console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`);
  12273. return;
  12274. }
  12275. if (this.isInPresentationMode || !destArray) {
  12276. this._setCurrentPageNumber(pageNumber, true);
  12277. return;
  12278. }
  12279. let x = 0,
  12280. y = 0;
  12281. let width = 0,
  12282. height = 0,
  12283. widthScale,
  12284. heightScale;
  12285. const changeOrientation = pageView.rotation % 180 !== 0;
  12286. const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS;
  12287. const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS;
  12288. let scale = 0;
  12289. switch (destArray[1].name) {
  12290. case "XYZ":
  12291. x = destArray[2];
  12292. y = destArray[3];
  12293. scale = destArray[4];
  12294. x = x !== null ? x : 0;
  12295. y = y !== null ? y : pageHeight;
  12296. break;
  12297. case "Fit":
  12298. case "FitB":
  12299. scale = "page-fit";
  12300. break;
  12301. case "FitH":
  12302. case "FitBH":
  12303. y = destArray[2];
  12304. scale = "page-width";
  12305. if (y === null && this._location) {
  12306. x = this._location.left;
  12307. y = this._location.top;
  12308. } else if (typeof y !== "number" || y < 0) {
  12309. y = pageHeight;
  12310. }
  12311. break;
  12312. case "FitV":
  12313. case "FitBV":
  12314. x = destArray[2];
  12315. width = pageWidth;
  12316. height = pageHeight;
  12317. scale = "page-height";
  12318. break;
  12319. case "FitR":
  12320. x = destArray[2];
  12321. y = destArray[3];
  12322. width = destArray[4] - x;
  12323. height = destArray[5] - y;
  12324. let hPadding = SCROLLBAR_PADDING,
  12325. vPadding = VERTICAL_PADDING;
  12326. if (this.removePageBorders) {
  12327. hPadding = vPadding = 0;
  12328. }
  12329. widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS;
  12330. heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS;
  12331. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  12332. break;
  12333. default:
  12334. console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`);
  12335. return;
  12336. }
  12337. if (!ignoreDestinationZoom) {
  12338. if (scale && scale !== this._currentScale) {
  12339. this.currentScaleValue = scale;
  12340. } else if (this._currentScale === UNKNOWN_SCALE) {
  12341. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  12342. }
  12343. }
  12344. if (scale === "page-fit" && !destArray[4]) {
  12345. this.#scrollIntoView(pageView);
  12346. return;
  12347. }
  12348. const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)];
  12349. let left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  12350. let top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  12351. if (!allowNegativeOffset) {
  12352. left = Math.max(left, 0);
  12353. top = Math.max(top, 0);
  12354. }
  12355. this.#scrollIntoView(pageView, {
  12356. left,
  12357. top
  12358. });
  12359. }
  12360. _updateLocation(firstPage) {
  12361. const currentScale = this._currentScale;
  12362. const currentScaleValue = this._currentScaleValue;
  12363. const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  12364. const pageNumber = firstPage.id;
  12365. const currentPageView = this._pages[pageNumber - 1];
  12366. const container = this.container;
  12367. const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  12368. const intLeft = Math.round(topLeft[0]);
  12369. const intTop = Math.round(topLeft[1]);
  12370. let pdfOpenParams = `#page=${pageNumber}`;
  12371. if (!this.isInPresentationMode) {
  12372. pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`;
  12373. }
  12374. this._location = {
  12375. pageNumber,
  12376. scale: normalizedScaleValue,
  12377. top: intTop,
  12378. left: intLeft,
  12379. rotation: this._pagesRotation,
  12380. pdfOpenParams
  12381. };
  12382. }
  12383. update() {
  12384. const visible = this._getVisiblePages();
  12385. const visiblePages = visible.views,
  12386. numVisiblePages = visiblePages.length;
  12387. if (numVisiblePages === 0) {
  12388. return;
  12389. }
  12390. const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1);
  12391. this.#buffer.resize(newCacheSize, visible.ids);
  12392. for (const {
  12393. view,
  12394. visibleArea
  12395. } of visiblePages) {
  12396. view.updateVisibleArea(visibleArea);
  12397. }
  12398. for (const view of this.#buffer) {
  12399. if (!visible.ids.has(view.id)) {
  12400. view.updateVisibleArea(null);
  12401. }
  12402. }
  12403. this.renderingQueue.renderHighestPriority(visible);
  12404. const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL);
  12405. const currentId = this._currentPageNumber;
  12406. let stillFullyVisible = false;
  12407. for (const page of visiblePages) {
  12408. if (page.percent < 100) {
  12409. break;
  12410. }
  12411. if (page.id === currentId && isSimpleLayout) {
  12412. stillFullyVisible = true;
  12413. break;
  12414. }
  12415. }
  12416. this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id);
  12417. this._updateLocation(visible.first);
  12418. this.eventBus.dispatch("updateviewarea", {
  12419. source: this,
  12420. location: this._location
  12421. });
  12422. }
  12423. #switchToEditAnnotationMode() {
  12424. const visible = this._getVisiblePages();
  12425. const pagesToRefresh = [];
  12426. const {
  12427. ids,
  12428. views
  12429. } = visible;
  12430. for (const page of views) {
  12431. const {
  12432. view
  12433. } = page;
  12434. if (!view.hasEditableAnnotations()) {
  12435. ids.delete(view.id);
  12436. continue;
  12437. }
  12438. pagesToRefresh.push(page);
  12439. }
  12440. if (pagesToRefresh.length === 0) {
  12441. return null;
  12442. }
  12443. this.renderingQueue.renderHighestPriority({
  12444. first: pagesToRefresh[0],
  12445. last: pagesToRefresh.at(-1),
  12446. views: pagesToRefresh,
  12447. ids
  12448. });
  12449. return ids;
  12450. }
  12451. containsElement(element) {
  12452. return this.container.contains(element);
  12453. }
  12454. focus() {
  12455. this.container.focus();
  12456. }
  12457. get _isContainerRtl() {
  12458. return getComputedStyle(this.container).direction === "rtl";
  12459. }
  12460. get isInPresentationMode() {
  12461. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  12462. }
  12463. get isChangingPresentationMode() {
  12464. return this.presentationModeState === PresentationModeState.CHANGING;
  12465. }
  12466. get isHorizontalScrollbarEnabled() {
  12467. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  12468. }
  12469. get isVerticalScrollbarEnabled() {
  12470. return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight;
  12471. }
  12472. _getVisiblePages() {
  12473. const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages,
  12474. horizontal = this._scrollMode === ScrollMode.HORIZONTAL,
  12475. rtl = horizontal && this._isContainerRtl;
  12476. return getVisibleElements({
  12477. scrollEl: this.container,
  12478. views,
  12479. sortByVisibility: true,
  12480. horizontal,
  12481. rtl
  12482. });
  12483. }
  12484. cleanup() {
  12485. for (const pageView of this._pages) {
  12486. if (pageView.renderingState !== RenderingStates.FINISHED) {
  12487. pageView.reset();
  12488. }
  12489. }
  12490. }
  12491. _cancelRendering() {
  12492. for (const pageView of this._pages) {
  12493. pageView.cancelRendering();
  12494. }
  12495. }
  12496. async #ensurePdfPageLoaded(pageView) {
  12497. if (pageView.pdfPage) {
  12498. return pageView.pdfPage;
  12499. }
  12500. try {
  12501. const pdfPage = await this.pdfDocument.getPage(pageView.id);
  12502. if (!pageView.pdfPage) {
  12503. pageView.setPdfPage(pdfPage);
  12504. }
  12505. return pdfPage;
  12506. } catch (reason) {
  12507. console.error("Unable to get page for page view", reason);
  12508. return null;
  12509. }
  12510. }
  12511. #getScrollAhead(visible) {
  12512. if (visible.first?.id === 1) {
  12513. return true;
  12514. } else if (visible.last?.id === this.pagesCount) {
  12515. return false;
  12516. }
  12517. switch (this._scrollMode) {
  12518. case ScrollMode.PAGE:
  12519. return this.#scrollModePageState.scrollDown;
  12520. case ScrollMode.HORIZONTAL:
  12521. return this.scroll.right;
  12522. }
  12523. return this.scroll.down;
  12524. }
  12525. forceRendering(currentlyVisiblePages) {
  12526. const visiblePages = currentlyVisiblePages || this._getVisiblePages();
  12527. const scrollAhead = this.#getScrollAhead(visiblePages);
  12528. const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL;
  12529. const ignoreDetailViews = this.#scaleTimeoutId !== null || this.#scrollTimeoutId !== null && visiblePages.views.some(page => page.detailView?.renderingCancelled);
  12530. const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra, ignoreDetailViews);
  12531. if (pageView) {
  12532. this.#ensurePdfPageLoaded(pageView).then(() => {
  12533. this.renderingQueue.renderView(pageView);
  12534. });
  12535. return true;
  12536. }
  12537. return false;
  12538. }
  12539. get hasEqualPageSizes() {
  12540. const firstPageView = this._pages[0];
  12541. for (let i = 1, ii = this._pages.length; i < ii; ++i) {
  12542. const pageView = this._pages[i];
  12543. if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) {
  12544. return false;
  12545. }
  12546. }
  12547. return true;
  12548. }
  12549. getPagesOverview() {
  12550. let initialOrientation;
  12551. return this._pages.map(pageView => {
  12552. const viewport = pageView.pdfPage.getViewport({
  12553. scale: 1
  12554. });
  12555. const orientation = isPortraitOrientation(viewport);
  12556. if (initialOrientation === undefined) {
  12557. initialOrientation = orientation;
  12558. } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) {
  12559. return {
  12560. width: viewport.height,
  12561. height: viewport.width,
  12562. rotation: (viewport.rotation - 90) % 360
  12563. };
  12564. }
  12565. return {
  12566. width: viewport.width,
  12567. height: viewport.height,
  12568. rotation: viewport.rotation
  12569. };
  12570. });
  12571. }
  12572. get optionalContentConfigPromise() {
  12573. if (!this.pdfDocument) {
  12574. return Promise.resolve(null);
  12575. }
  12576. if (!this._optionalContentConfigPromise) {
  12577. console.error("optionalContentConfigPromise: Not initialized yet.");
  12578. return this.pdfDocument.getOptionalContentConfig({
  12579. intent: "display"
  12580. });
  12581. }
  12582. return this._optionalContentConfigPromise;
  12583. }
  12584. set optionalContentConfigPromise(promise) {
  12585. if (!(promise instanceof Promise)) {
  12586. throw new Error(`Invalid optionalContentConfigPromise: ${promise}`);
  12587. }
  12588. if (!this.pdfDocument) {
  12589. return;
  12590. }
  12591. if (!this._optionalContentConfigPromise) {
  12592. return;
  12593. }
  12594. this._optionalContentConfigPromise = promise;
  12595. this.refresh(false, {
  12596. optionalContentConfigPromise: promise
  12597. });
  12598. this.eventBus.dispatch("optionalcontentconfigchanged", {
  12599. source: this,
  12600. promise
  12601. });
  12602. }
  12603. get scrollMode() {
  12604. return this._scrollMode;
  12605. }
  12606. set scrollMode(mode) {
  12607. if (this._scrollMode === mode) {
  12608. return;
  12609. }
  12610. if (!isValidScrollMode(mode)) {
  12611. throw new Error(`Invalid scroll mode: ${mode}`);
  12612. }
  12613. if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  12614. return;
  12615. }
  12616. this._previousScrollMode = this._scrollMode;
  12617. this._scrollMode = mode;
  12618. this.eventBus.dispatch("scrollmodechanged", {
  12619. source: this,
  12620. mode
  12621. });
  12622. this._updateScrollMode(this._currentPageNumber);
  12623. }
  12624. _updateScrollMode(pageNumber = null) {
  12625. const scrollMode = this._scrollMode,
  12626. viewer = this.viewer;
  12627. viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL);
  12628. viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED);
  12629. if (!this.pdfDocument || !pageNumber) {
  12630. return;
  12631. }
  12632. if (scrollMode === ScrollMode.PAGE) {
  12633. this.#ensurePageViewVisible();
  12634. } else if (this._previousScrollMode === ScrollMode.PAGE) {
  12635. this._updateSpreadMode();
  12636. }
  12637. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  12638. this.#setScale(this._currentScaleValue, {
  12639. noScroll: true
  12640. });
  12641. }
  12642. this._setCurrentPageNumber(pageNumber, true);
  12643. this.update();
  12644. }
  12645. get spreadMode() {
  12646. return this._spreadMode;
  12647. }
  12648. set spreadMode(mode) {
  12649. if (this._spreadMode === mode) {
  12650. return;
  12651. }
  12652. if (!isValidSpreadMode(mode)) {
  12653. throw new Error(`Invalid spread mode: ${mode}`);
  12654. }
  12655. this._spreadMode = mode;
  12656. this.eventBus.dispatch("spreadmodechanged", {
  12657. source: this,
  12658. mode
  12659. });
  12660. this._updateSpreadMode(this._currentPageNumber);
  12661. }
  12662. _updateSpreadMode(pageNumber = null) {
  12663. if (!this.pdfDocument) {
  12664. return;
  12665. }
  12666. const viewer = this.viewer,
  12667. pages = this._pages;
  12668. if (this._scrollMode === ScrollMode.PAGE) {
  12669. this.#ensurePageViewVisible();
  12670. } else {
  12671. viewer.textContent = "";
  12672. if (this._spreadMode === SpreadMode.NONE) {
  12673. for (const pageView of this._pages) {
  12674. viewer.append(pageView.div);
  12675. }
  12676. } else {
  12677. const parity = this._spreadMode - 1;
  12678. let spread = null;
  12679. for (let i = 0, ii = pages.length; i < ii; ++i) {
  12680. if (spread === null) {
  12681. spread = document.createElement("div");
  12682. spread.className = "spread";
  12683. viewer.append(spread);
  12684. } else if (i % 2 === parity) {
  12685. spread = spread.cloneNode(false);
  12686. viewer.append(spread);
  12687. }
  12688. spread.append(pages[i].div);
  12689. }
  12690. }
  12691. }
  12692. if (!pageNumber) {
  12693. return;
  12694. }
  12695. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  12696. this.#setScale(this._currentScaleValue, {
  12697. noScroll: true
  12698. });
  12699. }
  12700. this._setCurrentPageNumber(pageNumber, true);
  12701. this.update();
  12702. }
  12703. _getPageAdvance(currentPageNumber, previous = false) {
  12704. switch (this._scrollMode) {
  12705. case ScrollMode.WRAPPED:
  12706. {
  12707. const {
  12708. views
  12709. } = this._getVisiblePages(),
  12710. pageLayout = new Map();
  12711. for (const {
  12712. id,
  12713. y,
  12714. percent,
  12715. widthPercent
  12716. } of views) {
  12717. if (percent === 0 || widthPercent < 100) {
  12718. continue;
  12719. }
  12720. let yArray = pageLayout.get(y);
  12721. if (!yArray) {
  12722. pageLayout.set(y, yArray ||= []);
  12723. }
  12724. yArray.push(id);
  12725. }
  12726. for (const yArray of pageLayout.values()) {
  12727. const currentIndex = yArray.indexOf(currentPageNumber);
  12728. if (currentIndex === -1) {
  12729. continue;
  12730. }
  12731. const numPages = yArray.length;
  12732. if (numPages === 1) {
  12733. break;
  12734. }
  12735. if (previous) {
  12736. for (let i = currentIndex - 1, ii = 0; i >= ii; i--) {
  12737. const currentId = yArray[i],
  12738. expectedId = yArray[i + 1] - 1;
  12739. if (currentId < expectedId) {
  12740. return currentPageNumber - expectedId;
  12741. }
  12742. }
  12743. } else {
  12744. for (let i = currentIndex + 1, ii = numPages; i < ii; i++) {
  12745. const currentId = yArray[i],
  12746. expectedId = yArray[i - 1] + 1;
  12747. if (currentId > expectedId) {
  12748. return expectedId - currentPageNumber;
  12749. }
  12750. }
  12751. }
  12752. if (previous) {
  12753. const firstId = yArray[0];
  12754. if (firstId < currentPageNumber) {
  12755. return currentPageNumber - firstId + 1;
  12756. }
  12757. } else {
  12758. const lastId = yArray[numPages - 1];
  12759. if (lastId > currentPageNumber) {
  12760. return lastId - currentPageNumber + 1;
  12761. }
  12762. }
  12763. break;
  12764. }
  12765. break;
  12766. }
  12767. case ScrollMode.HORIZONTAL:
  12768. {
  12769. break;
  12770. }
  12771. case ScrollMode.PAGE:
  12772. case ScrollMode.VERTICAL:
  12773. {
  12774. if (this._spreadMode === SpreadMode.NONE) {
  12775. break;
  12776. }
  12777. const parity = this._spreadMode - 1;
  12778. if (previous && currentPageNumber % 2 !== parity) {
  12779. break;
  12780. } else if (!previous && currentPageNumber % 2 === parity) {
  12781. break;
  12782. }
  12783. const {
  12784. views
  12785. } = this._getVisiblePages(),
  12786. expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1;
  12787. for (const {
  12788. id,
  12789. percent,
  12790. widthPercent
  12791. } of views) {
  12792. if (id !== expectedId) {
  12793. continue;
  12794. }
  12795. if (percent > 0 && widthPercent === 100) {
  12796. return 2;
  12797. }
  12798. break;
  12799. }
  12800. break;
  12801. }
  12802. }
  12803. return 1;
  12804. }
  12805. nextPage() {
  12806. const currentPageNumber = this._currentPageNumber,
  12807. pagesCount = this.pagesCount;
  12808. if (currentPageNumber >= pagesCount) {
  12809. return false;
  12810. }
  12811. const advance = this._getPageAdvance(currentPageNumber, false) || 1;
  12812. this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount);
  12813. return true;
  12814. }
  12815. previousPage() {
  12816. const currentPageNumber = this._currentPageNumber;
  12817. if (currentPageNumber <= 1) {
  12818. return false;
  12819. }
  12820. const advance = this._getPageAdvance(currentPageNumber, true) || 1;
  12821. this.currentPageNumber = Math.max(currentPageNumber - advance, 1);
  12822. return true;
  12823. }
  12824. updateScale({
  12825. drawingDelay,
  12826. scaleFactor = null,
  12827. steps = null,
  12828. origin
  12829. }) {
  12830. if (steps === null && scaleFactor === null) {
  12831. throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");
  12832. }
  12833. if (!this.pdfDocument) {
  12834. return;
  12835. }
  12836. let newScale = this._currentScale;
  12837. if (scaleFactor > 0 && scaleFactor !== 1) {
  12838. newScale = Math.round(newScale * scaleFactor * 100) / 100;
  12839. } else if (steps) {
  12840. const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA;
  12841. const round = steps > 0 ? Math.ceil : Math.floor;
  12842. steps = Math.abs(steps);
  12843. do {
  12844. newScale = round((newScale * delta).toFixed(2) * 10) / 10;
  12845. } while (--steps > 0);
  12846. }
  12847. newScale = MathClamp(newScale, MIN_SCALE, MAX_SCALE);
  12848. this.#setScale(newScale, {
  12849. noScroll: false,
  12850. drawingDelay,
  12851. origin
  12852. });
  12853. }
  12854. increaseScale(options = {}) {
  12855. this.updateScale({
  12856. ...options,
  12857. steps: options.steps ?? 1
  12858. });
  12859. }
  12860. decreaseScale(options = {}) {
  12861. this.updateScale({
  12862. ...options,
  12863. steps: -(options.steps ?? 1)
  12864. });
  12865. }
  12866. #updateContainerHeightCss(height = this.container.clientHeight) {
  12867. if (height !== this.#previousContainerHeight) {
  12868. this.#previousContainerHeight = height;
  12869. docStyle.setProperty("--viewer-container-height", `${height}px`);
  12870. }
  12871. }
  12872. #resizeObserverCallback(entries) {
  12873. for (const entry of entries) {
  12874. if (entry.target === this.container) {
  12875. this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize));
  12876. this.#containerTopLeft = null;
  12877. break;
  12878. }
  12879. }
  12880. }
  12881. get containerTopLeft() {
  12882. return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft];
  12883. }
  12884. #cleanupTimeouts() {
  12885. if (this.#scaleTimeoutId !== null) {
  12886. clearTimeout(this.#scaleTimeoutId);
  12887. this.#scaleTimeoutId = null;
  12888. }
  12889. if (this.#scrollTimeoutId !== null) {
  12890. clearTimeout(this.#scrollTimeoutId);
  12891. this.#scrollTimeoutId = null;
  12892. }
  12893. }
  12894. #cleanupSwitchAnnotationEditorMode() {
  12895. this.#switchAnnotationEditorModeAC?.abort();
  12896. this.#switchAnnotationEditorModeAC = null;
  12897. if (this.#switchAnnotationEditorModeTimeoutId !== null) {
  12898. clearTimeout(this.#switchAnnotationEditorModeTimeoutId);
  12899. this.#switchAnnotationEditorModeTimeoutId = null;
  12900. }
  12901. }
  12902. #preloadEditingData(mode) {
  12903. switch (mode) {
  12904. case AnnotationEditorType.STAMP:
  12905. this.#mlManager?.loadModel("altText");
  12906. break;
  12907. case AnnotationEditorType.SIGNATURE:
  12908. this.#signatureManager?.loadSignatures();
  12909. break;
  12910. }
  12911. }
  12912. get annotationEditorMode() {
  12913. return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE;
  12914. }
  12915. set annotationEditorMode({
  12916. mode,
  12917. editId = null,
  12918. isFromKeyboard = false
  12919. }) {
  12920. if (!this.#annotationEditorUIManager) {
  12921. throw new Error(`The AnnotationEditor is not enabled.`);
  12922. }
  12923. if (this.#annotationEditorMode === mode) {
  12924. return;
  12925. }
  12926. if (!isValidAnnotationEditorMode(mode)) {
  12927. throw new Error(`Invalid AnnotationEditor mode: ${mode}`);
  12928. }
  12929. if (!this.pdfDocument) {
  12930. return;
  12931. }
  12932. this.#preloadEditingData(mode);
  12933. const {
  12934. eventBus,
  12935. pdfDocument
  12936. } = this;
  12937. const updater = async () => {
  12938. this.#cleanupSwitchAnnotationEditorMode();
  12939. this.#annotationEditorMode = mode;
  12940. await this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard);
  12941. if (mode !== this.#annotationEditorMode || pdfDocument !== this.pdfDocument) {
  12942. return;
  12943. }
  12944. eventBus.dispatch("annotationeditormodechanged", {
  12945. source: this,
  12946. mode
  12947. });
  12948. };
  12949. if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) {
  12950. const isEditing = mode !== AnnotationEditorType.NONE;
  12951. if (!isEditing) {
  12952. this.pdfDocument.annotationStorage.resetModifiedIds();
  12953. }
  12954. for (const pageView of this._pages) {
  12955. pageView.toggleEditingMode(isEditing);
  12956. }
  12957. const idsToRefresh = this.#switchToEditAnnotationMode();
  12958. if (isEditing && idsToRefresh) {
  12959. this.#cleanupSwitchAnnotationEditorMode();
  12960. this.#switchAnnotationEditorModeAC = new AbortController();
  12961. const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]);
  12962. eventBus._on("pagerendered", ({
  12963. pageNumber
  12964. }) => {
  12965. idsToRefresh.delete(pageNumber);
  12966. if (idsToRefresh.size === 0) {
  12967. this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0);
  12968. }
  12969. }, {
  12970. signal
  12971. });
  12972. return;
  12973. }
  12974. }
  12975. updater();
  12976. }
  12977. refresh(noUpdate = false, updateArgs = Object.create(null)) {
  12978. if (!this.pdfDocument) {
  12979. return;
  12980. }
  12981. for (const pageView of this._pages) {
  12982. pageView.update(updateArgs);
  12983. }
  12984. this.#cleanupTimeouts();
  12985. if (!noUpdate) {
  12986. this.update();
  12987. }
  12988. }
  12989. }
  12990. ;// ./web/secondary_toolbar.js
  12991. class SecondaryToolbar {
  12992. #opts;
  12993. constructor(options, eventBus) {
  12994. this.#opts = options;
  12995. const buttons = [{
  12996. element: options.presentationModeButton,
  12997. eventName: "presentationmode",
  12998. close: true
  12999. }, {
  13000. element: options.printButton,
  13001. eventName: "print",
  13002. close: true
  13003. }, {
  13004. element: options.downloadButton,
  13005. eventName: "download",
  13006. close: true
  13007. }, {
  13008. element: options.viewBookmarkButton,
  13009. eventName: null,
  13010. close: true
  13011. }, {
  13012. element: options.firstPageButton,
  13013. eventName: "firstpage",
  13014. close: true
  13015. }, {
  13016. element: options.lastPageButton,
  13017. eventName: "lastpage",
  13018. close: true
  13019. }, {
  13020. element: options.pageRotateCwButton,
  13021. eventName: "rotatecw",
  13022. close: false
  13023. }, {
  13024. element: options.pageRotateCcwButton,
  13025. eventName: "rotateccw",
  13026. close: false
  13027. }, {
  13028. element: options.cursorSelectToolButton,
  13029. eventName: "switchcursortool",
  13030. eventDetails: {
  13031. tool: CursorTool.SELECT
  13032. },
  13033. close: true
  13034. }, {
  13035. element: options.cursorHandToolButton,
  13036. eventName: "switchcursortool",
  13037. eventDetails: {
  13038. tool: CursorTool.HAND
  13039. },
  13040. close: true
  13041. }, {
  13042. element: options.scrollPageButton,
  13043. eventName: "switchscrollmode",
  13044. eventDetails: {
  13045. mode: ScrollMode.PAGE
  13046. },
  13047. close: true
  13048. }, {
  13049. element: options.scrollVerticalButton,
  13050. eventName: "switchscrollmode",
  13051. eventDetails: {
  13052. mode: ScrollMode.VERTICAL
  13053. },
  13054. close: true
  13055. }, {
  13056. element: options.scrollHorizontalButton,
  13057. eventName: "switchscrollmode",
  13058. eventDetails: {
  13059. mode: ScrollMode.HORIZONTAL
  13060. },
  13061. close: true
  13062. }, {
  13063. element: options.scrollWrappedButton,
  13064. eventName: "switchscrollmode",
  13065. eventDetails: {
  13066. mode: ScrollMode.WRAPPED
  13067. },
  13068. close: true
  13069. }, {
  13070. element: options.spreadNoneButton,
  13071. eventName: "switchspreadmode",
  13072. eventDetails: {
  13073. mode: SpreadMode.NONE
  13074. },
  13075. close: true
  13076. }, {
  13077. element: options.spreadOddButton,
  13078. eventName: "switchspreadmode",
  13079. eventDetails: {
  13080. mode: SpreadMode.ODD
  13081. },
  13082. close: true
  13083. }, {
  13084. element: options.spreadEvenButton,
  13085. eventName: "switchspreadmode",
  13086. eventDetails: {
  13087. mode: SpreadMode.EVEN
  13088. },
  13089. close: true
  13090. }, {
  13091. element: options.imageAltTextSettingsButton,
  13092. eventName: "imagealttextsettings",
  13093. close: true
  13094. }, {
  13095. element: options.documentPropertiesButton,
  13096. eventName: "documentproperties",
  13097. close: true
  13098. }];
  13099. buttons.push({
  13100. element: options.openFileButton,
  13101. eventName: "openfile",
  13102. close: true
  13103. });
  13104. this.eventBus = eventBus;
  13105. this.opened = false;
  13106. this.#bindListeners(buttons);
  13107. this.reset();
  13108. }
  13109. get isOpen() {
  13110. return this.opened;
  13111. }
  13112. setPageNumber(pageNumber) {
  13113. this.pageNumber = pageNumber;
  13114. this.#updateUIState();
  13115. }
  13116. setPagesCount(pagesCount) {
  13117. this.pagesCount = pagesCount;
  13118. this.#updateUIState();
  13119. }
  13120. reset() {
  13121. this.pageNumber = 0;
  13122. this.pagesCount = 0;
  13123. this.#updateUIState();
  13124. this.eventBus.dispatch("switchcursortool", {
  13125. source: this,
  13126. reset: true
  13127. });
  13128. this.#scrollModeChanged({
  13129. mode: ScrollMode.VERTICAL
  13130. });
  13131. this.#spreadModeChanged({
  13132. mode: SpreadMode.NONE
  13133. });
  13134. }
  13135. #updateUIState() {
  13136. const {
  13137. firstPageButton,
  13138. lastPageButton,
  13139. pageRotateCwButton,
  13140. pageRotateCcwButton
  13141. } = this.#opts;
  13142. firstPageButton.disabled = this.pageNumber <= 1;
  13143. lastPageButton.disabled = this.pageNumber >= this.pagesCount;
  13144. pageRotateCwButton.disabled = this.pagesCount === 0;
  13145. pageRotateCcwButton.disabled = this.pagesCount === 0;
  13146. }
  13147. #bindListeners(buttons) {
  13148. const {
  13149. eventBus
  13150. } = this;
  13151. const {
  13152. toggleButton
  13153. } = this.#opts;
  13154. toggleButton.addEventListener("click", this.toggle.bind(this));
  13155. for (const {
  13156. element,
  13157. eventName,
  13158. close,
  13159. eventDetails
  13160. } of buttons) {
  13161. element.addEventListener("click", evt => {
  13162. if (eventName !== null) {
  13163. eventBus.dispatch(eventName, {
  13164. source: this,
  13165. ...eventDetails
  13166. });
  13167. }
  13168. if (close) {
  13169. this.close();
  13170. }
  13171. eventBus.dispatch("reporttelemetry", {
  13172. source: this,
  13173. details: {
  13174. type: "buttons",
  13175. data: {
  13176. id: element.id
  13177. }
  13178. }
  13179. });
  13180. });
  13181. }
  13182. eventBus._on("cursortoolchanged", this.#cursorToolChanged.bind(this));
  13183. eventBus._on("scrollmodechanged", this.#scrollModeChanged.bind(this));
  13184. eventBus._on("spreadmodechanged", this.#spreadModeChanged.bind(this));
  13185. }
  13186. #cursorToolChanged({
  13187. tool,
  13188. disabled
  13189. }) {
  13190. const {
  13191. cursorSelectToolButton,
  13192. cursorHandToolButton
  13193. } = this.#opts;
  13194. toggleCheckedBtn(cursorSelectToolButton, tool === CursorTool.SELECT);
  13195. toggleCheckedBtn(cursorHandToolButton, tool === CursorTool.HAND);
  13196. cursorSelectToolButton.disabled = disabled;
  13197. cursorHandToolButton.disabled = disabled;
  13198. }
  13199. #scrollModeChanged({
  13200. mode
  13201. }) {
  13202. const {
  13203. scrollPageButton,
  13204. scrollVerticalButton,
  13205. scrollHorizontalButton,
  13206. scrollWrappedButton,
  13207. spreadNoneButton,
  13208. spreadOddButton,
  13209. spreadEvenButton
  13210. } = this.#opts;
  13211. toggleCheckedBtn(scrollPageButton, mode === ScrollMode.PAGE);
  13212. toggleCheckedBtn(scrollVerticalButton, mode === ScrollMode.VERTICAL);
  13213. toggleCheckedBtn(scrollHorizontalButton, mode === ScrollMode.HORIZONTAL);
  13214. toggleCheckedBtn(scrollWrappedButton, mode === ScrollMode.WRAPPED);
  13215. const forceScrollModePage = this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE;
  13216. scrollPageButton.disabled = forceScrollModePage;
  13217. scrollVerticalButton.disabled = forceScrollModePage;
  13218. scrollHorizontalButton.disabled = forceScrollModePage;
  13219. scrollWrappedButton.disabled = forceScrollModePage;
  13220. const isHorizontal = mode === ScrollMode.HORIZONTAL;
  13221. spreadNoneButton.disabled = isHorizontal;
  13222. spreadOddButton.disabled = isHorizontal;
  13223. spreadEvenButton.disabled = isHorizontal;
  13224. }
  13225. #spreadModeChanged({
  13226. mode
  13227. }) {
  13228. const {
  13229. spreadNoneButton,
  13230. spreadOddButton,
  13231. spreadEvenButton
  13232. } = this.#opts;
  13233. toggleCheckedBtn(spreadNoneButton, mode === SpreadMode.NONE);
  13234. toggleCheckedBtn(spreadOddButton, mode === SpreadMode.ODD);
  13235. toggleCheckedBtn(spreadEvenButton, mode === SpreadMode.EVEN);
  13236. }
  13237. open() {
  13238. if (this.opened) {
  13239. return;
  13240. }
  13241. this.opened = true;
  13242. const {
  13243. toggleButton,
  13244. toolbar
  13245. } = this.#opts;
  13246. toggleExpandedBtn(toggleButton, true, toolbar);
  13247. }
  13248. close() {
  13249. if (!this.opened) {
  13250. return;
  13251. }
  13252. this.opened = false;
  13253. const {
  13254. toggleButton,
  13255. toolbar
  13256. } = this.#opts;
  13257. toggleExpandedBtn(toggleButton, false, toolbar);
  13258. }
  13259. toggle() {
  13260. if (this.opened) {
  13261. this.close();
  13262. } else {
  13263. this.open();
  13264. }
  13265. }
  13266. }
  13267. ;// ./web/signature_manager.js
  13268. const DEFAULT_HEIGHT_IN_PAGE = 40;
  13269. class SignatureManager {
  13270. #addButton;
  13271. #tabsToAltText = null;
  13272. #clearButton;
  13273. #clearDescription;
  13274. #currentEditor;
  13275. #description;
  13276. #dialog;
  13277. #drawCurves = null;
  13278. #drawPlaceholder;
  13279. #drawPath = null;
  13280. #drawPathString = "";
  13281. #drawPoints = null;
  13282. #drawSVG;
  13283. #drawThickness;
  13284. #errorBar;
  13285. #extractedSignatureData = null;
  13286. #imagePath = null;
  13287. #imagePicker;
  13288. #imagePickerLink;
  13289. #imagePlaceholder;
  13290. #imageSVG;
  13291. #saveCheckbox;
  13292. #saveContainer;
  13293. #tabButtons;
  13294. #addSignatureToolbarButton;
  13295. #loadSignaturesPromise = null;
  13296. #typeInput;
  13297. #currentTab = null;
  13298. #currentTabAC = null;
  13299. #hasDescriptionChanged = false;
  13300. #eventBus;
  13301. #l10n;
  13302. #overlayManager;
  13303. #editDescriptionDialog;
  13304. #signatureStorage;
  13305. #uiManager = null;
  13306. static #l10nDescription = null;
  13307. constructor({
  13308. dialog,
  13309. panels,
  13310. typeButton,
  13311. typeInput,
  13312. drawButton,
  13313. drawPlaceholder,
  13314. drawSVG,
  13315. drawThickness,
  13316. imageButton,
  13317. imageSVG,
  13318. imagePlaceholder,
  13319. imagePicker,
  13320. imagePickerLink,
  13321. description,
  13322. clearButton,
  13323. cancelButton,
  13324. addButton,
  13325. errorCloseButton,
  13326. errorBar,
  13327. saveCheckbox,
  13328. saveContainer
  13329. }, editSignatureElements, addSignatureToolbarButton, overlayManager, l10n, signatureStorage, eventBus) {
  13330. this.#addButton = addButton;
  13331. this.#clearButton = clearButton;
  13332. this.#clearDescription = description.lastElementChild;
  13333. this.#description = description.firstElementChild;
  13334. this.#dialog = dialog;
  13335. this.#drawSVG = drawSVG;
  13336. this.#drawPlaceholder = drawPlaceholder;
  13337. this.#drawThickness = drawThickness;
  13338. this.#errorBar = errorBar;
  13339. this.#imageSVG = imageSVG;
  13340. this.#imagePlaceholder = imagePlaceholder;
  13341. this.#imagePicker = imagePicker;
  13342. this.#imagePickerLink = imagePickerLink;
  13343. this.#overlayManager = overlayManager;
  13344. this.#saveCheckbox = saveCheckbox;
  13345. this.#saveContainer = saveContainer;
  13346. this.#addSignatureToolbarButton = addSignatureToolbarButton;
  13347. this.#typeInput = typeInput;
  13348. this.#l10n = l10n;
  13349. this.#signatureStorage = signatureStorage;
  13350. this.#eventBus = eventBus;
  13351. this.#editDescriptionDialog = new EditDescriptionDialog(editSignatureElements, overlayManager);
  13352. SignatureManager.#l10nDescription ||= Object.freeze({
  13353. signature: "pdfjs-editor-add-signature-description-default-when-drawing"
  13354. });
  13355. dialog.addEventListener("close", this.#close.bind(this));
  13356. dialog.addEventListener("contextmenu", e => {
  13357. const {
  13358. target
  13359. } = e;
  13360. if (target !== this.#typeInput && target !== this.#description) {
  13361. e.preventDefault();
  13362. }
  13363. });
  13364. dialog.addEventListener("drop", e => {
  13365. stopEvent(e);
  13366. });
  13367. cancelButton.addEventListener("click", this.#cancel.bind(this));
  13368. addButton.addEventListener("click", this.#add.bind(this));
  13369. clearButton.addEventListener("click", () => {
  13370. this.#reportTelemetry({
  13371. type: "signature",
  13372. action: "pdfjs.signature.clear",
  13373. data: {
  13374. type: this.#currentTab
  13375. }
  13376. });
  13377. this.#initTab(null);
  13378. }, {
  13379. passive: true
  13380. });
  13381. this.#description.addEventListener("input", () => {
  13382. this.#clearDescription.disabled = this.#description.value === "";
  13383. }, {
  13384. passive: true
  13385. });
  13386. this.#clearDescription.addEventListener("click", () => {
  13387. this.#description.value = "";
  13388. this.#clearDescription.disabled = true;
  13389. }, {
  13390. passive: true
  13391. });
  13392. errorCloseButton.addEventListener("click", () => {
  13393. errorBar.hidden = true;
  13394. }, {
  13395. passive: true
  13396. });
  13397. this.#initTabButtons(typeButton, drawButton, imageButton, panels);
  13398. imagePicker.accept = SupportedImageMimeTypes.join(",");
  13399. eventBus._on("storedsignatureschanged", this.#signaturesChanged.bind(this));
  13400. overlayManager.register(dialog);
  13401. }
  13402. #initTabButtons(typeButton, drawButton, imageButton, panels) {
  13403. const buttons = this.#tabButtons = new Map([["type", typeButton], ["draw", drawButton], ["image", imageButton]]);
  13404. const tabCallback = e => {
  13405. for (const [name, button] of buttons) {
  13406. if (button === e.target) {
  13407. button.setAttribute("aria-selected", true);
  13408. button.setAttribute("tabindex", 0);
  13409. panels.setAttribute("data-selected", name);
  13410. this.#initTab(name);
  13411. } else {
  13412. button.setAttribute("aria-selected", false);
  13413. button.setAttribute("tabindex", -1);
  13414. }
  13415. }
  13416. };
  13417. const buttonsArray = Array.from(buttons.values());
  13418. for (let i = 0, ii = buttonsArray.length; i < ii; i++) {
  13419. const button = buttonsArray[i];
  13420. button.addEventListener("click", tabCallback, {
  13421. passive: true
  13422. });
  13423. button.addEventListener("keydown", ({
  13424. key
  13425. }) => {
  13426. if (key !== "ArrowLeft" && key !== "ArrowRight") {
  13427. return;
  13428. }
  13429. buttonsArray[i + (key === "ArrowLeft" ? -1 : 1)]?.focus();
  13430. }, {
  13431. passive: true
  13432. });
  13433. }
  13434. }
  13435. #resetCommon() {
  13436. this.#hasDescriptionChanged = false;
  13437. this.#description.value = "";
  13438. if (this.#currentTab) {
  13439. this.#tabsToAltText.get(this.#currentTab).value = "";
  13440. }
  13441. }
  13442. #resetTab(name) {
  13443. switch (name) {
  13444. case "type":
  13445. this.#typeInput.value = "";
  13446. break;
  13447. case "draw":
  13448. this.#drawCurves = null;
  13449. this.#drawPoints = null;
  13450. this.#drawPathString = "";
  13451. this.#drawPath?.remove();
  13452. this.#drawPath = null;
  13453. this.#drawPlaceholder.hidden = false;
  13454. this.#drawThickness.value = 1;
  13455. break;
  13456. case "image":
  13457. this.#imagePlaceholder.hidden = false;
  13458. this.#imagePath?.remove();
  13459. this.#imagePath = null;
  13460. break;
  13461. }
  13462. }
  13463. #initTab(name) {
  13464. if (name && this.#currentTab === name) {
  13465. return;
  13466. }
  13467. if (this.#currentTab) {
  13468. this.#tabsToAltText.get(this.#currentTab).value = this.#description.value;
  13469. }
  13470. if (name) {
  13471. this.#currentTab = name;
  13472. }
  13473. this.#errorBar.hidden = true;
  13474. const reset = !name;
  13475. if (reset) {
  13476. this.#resetCommon();
  13477. } else {
  13478. this.#description.value = this.#tabsToAltText.get(this.#currentTab).value;
  13479. }
  13480. this.#clearDescription.disabled = this.#description.value === "";
  13481. this.#currentTabAC?.abort();
  13482. this.#currentTabAC = new AbortController();
  13483. switch (this.#currentTab) {
  13484. case "type":
  13485. this.#initTypeTab(reset);
  13486. break;
  13487. case "draw":
  13488. this.#initDrawTab(reset);
  13489. break;
  13490. case "image":
  13491. this.#initImageTab(reset);
  13492. break;
  13493. }
  13494. }
  13495. #disableButtons(value) {
  13496. this.#saveCheckbox.disabled = this.#clearButton.disabled = this.#addButton.disabled = this.#description.disabled = !value;
  13497. }
  13498. #initTypeTab(reset) {
  13499. if (reset) {
  13500. this.#resetTab("type");
  13501. }
  13502. this.#disableButtons(this.#typeInput.value);
  13503. const {
  13504. signal
  13505. } = this.#currentTabAC;
  13506. const options = {
  13507. passive: true,
  13508. signal
  13509. };
  13510. this.#typeInput.addEventListener("input", () => {
  13511. const {
  13512. value
  13513. } = this.#typeInput;
  13514. if (!this.#hasDescriptionChanged) {
  13515. this.#tabsToAltText.get("type").default = this.#description.value = value;
  13516. this.#clearDescription.disabled = value === "";
  13517. }
  13518. this.#disableButtons(value);
  13519. }, options);
  13520. this.#description.addEventListener("input", () => {
  13521. this.#hasDescriptionChanged = this.#typeInput.value !== this.#description.value;
  13522. }, options);
  13523. }
  13524. #initDrawTab(reset) {
  13525. if (reset) {
  13526. this.#resetTab("draw");
  13527. }
  13528. this.#disableButtons(this.#drawPath);
  13529. const {
  13530. signal
  13531. } = this.#currentTabAC;
  13532. const options = {
  13533. signal
  13534. };
  13535. let currentPointerId = NaN;
  13536. const drawCallback = e => {
  13537. const {
  13538. pointerId
  13539. } = e;
  13540. if (!isNaN(currentPointerId) && currentPointerId !== pointerId) {
  13541. return;
  13542. }
  13543. currentPointerId = pointerId;
  13544. e.preventDefault();
  13545. this.#drawSVG.setPointerCapture(pointerId);
  13546. const {
  13547. width: drawWidth,
  13548. height: drawHeight
  13549. } = this.#drawSVG.getBoundingClientRect();
  13550. let {
  13551. offsetX,
  13552. offsetY
  13553. } = e;
  13554. offsetX = Math.round(offsetX);
  13555. offsetY = Math.round(offsetY);
  13556. if (e.target === this.#drawPlaceholder) {
  13557. this.#drawPlaceholder.hidden = true;
  13558. }
  13559. if (!this.#drawCurves) {
  13560. this.#drawCurves = {
  13561. width: drawWidth,
  13562. height: drawHeight,
  13563. thickness: parseInt(this.#drawThickness.value),
  13564. curves: []
  13565. };
  13566. this.#disableButtons(true);
  13567. const svgFactory = new DOMSVGFactory();
  13568. const path = this.#drawPath = svgFactory.createElement("path");
  13569. path.setAttribute("stroke-width", this.#drawThickness.value);
  13570. this.#drawSVG.append(path);
  13571. this.#drawSVG.addEventListener("pointerdown", drawCallback, options);
  13572. this.#drawPlaceholder.removeEventListener("pointerdown", drawCallback);
  13573. if (this.#description.value === "") {
  13574. this.#l10n.get(SignatureManager.#l10nDescription.signature).then(description => {
  13575. this.#tabsToAltText.get("draw").default = description;
  13576. this.#description.value ||= description;
  13577. this.#clearDescription.disabled = this.#description.value === "";
  13578. });
  13579. }
  13580. }
  13581. this.#drawPoints = [offsetX, offsetY];
  13582. this.#drawCurves.curves.push({
  13583. points: this.#drawPoints
  13584. });
  13585. this.#drawPathString += `M ${offsetX} ${offsetY}`;
  13586. this.#drawPath.setAttribute("d", this.#drawPathString);
  13587. const finishDrawAC = new AbortController();
  13588. const listenerDrawOptions = {
  13589. signal: AbortSignal.any([signal, finishDrawAC.signal])
  13590. };
  13591. this.#drawSVG.addEventListener("contextmenu", noContextMenu, listenerDrawOptions);
  13592. this.#drawSVG.addEventListener("pointermove", evt => {
  13593. evt.preventDefault();
  13594. let {
  13595. offsetX: x,
  13596. offsetY: y
  13597. } = evt;
  13598. x = Math.round(x);
  13599. y = Math.round(y);
  13600. const drawPoints = this.#drawPoints;
  13601. if (x < 0 || y < 0 || x > drawWidth || y > drawHeight || x === drawPoints.at(-2) && y === drawPoints.at(-1)) {
  13602. return;
  13603. }
  13604. if (drawPoints.length >= 4) {
  13605. const [x1, y1, x2, y2] = drawPoints.slice(-4);
  13606. this.#drawPathString += `C${(x1 + 5 * x2) / 6} ${(y1 + 5 * y2) / 6} ${(5 * x2 + x) / 6} ${(5 * y2 + y) / 6} ${(x2 + x) / 2} ${(y2 + y) / 2}`;
  13607. } else {
  13608. this.#drawPathString += `L${x} ${y}`;
  13609. }
  13610. drawPoints.push(x, y);
  13611. this.#drawPath.setAttribute("d", this.#drawPathString);
  13612. }, listenerDrawOptions);
  13613. this.#drawSVG.addEventListener("pointerup", evt => {
  13614. const {
  13615. pointerId: pId
  13616. } = evt;
  13617. if (!isNaN(currentPointerId) && currentPointerId !== pId) {
  13618. return;
  13619. }
  13620. currentPointerId = NaN;
  13621. evt.preventDefault();
  13622. this.#drawSVG.releasePointerCapture(pId);
  13623. finishDrawAC.abort();
  13624. if (this.#drawPoints.length === 2) {
  13625. this.#drawPathString += `L${this.#drawPoints[0]} ${this.#drawPoints[1]}`;
  13626. this.#drawPath.setAttribute("d", this.#drawPathString);
  13627. }
  13628. }, listenerDrawOptions);
  13629. };
  13630. if (this.#drawCurves) {
  13631. this.#drawSVG.addEventListener("pointerdown", drawCallback, options);
  13632. } else {
  13633. this.#drawPlaceholder.addEventListener("pointerdown", drawCallback, options);
  13634. }
  13635. this.#drawThickness.addEventListener("input", () => {
  13636. const {
  13637. value: thickness
  13638. } = this.#drawThickness;
  13639. this.#drawThickness.setAttribute("data-l10n-args", JSON.stringify({
  13640. thickness
  13641. }));
  13642. if (!this.#drawCurves) {
  13643. return;
  13644. }
  13645. this.#drawPath.setAttribute("stroke-width", thickness);
  13646. this.#drawCurves.thickness = thickness;
  13647. }, options);
  13648. }
  13649. #initImageTab(reset) {
  13650. if (reset) {
  13651. this.#resetTab("image");
  13652. }
  13653. this.#disableButtons(this.#imagePath);
  13654. const {
  13655. signal
  13656. } = this.#currentTabAC;
  13657. const options = {
  13658. signal
  13659. };
  13660. const passiveOptions = {
  13661. passive: true,
  13662. signal
  13663. };
  13664. this.#imagePickerLink.addEventListener("keydown", e => {
  13665. const {
  13666. key
  13667. } = e;
  13668. if (key === "Enter" || key === " ") {
  13669. stopEvent(e);
  13670. this.#imagePicker.click();
  13671. }
  13672. }, options);
  13673. this.#imagePicker.addEventListener("click", () => {
  13674. this.#dialog.classList.toggle("waiting", true);
  13675. }, passiveOptions);
  13676. this.#imagePicker.addEventListener("change", async () => {
  13677. const file = this.#imagePicker.files?.[0];
  13678. if (!file || !SupportedImageMimeTypes.includes(file.type)) {
  13679. this.#errorBar.hidden = false;
  13680. this.#dialog.classList.toggle("waiting", false);
  13681. return;
  13682. }
  13683. await this.#extractSignature(file);
  13684. }, passiveOptions);
  13685. this.#imagePicker.addEventListener("cancel", () => {
  13686. this.#dialog.classList.toggle("waiting", false);
  13687. }, passiveOptions);
  13688. this.#imagePlaceholder.addEventListener("dragover", e => {
  13689. const {
  13690. dataTransfer
  13691. } = e;
  13692. for (const {
  13693. type
  13694. } of dataTransfer.items) {
  13695. if (!SupportedImageMimeTypes.includes(type)) {
  13696. continue;
  13697. }
  13698. dataTransfer.dropEffect = dataTransfer.effectAllowed === "copy" ? "copy" : "move";
  13699. stopEvent(e);
  13700. return;
  13701. }
  13702. dataTransfer.dropEffect = "none";
  13703. }, options);
  13704. this.#imagePlaceholder.addEventListener("drop", e => {
  13705. const {
  13706. dataTransfer: {
  13707. files
  13708. }
  13709. } = e;
  13710. if (!files?.length) {
  13711. return;
  13712. }
  13713. for (const file of files) {
  13714. if (SupportedImageMimeTypes.includes(file.type)) {
  13715. this.#extractSignature(file);
  13716. break;
  13717. }
  13718. }
  13719. stopEvent(e);
  13720. this.#dialog.classList.toggle("waiting", true);
  13721. }, options);
  13722. }
  13723. async #extractSignature(file) {
  13724. let data;
  13725. try {
  13726. data = await this.#uiManager.imageManager.getFromFile(file);
  13727. } catch (e) {
  13728. console.error("SignatureManager.#extractSignature.", e);
  13729. }
  13730. if (!data) {
  13731. this.#errorBar.hidden = false;
  13732. this.#dialog.classList.toggle("waiting", false);
  13733. return;
  13734. }
  13735. const {
  13736. outline
  13737. } = this.#extractedSignatureData = this.#currentEditor.getFromImage(data.bitmap);
  13738. if (!outline) {
  13739. this.#dialog.classList.toggle("waiting", false);
  13740. return;
  13741. }
  13742. this.#imagePlaceholder.hidden = true;
  13743. this.#disableButtons(true);
  13744. const svgFactory = new DOMSVGFactory();
  13745. const path = this.#imagePath = svgFactory.createElement("path");
  13746. this.#imageSVG.setAttribute("viewBox", outline.viewBox);
  13747. this.#imageSVG.setAttribute("preserveAspectRatio", "xMidYMid meet");
  13748. this.#imageSVG.append(path);
  13749. path.setAttribute("d", outline.toSVGPath());
  13750. this.#tabsToAltText.get("image").default = file.name;
  13751. if (this.#description.value === "") {
  13752. this.#description.value = file.name || "";
  13753. this.#clearDescription.disabled = this.#description.value === "";
  13754. }
  13755. this.#dialog.classList.toggle("waiting", false);
  13756. }
  13757. #getOutlineForType() {
  13758. return this.#currentEditor.getFromText(this.#typeInput.value, window.getComputedStyle(this.#typeInput));
  13759. }
  13760. #getOutlineForDraw() {
  13761. const {
  13762. width,
  13763. height
  13764. } = this.#drawSVG.getBoundingClientRect();
  13765. return this.#currentEditor.getDrawnSignature(this.#drawCurves, width, height);
  13766. }
  13767. #reportTelemetry(data) {
  13768. this.#eventBus.dispatch("reporttelemetry", {
  13769. source: this,
  13770. details: {
  13771. type: "editing",
  13772. data
  13773. }
  13774. });
  13775. }
  13776. #addToolbarButton(signatureData, uuid, description) {
  13777. const {
  13778. curves,
  13779. areContours,
  13780. thickness,
  13781. width,
  13782. height
  13783. } = signatureData;
  13784. const maxDim = Math.max(width, height);
  13785. const outlineData = SignatureExtractor.processDrawnLines({
  13786. lines: {
  13787. curves,
  13788. thickness,
  13789. width,
  13790. height
  13791. },
  13792. pageWidth: maxDim,
  13793. pageHeight: maxDim,
  13794. rotation: 0,
  13795. innerMargin: 0,
  13796. mustSmooth: false,
  13797. areContours
  13798. });
  13799. if (!outlineData) {
  13800. return;
  13801. }
  13802. const {
  13803. outline
  13804. } = outlineData;
  13805. const svgFactory = new DOMSVGFactory();
  13806. const div = document.createElement("div");
  13807. const button = document.createElement("button");
  13808. button.addEventListener("click", () => {
  13809. this.#eventBus.dispatch("switchannotationeditorparams", {
  13810. source: this,
  13811. type: AnnotationEditorParamsType.CREATE,
  13812. value: {
  13813. signatureData: {
  13814. lines: {
  13815. curves,
  13816. thickness,
  13817. width,
  13818. height
  13819. },
  13820. mustSmooth: false,
  13821. areContours,
  13822. description,
  13823. uuid,
  13824. heightInPage: DEFAULT_HEIGHT_IN_PAGE
  13825. }
  13826. }
  13827. });
  13828. });
  13829. div.append(button);
  13830. div.classList.add("toolbarAddSignatureButtonContainer");
  13831. const svg = svgFactory.create(1, 1, true);
  13832. button.append(svg);
  13833. const span = document.createElement("span");
  13834. span.ariaHidden = true;
  13835. button.append(span);
  13836. button.classList.add("toolbarAddSignatureButton");
  13837. button.type = "button";
  13838. span.textContent = description;
  13839. button.setAttribute("data-l10n-id", "pdfjs-editor-add-saved-signature-button");
  13840. button.setAttribute("data-l10n-args", JSON.stringify({
  13841. description
  13842. }));
  13843. button.tabIndex = 0;
  13844. const path = svgFactory.createElement("path");
  13845. svg.append(path);
  13846. svg.setAttribute("viewBox", outline.viewBox);
  13847. svg.setAttribute("preserveAspectRatio", "xMidYMid meet");
  13848. if (areContours) {
  13849. path.classList.add("contours");
  13850. }
  13851. path.setAttribute("d", outline.toSVGPath());
  13852. const deleteButton = document.createElement("button");
  13853. div.append(deleteButton);
  13854. deleteButton.classList.add("toolbarButton", "deleteButton");
  13855. deleteButton.setAttribute("data-l10n-id", "pdfjs-editor-delete-signature-button1");
  13856. deleteButton.type = "button";
  13857. deleteButton.tabIndex = 0;
  13858. deleteButton.addEventListener("click", async () => {
  13859. if (await this.#signatureStorage.delete(uuid)) {
  13860. div.remove();
  13861. this.#reportTelemetry({
  13862. type: "signature",
  13863. action: "pdfjs.signature.delete_saved",
  13864. data: {
  13865. savedCount: await this.#signatureStorage.size()
  13866. }
  13867. });
  13868. }
  13869. });
  13870. const deleteSpan = document.createElement("span");
  13871. deleteButton.append(deleteSpan);
  13872. deleteSpan.setAttribute("data-l10n-id", "pdfjs-editor-delete-signature-button-label1");
  13873. this.#addSignatureToolbarButton.before(div);
  13874. }
  13875. async #signaturesChanged() {
  13876. const parent = this.#addSignatureToolbarButton.parentElement;
  13877. while (parent.firstElementChild !== this.#addSignatureToolbarButton) {
  13878. parent.firstElementChild.remove();
  13879. }
  13880. this.#loadSignaturesPromise = null;
  13881. await this.loadSignatures(true);
  13882. }
  13883. getSignature(params) {
  13884. return this.open(params);
  13885. }
  13886. async loadSignatures(reload = false) {
  13887. if (!this.#addSignatureToolbarButton || !reload && this.#addSignatureToolbarButton.previousElementSibling || !this.#signatureStorage) {
  13888. return;
  13889. }
  13890. if (!this.#loadSignaturesPromise) {
  13891. this.#loadSignaturesPromise = this.#signatureStorage.getAll().then(async signatures => [signatures, await Promise.all(Array.from(signatures.values(), ({
  13892. signatureData
  13893. }) => SignatureExtractor.decompressSignature(signatureData)))]);
  13894. if (!reload) {
  13895. return;
  13896. }
  13897. }
  13898. const [signatures, signaturesData] = await this.#loadSignaturesPromise;
  13899. this.#loadSignaturesPromise = null;
  13900. let i = 0;
  13901. for (const [uuid, {
  13902. description
  13903. }] of signatures) {
  13904. const data = signaturesData[i++];
  13905. if (!data) {
  13906. continue;
  13907. }
  13908. data.curves = data.outlines.map(points => ({
  13909. points
  13910. }));
  13911. delete data.outlines;
  13912. this.#addToolbarButton(data, uuid, description);
  13913. }
  13914. }
  13915. async renderEditButton(editor) {
  13916. const button = document.createElement("button");
  13917. button.classList.add("altText", "editDescription");
  13918. button.tabIndex = 0;
  13919. button.title = editor.description;
  13920. const span = document.createElement("span");
  13921. button.append(span);
  13922. span.setAttribute("data-l10n-id", "pdfjs-editor-add-signature-edit-button-label");
  13923. button.addEventListener("click", () => {
  13924. this.#editDescriptionDialog.open(editor);
  13925. }, {
  13926. passive: true
  13927. });
  13928. return button;
  13929. }
  13930. async open({
  13931. uiManager,
  13932. editor
  13933. }) {
  13934. this.#tabsToAltText ||= new Map(this.#tabButtons.keys().map(name => [name, {
  13935. value: "",
  13936. default: ""
  13937. }]));
  13938. this.#uiManager = uiManager;
  13939. this.#currentEditor = editor;
  13940. this.#uiManager.removeEditListeners();
  13941. const isStorageFull = await this.#signatureStorage.isFull();
  13942. this.#saveContainer.classList.toggle("fullStorage", isStorageFull);
  13943. this.#saveCheckbox.checked = !isStorageFull;
  13944. await this.#overlayManager.open(this.#dialog);
  13945. const tabType = this.#tabButtons.get("type");
  13946. tabType.focus();
  13947. tabType.click();
  13948. }
  13949. #cancel() {
  13950. this.#finish();
  13951. }
  13952. #finish() {
  13953. this.#overlayManager.closeIfActive(this.#dialog);
  13954. }
  13955. #close() {
  13956. if (this.#currentEditor._drawId === null) {
  13957. this.#currentEditor.remove();
  13958. }
  13959. this.#uiManager?.addEditListeners();
  13960. this.#currentTabAC?.abort();
  13961. this.#currentTabAC = null;
  13962. this.#uiManager = null;
  13963. this.#currentEditor = null;
  13964. this.#resetCommon();
  13965. for (const [name] of this.#tabButtons) {
  13966. this.#resetTab(name);
  13967. }
  13968. this.#disableButtons(false);
  13969. this.#currentTab = null;
  13970. this.#tabsToAltText = null;
  13971. }
  13972. async #add() {
  13973. let data;
  13974. const type = this.#currentTab;
  13975. switch (type) {
  13976. case "type":
  13977. data = this.#getOutlineForType();
  13978. break;
  13979. case "draw":
  13980. data = this.#getOutlineForDraw();
  13981. break;
  13982. case "image":
  13983. data = this.#extractedSignatureData;
  13984. break;
  13985. }
  13986. let uuid = null;
  13987. const description = this.#description.value;
  13988. if (this.#saveCheckbox.checked) {
  13989. const {
  13990. newCurves,
  13991. areContours,
  13992. thickness,
  13993. width,
  13994. height
  13995. } = data;
  13996. const signatureData = await SignatureExtractor.compressSignature({
  13997. outlines: newCurves,
  13998. areContours,
  13999. thickness,
  14000. width,
  14001. height
  14002. });
  14003. uuid = await this.#signatureStorage.create({
  14004. description,
  14005. signatureData
  14006. });
  14007. if (uuid) {
  14008. this.#addToolbarButton({
  14009. curves: newCurves.map(points => ({
  14010. points
  14011. })),
  14012. areContours,
  14013. thickness,
  14014. width,
  14015. height
  14016. }, uuid, description);
  14017. } else {
  14018. console.warn("SignatureManager.add: cannot save the signature.");
  14019. }
  14020. }
  14021. const altText = this.#tabsToAltText.get(type);
  14022. this.#reportTelemetry({
  14023. type: "signature",
  14024. action: "pdfjs.signature.created",
  14025. data: {
  14026. type,
  14027. saved: !!uuid,
  14028. savedCount: await this.#signatureStorage.size(),
  14029. descriptionChanged: description !== altText.default
  14030. }
  14031. });
  14032. this.#currentEditor.addSignature(data, DEFAULT_HEIGHT_IN_PAGE, this.#description.value, uuid);
  14033. this.#finish();
  14034. }
  14035. destroy() {
  14036. this.#uiManager = null;
  14037. this.#finish();
  14038. }
  14039. }
  14040. class EditDescriptionDialog {
  14041. #currentEditor;
  14042. #previousDescription;
  14043. #description;
  14044. #dialog;
  14045. #overlayManager;
  14046. #signatureSVG;
  14047. #uiManager;
  14048. constructor({
  14049. dialog,
  14050. description,
  14051. cancelButton,
  14052. updateButton,
  14053. editSignatureView
  14054. }, overlayManager) {
  14055. const descriptionInput = this.#description = description.firstElementChild;
  14056. this.#signatureSVG = editSignatureView;
  14057. this.#dialog = dialog;
  14058. this.#overlayManager = overlayManager;
  14059. dialog.addEventListener("close", this.#close.bind(this));
  14060. dialog.addEventListener("contextmenu", e => {
  14061. if (e.target !== this.#description) {
  14062. e.preventDefault();
  14063. }
  14064. });
  14065. cancelButton.addEventListener("click", this.#cancel.bind(this));
  14066. updateButton.addEventListener("click", this.#update.bind(this));
  14067. const clearDescription = description.lastElementChild;
  14068. clearDescription.addEventListener("click", () => {
  14069. descriptionInput.value = "";
  14070. clearDescription.disabled = true;
  14071. updateButton.disabled = this.#previousDescription === "";
  14072. });
  14073. descriptionInput.addEventListener("input", () => {
  14074. const {
  14075. value
  14076. } = descriptionInput;
  14077. clearDescription.disabled = value === "";
  14078. updateButton.disabled = value === this.#previousDescription;
  14079. editSignatureView.setAttribute("aria-label", value);
  14080. }, {
  14081. passive: true
  14082. });
  14083. overlayManager.register(dialog);
  14084. }
  14085. async open(editor) {
  14086. this.#uiManager = editor._uiManager;
  14087. this.#currentEditor = editor;
  14088. this.#previousDescription = this.#description.value = editor.description;
  14089. this.#description.dispatchEvent(new Event("input"));
  14090. this.#uiManager.removeEditListeners();
  14091. const {
  14092. areContours,
  14093. outline
  14094. } = editor.getSignaturePreview();
  14095. const svgFactory = new DOMSVGFactory();
  14096. const path = svgFactory.createElement("path");
  14097. this.#signatureSVG.append(path);
  14098. this.#signatureSVG.setAttribute("viewBox", outline.viewBox);
  14099. path.setAttribute("d", outline.toSVGPath());
  14100. if (areContours) {
  14101. path.classList.add("contours");
  14102. }
  14103. await this.#overlayManager.open(this.#dialog);
  14104. }
  14105. async #update() {
  14106. this.#currentEditor._reportTelemetry({
  14107. action: "pdfjs.signature.edit_description",
  14108. data: {
  14109. hasBeenChanged: true
  14110. }
  14111. });
  14112. this.#currentEditor.description = this.#description.value;
  14113. this.#finish();
  14114. }
  14115. #cancel() {
  14116. this.#currentEditor._reportTelemetry({
  14117. action: "pdfjs.signature.edit_description",
  14118. data: {
  14119. hasBeenChanged: false
  14120. }
  14121. });
  14122. this.#finish();
  14123. }
  14124. #finish() {
  14125. this.#overlayManager.closeIfActive(this.#dialog);
  14126. }
  14127. #close() {
  14128. this.#uiManager?.addEditListeners();
  14129. this.#uiManager = null;
  14130. this.#currentEditor = null;
  14131. this.#signatureSVG.firstElementChild.remove();
  14132. }
  14133. }
  14134. ;// ./web/toolbar.js
  14135. class Toolbar {
  14136. #colorPicker = null;
  14137. #opts;
  14138. constructor(options, eventBus, toolbarDensity = 0) {
  14139. this.#opts = options;
  14140. this.eventBus = eventBus;
  14141. const buttons = [{
  14142. element: options.previous,
  14143. eventName: "previouspage"
  14144. }, {
  14145. element: options.next,
  14146. eventName: "nextpage"
  14147. }, {
  14148. element: options.zoomIn,
  14149. eventName: "zoomin"
  14150. }, {
  14151. element: options.zoomOut,
  14152. eventName: "zoomout"
  14153. }, {
  14154. element: options.print,
  14155. eventName: "print"
  14156. }, {
  14157. element: options.download,
  14158. eventName: "download"
  14159. }, {
  14160. element: options.editorFreeTextButton,
  14161. eventName: "switchannotationeditormode",
  14162. eventDetails: {
  14163. get mode() {
  14164. const {
  14165. classList
  14166. } = options.editorFreeTextButton;
  14167. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.FREETEXT;
  14168. }
  14169. }
  14170. }, {
  14171. element: options.editorHighlightButton,
  14172. eventName: "switchannotationeditormode",
  14173. eventDetails: {
  14174. get mode() {
  14175. const {
  14176. classList
  14177. } = options.editorHighlightButton;
  14178. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.HIGHLIGHT;
  14179. }
  14180. }
  14181. }, {
  14182. element: options.editorInkButton,
  14183. eventName: "switchannotationeditormode",
  14184. eventDetails: {
  14185. get mode() {
  14186. const {
  14187. classList
  14188. } = options.editorInkButton;
  14189. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.INK;
  14190. }
  14191. }
  14192. }, {
  14193. element: options.editorStampButton,
  14194. eventName: "switchannotationeditormode",
  14195. eventDetails: {
  14196. get mode() {
  14197. const {
  14198. classList
  14199. } = options.editorStampButton;
  14200. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.STAMP;
  14201. }
  14202. },
  14203. telemetry: {
  14204. type: "editing",
  14205. data: {
  14206. action: "pdfjs.image.icon_click"
  14207. }
  14208. }
  14209. }, {
  14210. element: options.editorSignatureButton,
  14211. eventName: "switchannotationeditormode",
  14212. eventDetails: {
  14213. get mode() {
  14214. const {
  14215. classList
  14216. } = options.editorSignatureButton;
  14217. return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.SIGNATURE;
  14218. }
  14219. }
  14220. }];
  14221. this.#bindListeners(buttons);
  14222. this.#updateToolbarDensity({
  14223. value: toolbarDensity
  14224. });
  14225. this.reset();
  14226. }
  14227. #updateToolbarDensity({
  14228. value
  14229. }) {
  14230. let name = "normal";
  14231. switch (value) {
  14232. case 1:
  14233. name = "compact";
  14234. break;
  14235. case 2:
  14236. name = "touch";
  14237. break;
  14238. }
  14239. document.documentElement.setAttribute("data-toolbar-density", name);
  14240. }
  14241. setPageNumber(pageNumber, pageLabel) {
  14242. this.pageNumber = pageNumber;
  14243. this.pageLabel = pageLabel;
  14244. this.#updateUIState(false);
  14245. }
  14246. setPagesCount(pagesCount, hasPageLabels) {
  14247. this.pagesCount = pagesCount;
  14248. this.hasPageLabels = hasPageLabels;
  14249. this.#updateUIState(true);
  14250. }
  14251. setPageScale(pageScaleValue, pageScale) {
  14252. this.pageScaleValue = (pageScaleValue || pageScale).toString();
  14253. this.pageScale = pageScale;
  14254. this.#updateUIState(false);
  14255. }
  14256. reset() {
  14257. this.#colorPicker = null;
  14258. this.pageNumber = 0;
  14259. this.pageLabel = null;
  14260. this.hasPageLabels = false;
  14261. this.pagesCount = 0;
  14262. this.pageScaleValue = DEFAULT_SCALE_VALUE;
  14263. this.pageScale = DEFAULT_SCALE;
  14264. this.#updateUIState(true);
  14265. this.updateLoadingIndicatorState();
  14266. this.#editorModeChanged({
  14267. mode: AnnotationEditorType.DISABLE
  14268. });
  14269. }
  14270. #bindListeners(buttons) {
  14271. const {
  14272. eventBus
  14273. } = this;
  14274. const {
  14275. editorHighlightColorPicker,
  14276. editorHighlightButton,
  14277. pageNumber,
  14278. scaleSelect
  14279. } = this.#opts;
  14280. const self = this;
  14281. for (const {
  14282. element,
  14283. eventName,
  14284. eventDetails,
  14285. telemetry
  14286. } of buttons) {
  14287. element.addEventListener("click", evt => {
  14288. if (eventName !== null) {
  14289. eventBus.dispatch(eventName, {
  14290. source: this,
  14291. ...eventDetails,
  14292. isFromKeyboard: evt.detail === 0
  14293. });
  14294. }
  14295. if (telemetry) {
  14296. eventBus.dispatch("reporttelemetry", {
  14297. source: this,
  14298. details: telemetry
  14299. });
  14300. }
  14301. });
  14302. }
  14303. pageNumber.addEventListener("click", function () {
  14304. this.select();
  14305. });
  14306. pageNumber.addEventListener("change", function () {
  14307. eventBus.dispatch("pagenumberchanged", {
  14308. source: self,
  14309. value: this.value
  14310. });
  14311. });
  14312. scaleSelect.addEventListener("change", function () {
  14313. if (this.value === "custom") {
  14314. return;
  14315. }
  14316. eventBus.dispatch("scalechanged", {
  14317. source: self,
  14318. value: this.value
  14319. });
  14320. });
  14321. scaleSelect.addEventListener("click", function ({
  14322. target
  14323. }) {
  14324. if (this.value === self.pageScaleValue && target.tagName.toUpperCase() === "OPTION") {
  14325. this.blur();
  14326. }
  14327. });
  14328. scaleSelect.oncontextmenu = noContextMenu;
  14329. eventBus._on("annotationeditormodechanged", this.#editorModeChanged.bind(this));
  14330. eventBus._on("showannotationeditorui", ({
  14331. mode
  14332. }) => {
  14333. switch (mode) {
  14334. case AnnotationEditorType.HIGHLIGHT:
  14335. editorHighlightButton.click();
  14336. break;
  14337. }
  14338. });
  14339. eventBus._on("toolbardensity", this.#updateToolbarDensity.bind(this));
  14340. if (editorHighlightColorPicker) {
  14341. eventBus._on("annotationeditoruimanager", ({
  14342. uiManager
  14343. }) => {
  14344. const cp = this.#colorPicker = new ColorPicker({
  14345. uiManager
  14346. });
  14347. uiManager.setMainHighlightColorPicker(cp);
  14348. editorHighlightColorPicker.append(cp.renderMainDropdown());
  14349. });
  14350. eventBus._on("mainhighlightcolorpickerupdatecolor", ({
  14351. value
  14352. }) => {
  14353. this.#colorPicker?.updateColor(value);
  14354. });
  14355. }
  14356. }
  14357. #editorModeChanged({
  14358. mode
  14359. }) {
  14360. const {
  14361. editorFreeTextButton,
  14362. editorFreeTextParamsToolbar,
  14363. editorHighlightButton,
  14364. editorHighlightParamsToolbar,
  14365. editorInkButton,
  14366. editorInkParamsToolbar,
  14367. editorStampButton,
  14368. editorStampParamsToolbar,
  14369. editorSignatureButton,
  14370. editorSignatureParamsToolbar
  14371. } = this.#opts;
  14372. toggleExpandedBtn(editorFreeTextButton, mode === AnnotationEditorType.FREETEXT, editorFreeTextParamsToolbar);
  14373. toggleExpandedBtn(editorHighlightButton, mode === AnnotationEditorType.HIGHLIGHT, editorHighlightParamsToolbar);
  14374. toggleExpandedBtn(editorInkButton, mode === AnnotationEditorType.INK, editorInkParamsToolbar);
  14375. toggleExpandedBtn(editorStampButton, mode === AnnotationEditorType.STAMP, editorStampParamsToolbar);
  14376. toggleExpandedBtn(editorSignatureButton, mode === AnnotationEditorType.SIGNATURE, editorSignatureParamsToolbar);
  14377. const isDisable = mode === AnnotationEditorType.DISABLE;
  14378. editorFreeTextButton.disabled = isDisable;
  14379. editorHighlightButton.disabled = isDisable;
  14380. editorInkButton.disabled = isDisable;
  14381. editorStampButton.disabled = isDisable;
  14382. editorSignatureButton.disabled = isDisable;
  14383. }
  14384. #updateUIState(resetNumPages = false) {
  14385. const {
  14386. pageNumber,
  14387. pagesCount,
  14388. pageScaleValue,
  14389. pageScale
  14390. } = this;
  14391. const opts = this.#opts;
  14392. if (resetNumPages) {
  14393. if (this.hasPageLabels) {
  14394. opts.pageNumber.type = "text";
  14395. opts.numPages.setAttribute("data-l10n-id", "pdfjs-page-of-pages");
  14396. } else {
  14397. opts.pageNumber.type = "number";
  14398. opts.numPages.setAttribute("data-l10n-id", "pdfjs-of-pages");
  14399. opts.numPages.setAttribute("data-l10n-args", JSON.stringify({
  14400. pagesCount
  14401. }));
  14402. }
  14403. opts.pageNumber.max = pagesCount;
  14404. }
  14405. if (this.hasPageLabels) {
  14406. opts.pageNumber.value = this.pageLabel;
  14407. opts.numPages.setAttribute("data-l10n-args", JSON.stringify({
  14408. pageNumber,
  14409. pagesCount
  14410. }));
  14411. } else {
  14412. opts.pageNumber.value = pageNumber;
  14413. }
  14414. opts.previous.disabled = pageNumber <= 1;
  14415. opts.next.disabled = pageNumber >= pagesCount;
  14416. opts.zoomOut.disabled = pageScale <= MIN_SCALE;
  14417. opts.zoomIn.disabled = pageScale >= MAX_SCALE;
  14418. let predefinedValueFound = false;
  14419. for (const option of opts.scaleSelect.options) {
  14420. if (option.value !== pageScaleValue) {
  14421. option.selected = false;
  14422. continue;
  14423. }
  14424. option.selected = true;
  14425. predefinedValueFound = true;
  14426. }
  14427. if (!predefinedValueFound) {
  14428. opts.customScaleOption.selected = true;
  14429. opts.customScaleOption.setAttribute("data-l10n-args", JSON.stringify({
  14430. scale: Math.round(pageScale * 10000) / 100
  14431. }));
  14432. }
  14433. }
  14434. updateLoadingIndicatorState(loading = false) {
  14435. const {
  14436. pageNumber
  14437. } = this.#opts;
  14438. pageNumber.classList.toggle("loading", loading);
  14439. }
  14440. }
  14441. ;// ./web/view_history.js
  14442. const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;
  14443. class ViewHistory {
  14444. constructor(fingerprint, cacheSize = DEFAULT_VIEW_HISTORY_CACHE_SIZE) {
  14445. this.fingerprint = fingerprint;
  14446. this.cacheSize = cacheSize;
  14447. this._initializedPromise = this._readFromStorage().then(databaseStr => {
  14448. const database = JSON.parse(databaseStr || "{}");
  14449. let index = -1;
  14450. if (!Array.isArray(database.files)) {
  14451. database.files = [];
  14452. } else {
  14453. while (database.files.length >= this.cacheSize) {
  14454. database.files.shift();
  14455. }
  14456. for (let i = 0, ii = database.files.length; i < ii; i++) {
  14457. const branch = database.files[i];
  14458. if (branch.fingerprint === this.fingerprint) {
  14459. index = i;
  14460. break;
  14461. }
  14462. }
  14463. }
  14464. if (index === -1) {
  14465. index = database.files.push({
  14466. fingerprint: this.fingerprint
  14467. }) - 1;
  14468. }
  14469. this.file = database.files[index];
  14470. this.database = database;
  14471. });
  14472. }
  14473. async _writeToStorage() {
  14474. const databaseStr = JSON.stringify(this.database);
  14475. localStorage.setItem("pdfjs.history", databaseStr);
  14476. }
  14477. async _readFromStorage() {
  14478. return localStorage.getItem("pdfjs.history");
  14479. }
  14480. async set(name, val) {
  14481. await this._initializedPromise;
  14482. this.file[name] = val;
  14483. return this._writeToStorage();
  14484. }
  14485. async setMultiple(properties) {
  14486. await this._initializedPromise;
  14487. for (const name in properties) {
  14488. this.file[name] = properties[name];
  14489. }
  14490. return this._writeToStorage();
  14491. }
  14492. async get(name, defaultValue) {
  14493. await this._initializedPromise;
  14494. const val = this.file[name];
  14495. return val !== undefined ? val : defaultValue;
  14496. }
  14497. async getMultiple(properties) {
  14498. await this._initializedPromise;
  14499. const values = Object.create(null);
  14500. for (const name in properties) {
  14501. const val = this.file[name];
  14502. values[name] = val !== undefined ? val : properties[name];
  14503. }
  14504. return values;
  14505. }
  14506. }
  14507. ;// ./web/app.js
  14508. const FORCE_PAGES_LOADED_TIMEOUT = 10000;
  14509. const ViewOnLoad = {
  14510. UNKNOWN: -1,
  14511. PREVIOUS: 0,
  14512. INITIAL: 1
  14513. };
  14514. const PDFViewerApplication = {
  14515. initialBookmark: document.location.hash.substring(1),
  14516. _initializedCapability: {
  14517. ...Promise.withResolvers(),
  14518. settled: false
  14519. },
  14520. appConfig: null,
  14521. pdfDocument: null,
  14522. pdfLoadingTask: null,
  14523. printService: null,
  14524. pdfViewer: null,
  14525. pdfThumbnailViewer: null,
  14526. pdfRenderingQueue: null,
  14527. pdfPresentationMode: null,
  14528. pdfDocumentProperties: null,
  14529. pdfLinkService: null,
  14530. pdfHistory: null,
  14531. pdfSidebar: null,
  14532. pdfOutlineViewer: null,
  14533. pdfAttachmentViewer: null,
  14534. pdfLayerViewer: null,
  14535. pdfCursorTools: null,
  14536. pdfScriptingManager: null,
  14537. store: null,
  14538. downloadManager: null,
  14539. overlayManager: null,
  14540. preferences: new Preferences(),
  14541. toolbar: null,
  14542. secondaryToolbar: null,
  14543. eventBus: null,
  14544. l10n: null,
  14545. annotationEditorParams: null,
  14546. imageAltTextSettings: null,
  14547. isInitialViewSet: false,
  14548. isViewerEmbedded: window.parent !== window,
  14549. url: "",
  14550. baseUrl: "",
  14551. mlManager: null,
  14552. _downloadUrl: "",
  14553. _eventBusAbortController: null,
  14554. _windowAbortController: null,
  14555. _globalAbortController: new AbortController(),
  14556. documentInfo: null,
  14557. metadata: null,
  14558. _contentDispositionFilename: null,
  14559. _contentLength: null,
  14560. _saveInProgress: false,
  14561. _wheelUnusedTicks: 0,
  14562. _wheelUnusedFactor: 1,
  14563. _touchManager: null,
  14564. _touchUnusedTicks: 0,
  14565. _touchUnusedFactor: 1,
  14566. _PDFBug: null,
  14567. _hasAnnotationEditors: false,
  14568. _title: document.title,
  14569. _printAnnotationStoragePromise: null,
  14570. _isCtrlKeyDown: false,
  14571. _caretBrowsing: null,
  14572. _isScrolling: false,
  14573. editorUndoBar: null,
  14574. async initialize(appConfig) {
  14575. this.appConfig = appConfig;
  14576. try {
  14577. await this.preferences.initializedPromise;
  14578. } catch (ex) {
  14579. console.error("initialize:", ex);
  14580. }
  14581. if (AppOptions.get("pdfBugEnabled")) {
  14582. await this._parseHashParams();
  14583. }
  14584. let mode;
  14585. switch (AppOptions.get("viewerCssTheme")) {
  14586. case 1:
  14587. mode = "light";
  14588. break;
  14589. case 2:
  14590. mode = "dark";
  14591. break;
  14592. }
  14593. if (mode) {
  14594. docStyle.setProperty("color-scheme", mode);
  14595. }
  14596. this.l10n = await this.externalServices.createL10n();
  14597. document.getElementsByTagName("html")[0].dir = this.l10n.getDirection();
  14598. this.l10n.translate(appConfig.appContainer || document.documentElement);
  14599. if (this.isViewerEmbedded && AppOptions.get("externalLinkTarget") === LinkTarget.NONE) {
  14600. AppOptions.set("externalLinkTarget", LinkTarget.TOP);
  14601. }
  14602. await this._initializeViewerComponents();
  14603. this.bindEvents();
  14604. this.bindWindowEvents();
  14605. this._initializedCapability.settled = true;
  14606. this._initializedCapability.resolve();
  14607. },
  14608. async _parseHashParams() {
  14609. const hash = document.location.hash.substring(1);
  14610. if (!hash) {
  14611. return;
  14612. }
  14613. const {
  14614. mainContainer,
  14615. viewerContainer
  14616. } = this.appConfig,
  14617. params = parseQueryString(hash);
  14618. const loadPDFBug = async () => {
  14619. if (this._PDFBug) {
  14620. return;
  14621. }
  14622. const {
  14623. PDFBug
  14624. } = await import(
  14625. /*webpackIgnore: true*/
  14626. /*@vite-ignore*/
  14627. AppOptions.get("debuggerSrc"));
  14628. this._PDFBug = PDFBug;
  14629. };
  14630. if (params.get("disableworker") === "true") {
  14631. try {
  14632. GlobalWorkerOptions.workerSrc ||= AppOptions.get("workerSrc");
  14633. await import(
  14634. /*webpackIgnore: true*/
  14635. /*@vite-ignore*/
  14636. PDFWorker.workerSrc);
  14637. } catch (ex) {
  14638. console.error("_parseHashParams:", ex);
  14639. }
  14640. }
  14641. if (params.has("textlayer")) {
  14642. switch (params.get("textlayer")) {
  14643. case "off":
  14644. AppOptions.set("textLayerMode", TextLayerMode.DISABLE);
  14645. break;
  14646. case "visible":
  14647. case "shadow":
  14648. case "hover":
  14649. viewerContainer.classList.add(`textLayer-${params.get("textlayer")}`);
  14650. try {
  14651. await loadPDFBug();
  14652. this._PDFBug.loadCSS();
  14653. } catch (ex) {
  14654. console.error("_parseHashParams:", ex);
  14655. }
  14656. break;
  14657. }
  14658. }
  14659. if (params.has("pdfbug")) {
  14660. AppOptions.setAll({
  14661. pdfBug: true,
  14662. fontExtraProperties: true
  14663. });
  14664. const enabled = params.get("pdfbug").split(",");
  14665. try {
  14666. await loadPDFBug();
  14667. this._PDFBug.init(mainContainer, enabled);
  14668. } catch (ex) {
  14669. console.error("_parseHashParams:", ex);
  14670. }
  14671. }
  14672. if (params.has("locale")) {
  14673. AppOptions.set("localeProperties", {
  14674. lang: params.get("locale")
  14675. });
  14676. }
  14677. const opts = {
  14678. disableAutoFetch: x => x === "true",
  14679. disableFontFace: x => x === "true",
  14680. disableHistory: x => x === "true",
  14681. disableRange: x => x === "true",
  14682. disableStream: x => x === "true",
  14683. verbosity: x => x | 0
  14684. };
  14685. for (const name in opts) {
  14686. const check = opts[name],
  14687. key = name.toLowerCase();
  14688. if (params.has(key)) {
  14689. AppOptions.set(name, check(params.get(key)));
  14690. }
  14691. }
  14692. },
  14693. async _initializeViewerComponents() {
  14694. const {
  14695. appConfig,
  14696. externalServices,
  14697. l10n,
  14698. mlManager
  14699. } = this;
  14700. const abortSignal = this._globalAbortController.signal;
  14701. const eventBus = new EventBus();
  14702. this.eventBus = AppOptions.eventBus = eventBus;
  14703. mlManager?.setEventBus(eventBus, abortSignal);
  14704. const overlayManager = this.overlayManager = new OverlayManager();
  14705. const renderingQueue = this.pdfRenderingQueue = new PDFRenderingQueue();
  14706. renderingQueue.onIdle = this._cleanup.bind(this);
  14707. const linkService = this.pdfLinkService = new PDFLinkService({
  14708. eventBus,
  14709. externalLinkTarget: AppOptions.get("externalLinkTarget"),
  14710. externalLinkRel: AppOptions.get("externalLinkRel"),
  14711. ignoreDestinationZoom: AppOptions.get("ignoreDestinationZoom")
  14712. });
  14713. const downloadManager = this.downloadManager = new DownloadManager();
  14714. const findController = this.findController = new PDFFindController({
  14715. linkService,
  14716. eventBus,
  14717. updateMatchesCountOnProgress: true
  14718. });
  14719. const pdfScriptingManager = this.pdfScriptingManager = new PDFScriptingManager({
  14720. eventBus,
  14721. externalServices,
  14722. docProperties: this._scriptingDocProperties.bind(this)
  14723. });
  14724. const container = appConfig.mainContainer,
  14725. viewer = appConfig.viewerContainer;
  14726. const annotationEditorMode = AppOptions.get("annotationEditorMode");
  14727. const pageColors = AppOptions.get("forcePageColors") || window.matchMedia("(forced-colors: active)").matches ? {
  14728. background: AppOptions.get("pageColorsBackground"),
  14729. foreground: AppOptions.get("pageColorsForeground")
  14730. } : null;
  14731. let altTextManager;
  14732. if (AppOptions.get("enableUpdatedAddImage")) {
  14733. altTextManager = appConfig.newAltTextDialog ? new NewAltTextManager(appConfig.newAltTextDialog, overlayManager, eventBus) : null;
  14734. } else {
  14735. altTextManager = appConfig.altTextDialog ? new AltTextManager(appConfig.altTextDialog, container, overlayManager, eventBus) : null;
  14736. }
  14737. if (appConfig.editorUndoBar) {
  14738. this.editorUndoBar = new EditorUndoBar(appConfig.editorUndoBar, eventBus);
  14739. }
  14740. const signatureManager = AppOptions.get("enableSignatureEditor") && appConfig.addSignatureDialog ? new SignatureManager(appConfig.addSignatureDialog, appConfig.editSignatureDialog, appConfig.annotationEditorParams?.editorSignatureAddSignature || null, overlayManager, l10n, externalServices.createSignatureStorage(eventBus, abortSignal), eventBus) : null;
  14741. const enableHWA = AppOptions.get("enableHWA"),
  14742. maxCanvasPixels = AppOptions.get("maxCanvasPixels"),
  14743. maxCanvasDim = AppOptions.get("maxCanvasDim");
  14744. const pdfViewer = this.pdfViewer = new PDFViewer({
  14745. container,
  14746. viewer,
  14747. eventBus,
  14748. renderingQueue,
  14749. linkService,
  14750. downloadManager,
  14751. altTextManager,
  14752. signatureManager,
  14753. editorUndoBar: this.editorUndoBar,
  14754. findController,
  14755. scriptingManager: AppOptions.get("enableScripting") && pdfScriptingManager,
  14756. l10n,
  14757. textLayerMode: AppOptions.get("textLayerMode"),
  14758. annotationMode: AppOptions.get("annotationMode"),
  14759. annotationEditorMode,
  14760. annotationEditorHighlightColors: AppOptions.get("highlightEditorColors"),
  14761. enableHighlightFloatingButton: AppOptions.get("enableHighlightFloatingButton"),
  14762. enableUpdatedAddImage: AppOptions.get("enableUpdatedAddImage"),
  14763. enableNewAltTextWhenAddingImage: AppOptions.get("enableNewAltTextWhenAddingImage"),
  14764. imageResourcesPath: AppOptions.get("imageResourcesPath"),
  14765. enablePrintAutoRotate: AppOptions.get("enablePrintAutoRotate"),
  14766. maxCanvasPixels,
  14767. maxCanvasDim,
  14768. enableDetailCanvas: AppOptions.get("enableDetailCanvas"),
  14769. enablePermissions: AppOptions.get("enablePermissions"),
  14770. pageColors,
  14771. mlManager,
  14772. abortSignal,
  14773. enableHWA,
  14774. supportsPinchToZoom: this.supportsPinchToZoom,
  14775. enableAutoLinking: AppOptions.get("enableAutoLinking")
  14776. });
  14777. renderingQueue.setViewer(pdfViewer);
  14778. linkService.setViewer(pdfViewer);
  14779. pdfScriptingManager.setViewer(pdfViewer);
  14780. if (appConfig.sidebar?.thumbnailView) {
  14781. this.pdfThumbnailViewer = new PDFThumbnailViewer({
  14782. container: appConfig.sidebar.thumbnailView,
  14783. eventBus,
  14784. renderingQueue,
  14785. linkService,
  14786. maxCanvasPixels,
  14787. maxCanvasDim,
  14788. pageColors,
  14789. abortSignal,
  14790. enableHWA
  14791. });
  14792. renderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
  14793. }
  14794. if (!this.isViewerEmbedded && !AppOptions.get("disableHistory")) {
  14795. this.pdfHistory = new PDFHistory({
  14796. linkService,
  14797. eventBus
  14798. });
  14799. linkService.setHistory(this.pdfHistory);
  14800. }
  14801. if (!this.supportsIntegratedFind && appConfig.findBar) {
  14802. this.findBar = new PDFFindBar(appConfig.findBar, appConfig.principalContainer, eventBus);
  14803. }
  14804. if (appConfig.annotationEditorParams) {
  14805. if (annotationEditorMode !== AnnotationEditorType.DISABLE) {
  14806. const editorSignatureButton = appConfig.toolbar?.editorSignatureButton;
  14807. if (editorSignatureButton && AppOptions.get("enableSignatureEditor")) {
  14808. editorSignatureButton.parentElement.hidden = false;
  14809. }
  14810. this.annotationEditorParams = new AnnotationEditorParams(appConfig.annotationEditorParams, eventBus);
  14811. } else {
  14812. for (const id of ["editorModeButtons", "editorModeSeparator"]) {
  14813. document.getElementById(id)?.classList.add("hidden");
  14814. }
  14815. }
  14816. }
  14817. if (mlManager && appConfig.secondaryToolbar?.imageAltTextSettingsButton) {
  14818. this.imageAltTextSettings = new ImageAltTextSettings(appConfig.altTextSettingsDialog, overlayManager, eventBus, mlManager);
  14819. }
  14820. if (appConfig.documentProperties) {
  14821. this.pdfDocumentProperties = new PDFDocumentProperties(appConfig.documentProperties, overlayManager, eventBus, l10n, () => this._docFilename);
  14822. }
  14823. if (appConfig.secondaryToolbar?.cursorHandToolButton) {
  14824. this.pdfCursorTools = new PDFCursorTools({
  14825. container,
  14826. eventBus,
  14827. cursorToolOnLoad: AppOptions.get("cursorToolOnLoad")
  14828. });
  14829. }
  14830. if (appConfig.toolbar) {
  14831. this.toolbar = new Toolbar(appConfig.toolbar, eventBus, AppOptions.get("toolbarDensity"));
  14832. }
  14833. if (appConfig.secondaryToolbar) {
  14834. if (AppOptions.get("enableAltText")) {
  14835. appConfig.secondaryToolbar.imageAltTextSettingsButton?.classList.remove("hidden");
  14836. appConfig.secondaryToolbar.imageAltTextSettingsSeparator?.classList.remove("hidden");
  14837. }
  14838. this.secondaryToolbar = new SecondaryToolbar(appConfig.secondaryToolbar, eventBus);
  14839. }
  14840. if (this.supportsFullscreen && appConfig.secondaryToolbar?.presentationModeButton) {
  14841. this.pdfPresentationMode = new PDFPresentationMode({
  14842. container,
  14843. pdfViewer,
  14844. eventBus
  14845. });
  14846. }
  14847. if (appConfig.passwordOverlay) {
  14848. this.passwordPrompt = new PasswordPrompt(appConfig.passwordOverlay, overlayManager, this.isViewerEmbedded);
  14849. }
  14850. if (appConfig.sidebar?.outlineView) {
  14851. this.pdfOutlineViewer = new PDFOutlineViewer({
  14852. container: appConfig.sidebar.outlineView,
  14853. eventBus,
  14854. l10n,
  14855. linkService,
  14856. downloadManager
  14857. });
  14858. }
  14859. if (appConfig.sidebar?.attachmentsView) {
  14860. this.pdfAttachmentViewer = new PDFAttachmentViewer({
  14861. container: appConfig.sidebar.attachmentsView,
  14862. eventBus,
  14863. l10n,
  14864. downloadManager
  14865. });
  14866. }
  14867. if (appConfig.sidebar?.layersView) {
  14868. this.pdfLayerViewer = new PDFLayerViewer({
  14869. container: appConfig.sidebar.layersView,
  14870. eventBus,
  14871. l10n
  14872. });
  14873. }
  14874. if (appConfig.sidebar) {
  14875. this.pdfSidebar = new PDFSidebar({
  14876. elements: appConfig.sidebar,
  14877. eventBus,
  14878. l10n
  14879. });
  14880. this.pdfSidebar.onToggled = this.forceRendering.bind(this);
  14881. this.pdfSidebar.onUpdateThumbnails = () => {
  14882. for (const pageView of pdfViewer.getCachedPageViews()) {
  14883. if (pageView.renderingState === RenderingStates.FINISHED) {
  14884. this.pdfThumbnailViewer.getThumbnail(pageView.id - 1)?.setImage(pageView);
  14885. }
  14886. }
  14887. this.pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber);
  14888. };
  14889. }
  14890. },
  14891. async run(config) {
  14892. await this.initialize(config);
  14893. const {
  14894. appConfig,
  14895. eventBus
  14896. } = this;
  14897. let file;
  14898. const queryString = document.location.search.substring(1);
  14899. const params = parseQueryString(queryString);
  14900. file = params.get("file") ?? AppOptions.get("defaultUrl");
  14901. validateFileURL(file);
  14902. const fileInput = this._openFileInput = document.createElement("input");
  14903. fileInput.id = "fileInput";
  14904. fileInput.hidden = true;
  14905. fileInput.type = "file";
  14906. fileInput.value = null;
  14907. document.body.append(fileInput);
  14908. fileInput.addEventListener("change", function (evt) {
  14909. const {
  14910. files
  14911. } = evt.target;
  14912. if (!files || files.length === 0) {
  14913. return;
  14914. }
  14915. eventBus.dispatch("fileinputchange", {
  14916. source: this,
  14917. fileInput: evt.target
  14918. });
  14919. });
  14920. appConfig.mainContainer.addEventListener("dragover", function (evt) {
  14921. for (const item of evt.dataTransfer.items) {
  14922. if (item.type === "application/pdf") {
  14923. evt.dataTransfer.dropEffect = evt.dataTransfer.effectAllowed === "copy" ? "copy" : "move";
  14924. stopEvent(evt);
  14925. return;
  14926. }
  14927. }
  14928. });
  14929. appConfig.mainContainer.addEventListener("drop", function (evt) {
  14930. if (evt.dataTransfer.files?.[0].type !== "application/pdf") {
  14931. return;
  14932. }
  14933. stopEvent(evt);
  14934. eventBus.dispatch("fileinputchange", {
  14935. source: this,
  14936. fileInput: evt.dataTransfer
  14937. });
  14938. });
  14939. if (!AppOptions.get("supportsDocumentFonts")) {
  14940. AppOptions.set("disableFontFace", true);
  14941. this.l10n.get("pdfjs-web-fonts-disabled").then(msg => {
  14942. console.warn(msg);
  14943. });
  14944. }
  14945. if (!this.supportsPrinting) {
  14946. appConfig.toolbar?.print?.classList.add("hidden");
  14947. appConfig.secondaryToolbar?.printButton.classList.add("hidden");
  14948. }
  14949. if (!this.supportsFullscreen) {
  14950. appConfig.secondaryToolbar?.presentationModeButton.classList.add("hidden");
  14951. }
  14952. if (this.supportsIntegratedFind) {
  14953. appConfig.findBar?.toggleButton?.classList.add("hidden");
  14954. }
  14955. if (file) {
  14956. this.open({
  14957. url: file
  14958. });
  14959. } else {
  14960. this._hideViewBookmark();
  14961. }
  14962. },
  14963. get externalServices() {
  14964. return shadow(this, "externalServices", new ExternalServices());
  14965. },
  14966. get initialized() {
  14967. return this._initializedCapability.settled;
  14968. },
  14969. get initializedPromise() {
  14970. return this._initializedCapability.promise;
  14971. },
  14972. updateZoom(steps, scaleFactor, origin) {
  14973. if (this.pdfViewer.isInPresentationMode) {
  14974. return;
  14975. }
  14976. this.pdfViewer.updateScale({
  14977. drawingDelay: AppOptions.get("defaultZoomDelay"),
  14978. steps,
  14979. scaleFactor,
  14980. origin
  14981. });
  14982. },
  14983. zoomIn() {
  14984. this.updateZoom(1);
  14985. },
  14986. zoomOut() {
  14987. this.updateZoom(-1);
  14988. },
  14989. zoomReset() {
  14990. if (this.pdfViewer.isInPresentationMode) {
  14991. return;
  14992. }
  14993. this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  14994. },
  14995. touchPinchCallback(origin, prevDistance, distance) {
  14996. if (this.supportsPinchToZoom) {
  14997. const newScaleFactor = this._accumulateFactor(this.pdfViewer.currentScale, distance / prevDistance, "_touchUnusedFactor");
  14998. this.updateZoom(null, newScaleFactor, origin);
  14999. } else {
  15000. const PIXELS_PER_LINE_SCALE = 30;
  15001. const ticks = this._accumulateTicks((distance - prevDistance) / PIXELS_PER_LINE_SCALE, "_touchUnusedTicks");
  15002. this.updateZoom(ticks, null, origin);
  15003. }
  15004. },
  15005. touchPinchEndCallback() {
  15006. this._touchUnusedTicks = 0;
  15007. this._touchUnusedFactor = 1;
  15008. },
  15009. get pagesCount() {
  15010. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  15011. },
  15012. get page() {
  15013. return this.pdfViewer.currentPageNumber;
  15014. },
  15015. set page(val) {
  15016. this.pdfViewer.currentPageNumber = val;
  15017. },
  15018. get supportsPrinting() {
  15019. return shadow(this, "supportsPrinting", AppOptions.get("supportsPrinting") && PDFPrintServiceFactory.supportsPrinting);
  15020. },
  15021. get supportsFullscreen() {
  15022. return shadow(this, "supportsFullscreen", document.fullscreenEnabled);
  15023. },
  15024. get supportsPinchToZoom() {
  15025. return shadow(this, "supportsPinchToZoom", AppOptions.get("supportsPinchToZoom"));
  15026. },
  15027. get supportsIntegratedFind() {
  15028. return shadow(this, "supportsIntegratedFind", AppOptions.get("supportsIntegratedFind"));
  15029. },
  15030. get loadingBar() {
  15031. const barElement = document.getElementById("loadingBar");
  15032. const bar = barElement ? new ProgressBar(barElement) : null;
  15033. return shadow(this, "loadingBar", bar);
  15034. },
  15035. get supportsMouseWheelZoomCtrlKey() {
  15036. return shadow(this, "supportsMouseWheelZoomCtrlKey", AppOptions.get("supportsMouseWheelZoomCtrlKey"));
  15037. },
  15038. get supportsMouseWheelZoomMetaKey() {
  15039. return shadow(this, "supportsMouseWheelZoomMetaKey", AppOptions.get("supportsMouseWheelZoomMetaKey"));
  15040. },
  15041. get supportsCaretBrowsingMode() {
  15042. return AppOptions.get("supportsCaretBrowsingMode");
  15043. },
  15044. moveCaret(isUp, select) {
  15045. this._caretBrowsing ||= new CaretBrowsingMode(this._globalAbortController.signal, this.appConfig.mainContainer, this.appConfig.viewerContainer, this.appConfig.toolbar?.container);
  15046. this._caretBrowsing.moveCaret(isUp, select);
  15047. },
  15048. setTitleUsingUrl(url = "", downloadUrl = null) {
  15049. this.url = url;
  15050. this.baseUrl = updateUrlHash(url, "", true);
  15051. if (downloadUrl) {
  15052. this._downloadUrl = downloadUrl === url ? this.baseUrl : updateUrlHash(downloadUrl, "", true);
  15053. }
  15054. if (isDataScheme(url)) {
  15055. this._hideViewBookmark();
  15056. }
  15057. let title = pdfjs_getPdfFilenameFromUrl(url, "");
  15058. if (!title) {
  15059. try {
  15060. title = decodeURIComponent(getFilenameFromUrl(url));
  15061. } catch {}
  15062. }
  15063. this.setTitle(title || url);
  15064. },
  15065. setTitle(title = this._title) {
  15066. this._title = title;
  15067. if (this.isViewerEmbedded) {
  15068. return;
  15069. }
  15070. const editorIndicator = this._hasAnnotationEditors && !this.pdfRenderingQueue.printing;
  15071. document.title = `${editorIndicator ? "* " : ""}${title}`;
  15072. },
  15073. get _docFilename() {
  15074. return this._contentDispositionFilename || pdfjs_getPdfFilenameFromUrl(this.url);
  15075. },
  15076. _hideViewBookmark() {
  15077. const {
  15078. secondaryToolbar
  15079. } = this.appConfig;
  15080. secondaryToolbar?.viewBookmarkButton.classList.add("hidden");
  15081. if (secondaryToolbar?.presentationModeButton.classList.contains("hidden")) {
  15082. document.getElementById("viewBookmarkSeparator")?.classList.add("hidden");
  15083. }
  15084. },
  15085. async close() {
  15086. this._unblockDocumentLoadEvent();
  15087. this._hideViewBookmark();
  15088. if (!this.pdfLoadingTask) {
  15089. return;
  15090. }
  15091. if (this.pdfDocument?.annotationStorage.size > 0 && this._annotationStorageModified) {
  15092. try {
  15093. await this.save();
  15094. } catch {}
  15095. }
  15096. const promises = [];
  15097. promises.push(this.pdfLoadingTask.destroy());
  15098. this.pdfLoadingTask = null;
  15099. if (this.pdfDocument) {
  15100. this.pdfDocument = null;
  15101. this.pdfThumbnailViewer?.setDocument(null);
  15102. this.pdfViewer.setDocument(null);
  15103. this.pdfLinkService.setDocument(null);
  15104. this.pdfDocumentProperties?.setDocument(null);
  15105. }
  15106. this.pdfLinkService.externalLinkEnabled = true;
  15107. this.store = null;
  15108. this.isInitialViewSet = false;
  15109. this.url = "";
  15110. this.baseUrl = "";
  15111. this._downloadUrl = "";
  15112. this.documentInfo = null;
  15113. this.metadata = null;
  15114. this._contentDispositionFilename = null;
  15115. this._contentLength = null;
  15116. this._saveInProgress = false;
  15117. this._hasAnnotationEditors = false;
  15118. promises.push(this.pdfScriptingManager.destroyPromise, this.passwordPrompt.close());
  15119. this.setTitle();
  15120. this.pdfSidebar?.reset();
  15121. this.pdfOutlineViewer?.reset();
  15122. this.pdfAttachmentViewer?.reset();
  15123. this.pdfLayerViewer?.reset();
  15124. this.pdfHistory?.reset();
  15125. this.findBar?.reset();
  15126. this.toolbar?.reset();
  15127. this.secondaryToolbar?.reset();
  15128. this._PDFBug?.cleanup();
  15129. await Promise.all(promises);
  15130. },
  15131. async open(args) {
  15132. if (this.pdfLoadingTask) {
  15133. await this.close();
  15134. }
  15135. const workerParams = AppOptions.getAll(OptionKind.WORKER);
  15136. Object.assign(GlobalWorkerOptions, workerParams);
  15137. if (args.url) {
  15138. this.setTitleUsingUrl(args.originalUrl || args.url, args.url);
  15139. }
  15140. const apiParams = AppOptions.getAll(OptionKind.API);
  15141. const loadingTask = getDocument({
  15142. ...apiParams,
  15143. ...args
  15144. });
  15145. this.pdfLoadingTask = loadingTask;
  15146. loadingTask.onPassword = (updateCallback, reason) => {
  15147. if (this.isViewerEmbedded) {
  15148. this._unblockDocumentLoadEvent();
  15149. }
  15150. this.pdfLinkService.externalLinkEnabled = false;
  15151. this.passwordPrompt.setUpdateCallback(updateCallback, reason);
  15152. this.passwordPrompt.open();
  15153. };
  15154. loadingTask.onProgress = ({
  15155. loaded,
  15156. total
  15157. }) => {
  15158. this.progress(loaded / total);
  15159. };
  15160. return loadingTask.promise.then(pdfDocument => {
  15161. this.load(pdfDocument);
  15162. }, reason => {
  15163. if (loadingTask !== this.pdfLoadingTask) {
  15164. return undefined;
  15165. }
  15166. let key = "pdfjs-loading-error";
  15167. if (reason instanceof InvalidPDFException) {
  15168. key = "pdfjs-invalid-file-error";
  15169. } else if (reason instanceof ResponseException) {
  15170. key = reason.missing ? "pdfjs-missing-file-error" : "pdfjs-unexpected-response-error";
  15171. }
  15172. return this._documentError(key, {
  15173. message: reason.message
  15174. }).then(() => {
  15175. throw reason;
  15176. });
  15177. });
  15178. },
  15179. async download() {
  15180. let data;
  15181. try {
  15182. data = await (this.pdfDocument ? this.pdfDocument.getData() : this.pdfLoadingTask.getData());
  15183. } catch {}
  15184. this.downloadManager.download(data, this._downloadUrl, this._docFilename);
  15185. },
  15186. async save() {
  15187. if (this._saveInProgress) {
  15188. return;
  15189. }
  15190. this._saveInProgress = true;
  15191. await this.pdfScriptingManager.dispatchWillSave();
  15192. try {
  15193. const data = await this.pdfDocument.saveDocument();
  15194. this.downloadManager.download(data, this._downloadUrl, this._docFilename);
  15195. } catch (reason) {
  15196. console.error(`Error when saving the document:`, reason);
  15197. await this.download();
  15198. } finally {
  15199. await this.pdfScriptingManager.dispatchDidSave();
  15200. this._saveInProgress = false;
  15201. }
  15202. if (this._hasAnnotationEditors) {
  15203. this.externalServices.reportTelemetry({
  15204. type: "editing",
  15205. data: {
  15206. type: "save",
  15207. stats: this.pdfDocument?.annotationStorage.editorStats
  15208. }
  15209. });
  15210. }
  15211. },
  15212. async downloadOrSave() {
  15213. const {
  15214. classList
  15215. } = this.appConfig.appContainer;
  15216. classList.add("wait");
  15217. await (this.pdfDocument?.annotationStorage.size > 0 ? this.save() : this.download());
  15218. classList.remove("wait");
  15219. },
  15220. async _documentError(key, moreInfo = null) {
  15221. this._unblockDocumentLoadEvent();
  15222. const message = await this._otherError(key || "pdfjs-loading-error", moreInfo);
  15223. this.eventBus.dispatch("documenterror", {
  15224. source: this,
  15225. message,
  15226. reason: moreInfo?.message ?? null
  15227. });
  15228. },
  15229. async _otherError(key, moreInfo = null) {
  15230. const message = await this.l10n.get(key);
  15231. const moreInfoText = [`PDF.js v${version || "?"} (build: ${build || "?"})`];
  15232. if (moreInfo) {
  15233. moreInfoText.push(`Message: ${moreInfo.message}`);
  15234. if (moreInfo.stack) {
  15235. moreInfoText.push(`Stack: ${moreInfo.stack}`);
  15236. } else {
  15237. if (moreInfo.filename) {
  15238. moreInfoText.push(`File: ${moreInfo.filename}`);
  15239. }
  15240. if (moreInfo.lineNumber) {
  15241. moreInfoText.push(`Line: ${moreInfo.lineNumber}`);
  15242. }
  15243. }
  15244. }
  15245. console.error(`${message}\n\n${moreInfoText.join("\n")}`);
  15246. return message;
  15247. },
  15248. progress(level) {
  15249. const percent = Math.round(level * 100);
  15250. if (!this.loadingBar || percent <= this.loadingBar.percent) {
  15251. return;
  15252. }
  15253. this.loadingBar.percent = percent;
  15254. if (this.pdfDocument?.loadingParams.disableAutoFetch ?? AppOptions.get("disableAutoFetch")) {
  15255. this.loadingBar.setDisableAutoFetch();
  15256. }
  15257. },
  15258. load(pdfDocument) {
  15259. this.pdfDocument = pdfDocument;
  15260. pdfDocument.getDownloadInfo().then(({
  15261. length
  15262. }) => {
  15263. this._contentLength = length;
  15264. this.loadingBar?.hide();
  15265. firstPagePromise.then(() => {
  15266. this.eventBus.dispatch("documentloaded", {
  15267. source: this
  15268. });
  15269. });
  15270. });
  15271. const pageLayoutPromise = pdfDocument.getPageLayout().catch(() => {});
  15272. const pageModePromise = pdfDocument.getPageMode().catch(() => {});
  15273. const openActionPromise = pdfDocument.getOpenAction().catch(() => {});
  15274. this.toolbar?.setPagesCount(pdfDocument.numPages, false);
  15275. this.secondaryToolbar?.setPagesCount(pdfDocument.numPages);
  15276. this.pdfLinkService.setDocument(pdfDocument);
  15277. this.pdfDocumentProperties?.setDocument(pdfDocument);
  15278. const pdfViewer = this.pdfViewer;
  15279. pdfViewer.setDocument(pdfDocument);
  15280. const {
  15281. firstPagePromise,
  15282. onePageRendered,
  15283. pagesPromise
  15284. } = pdfViewer;
  15285. this.pdfThumbnailViewer?.setDocument(pdfDocument);
  15286. const storedPromise = (this.store = new ViewHistory(pdfDocument.fingerprints[0])).getMultiple({
  15287. page: null,
  15288. zoom: DEFAULT_SCALE_VALUE,
  15289. scrollLeft: "0",
  15290. scrollTop: "0",
  15291. rotation: null,
  15292. sidebarView: SidebarView.UNKNOWN,
  15293. scrollMode: ScrollMode.UNKNOWN,
  15294. spreadMode: SpreadMode.UNKNOWN
  15295. }).catch(() => {});
  15296. firstPagePromise.then(pdfPage => {
  15297. this.loadingBar?.setWidth(this.appConfig.viewerContainer);
  15298. this._initializeAnnotationStorageCallbacks(pdfDocument);
  15299. Promise.all([animationStarted, storedPromise, pageLayoutPromise, pageModePromise, openActionPromise]).then(async ([timeStamp, stored, pageLayout, pageMode, openAction]) => {
  15300. const viewOnLoad = AppOptions.get("viewOnLoad");
  15301. this._initializePdfHistory({
  15302. fingerprint: pdfDocument.fingerprints[0],
  15303. viewOnLoad,
  15304. initialDest: openAction?.dest
  15305. });
  15306. const initialBookmark = this.initialBookmark;
  15307. const zoom = AppOptions.get("defaultZoomValue");
  15308. let hash = zoom ? `zoom=${zoom}` : null;
  15309. let rotation = null;
  15310. let sidebarView = AppOptions.get("sidebarViewOnLoad");
  15311. let scrollMode = AppOptions.get("scrollModeOnLoad");
  15312. let spreadMode = AppOptions.get("spreadModeOnLoad");
  15313. if (stored?.page && viewOnLoad !== ViewOnLoad.INITIAL) {
  15314. hash = `page=${stored.page}&zoom=${zoom || stored.zoom},` + `${stored.scrollLeft},${stored.scrollTop}`;
  15315. rotation = parseInt(stored.rotation, 10);
  15316. if (sidebarView === SidebarView.UNKNOWN) {
  15317. sidebarView = stored.sidebarView | 0;
  15318. }
  15319. if (scrollMode === ScrollMode.UNKNOWN) {
  15320. scrollMode = stored.scrollMode | 0;
  15321. }
  15322. if (spreadMode === SpreadMode.UNKNOWN) {
  15323. spreadMode = stored.spreadMode | 0;
  15324. }
  15325. }
  15326. if (pageMode && sidebarView === SidebarView.UNKNOWN) {
  15327. sidebarView = apiPageModeToSidebarView(pageMode);
  15328. }
  15329. if (pageLayout && scrollMode === ScrollMode.UNKNOWN && spreadMode === SpreadMode.UNKNOWN) {
  15330. const modes = apiPageLayoutToViewerModes(pageLayout);
  15331. spreadMode = modes.spreadMode;
  15332. }
  15333. this.setInitialView(hash, {
  15334. rotation,
  15335. sidebarView,
  15336. scrollMode,
  15337. spreadMode
  15338. });
  15339. this.eventBus.dispatch("documentinit", {
  15340. source: this
  15341. });
  15342. if (!this.isViewerEmbedded) {
  15343. pdfViewer.focus();
  15344. }
  15345. await Promise.race([pagesPromise, new Promise(resolve => {
  15346. setTimeout(resolve, FORCE_PAGES_LOADED_TIMEOUT);
  15347. })]);
  15348. if (!initialBookmark && !hash) {
  15349. return;
  15350. }
  15351. if (pdfViewer.hasEqualPageSizes) {
  15352. return;
  15353. }
  15354. this.initialBookmark = initialBookmark;
  15355. pdfViewer.currentScaleValue = pdfViewer.currentScaleValue;
  15356. this.setInitialView(hash);
  15357. }).catch(() => {
  15358. this.setInitialView();
  15359. }).then(function () {
  15360. pdfViewer.update();
  15361. });
  15362. });
  15363. pagesPromise.then(() => {
  15364. this._unblockDocumentLoadEvent();
  15365. this._initializeAutoPrint(pdfDocument, openActionPromise);
  15366. }, reason => {
  15367. this._documentError("pdfjs-loading-error", {
  15368. message: reason.message
  15369. });
  15370. });
  15371. onePageRendered.then(data => {
  15372. this.externalServices.reportTelemetry({
  15373. type: "pageInfo",
  15374. timestamp: data.timestamp
  15375. });
  15376. if (this.pdfOutlineViewer) {
  15377. pdfDocument.getOutline().then(outline => {
  15378. if (pdfDocument !== this.pdfDocument) {
  15379. return;
  15380. }
  15381. this.pdfOutlineViewer.render({
  15382. outline,
  15383. pdfDocument
  15384. });
  15385. });
  15386. }
  15387. if (this.pdfAttachmentViewer) {
  15388. pdfDocument.getAttachments().then(attachments => {
  15389. if (pdfDocument !== this.pdfDocument) {
  15390. return;
  15391. }
  15392. this.pdfAttachmentViewer.render({
  15393. attachments
  15394. });
  15395. });
  15396. }
  15397. if (this.pdfLayerViewer) {
  15398. pdfViewer.optionalContentConfigPromise.then(optionalContentConfig => {
  15399. if (pdfDocument !== this.pdfDocument) {
  15400. return;
  15401. }
  15402. this.pdfLayerViewer.render({
  15403. optionalContentConfig,
  15404. pdfDocument
  15405. });
  15406. });
  15407. }
  15408. });
  15409. this._initializePageLabels(pdfDocument);
  15410. this._initializeMetadata(pdfDocument);
  15411. },
  15412. async _scriptingDocProperties(pdfDocument) {
  15413. if (!this.documentInfo) {
  15414. await new Promise(resolve => {
  15415. this.eventBus._on("metadataloaded", resolve, {
  15416. once: true
  15417. });
  15418. });
  15419. if (pdfDocument !== this.pdfDocument) {
  15420. return null;
  15421. }
  15422. }
  15423. if (!this._contentLength) {
  15424. await new Promise(resolve => {
  15425. this.eventBus._on("documentloaded", resolve, {
  15426. once: true
  15427. });
  15428. });
  15429. if (pdfDocument !== this.pdfDocument) {
  15430. return null;
  15431. }
  15432. }
  15433. return {
  15434. ...this.documentInfo,
  15435. baseURL: this.baseUrl,
  15436. filesize: this._contentLength,
  15437. filename: this._docFilename,
  15438. metadata: this.metadata?.getRaw(),
  15439. authors: this.metadata?.get("dc:creator"),
  15440. numPages: this.pagesCount,
  15441. URL: this.url
  15442. };
  15443. },
  15444. async _initializeAutoPrint(pdfDocument, openActionPromise) {
  15445. const [openAction, jsActions] = await Promise.all([openActionPromise, this.pdfViewer.enableScripting ? null : pdfDocument.getJSActions()]);
  15446. if (pdfDocument !== this.pdfDocument) {
  15447. return;
  15448. }
  15449. let triggerAutoPrint = openAction?.action === "Print";
  15450. if (jsActions) {
  15451. console.warn("Warning: JavaScript support is not enabled");
  15452. for (const name in jsActions) {
  15453. if (triggerAutoPrint) {
  15454. break;
  15455. }
  15456. switch (name) {
  15457. case "WillClose":
  15458. case "WillSave":
  15459. case "DidSave":
  15460. case "WillPrint":
  15461. case "DidPrint":
  15462. continue;
  15463. }
  15464. triggerAutoPrint = jsActions[name].some(js => AutoPrintRegExp.test(js));
  15465. }
  15466. }
  15467. if (triggerAutoPrint) {
  15468. this.triggerPrinting();
  15469. }
  15470. },
  15471. async _initializeMetadata(pdfDocument) {
  15472. const {
  15473. info,
  15474. metadata,
  15475. contentDispositionFilename,
  15476. contentLength
  15477. } = await pdfDocument.getMetadata();
  15478. if (pdfDocument !== this.pdfDocument) {
  15479. return;
  15480. }
  15481. this.documentInfo = info;
  15482. this.metadata = metadata;
  15483. this._contentDispositionFilename ??= contentDispositionFilename;
  15484. this._contentLength ??= contentLength;
  15485. console.log(`PDF ${pdfDocument.fingerprints[0]} [${info.PDFFormatVersion} ` + `${(info.Producer || "-").trim()} / ${(info.Creator || "-").trim()}] ` + `(PDF.js: ${version || "?"} [${build || "?"}])`);
  15486. let pdfTitle = info.Title;
  15487. const metadataTitle = metadata?.get("dc:title");
  15488. if (metadataTitle) {
  15489. if (metadataTitle !== "Untitled" && !/[\uFFF0-\uFFFF]/g.test(metadataTitle)) {
  15490. pdfTitle = metadataTitle;
  15491. }
  15492. }
  15493. if (pdfTitle) {
  15494. this.setTitle(`${pdfTitle} - ${this._contentDispositionFilename || this._title}`);
  15495. } else if (this._contentDispositionFilename) {
  15496. this.setTitle(this._contentDispositionFilename);
  15497. }
  15498. if (info.IsXFAPresent && !info.IsAcroFormPresent && !pdfDocument.isPureXfa) {
  15499. if (pdfDocument.loadingParams.enableXfa) {
  15500. console.warn("Warning: XFA Foreground documents are not supported");
  15501. } else {
  15502. console.warn("Warning: XFA support is not enabled");
  15503. }
  15504. } else if ((info.IsAcroFormPresent || info.IsXFAPresent) && !this.pdfViewer.renderForms) {
  15505. console.warn("Warning: Interactive form support is not enabled");
  15506. }
  15507. if (info.IsSignaturesPresent) {
  15508. console.warn("Warning: Digital signatures validation is not supported");
  15509. }
  15510. this.eventBus.dispatch("metadataloaded", {
  15511. source: this
  15512. });
  15513. },
  15514. async _initializePageLabels(pdfDocument) {
  15515. const labels = await pdfDocument.getPageLabels();
  15516. if (pdfDocument !== this.pdfDocument) {
  15517. return;
  15518. }
  15519. if (!labels || AppOptions.get("disablePageLabels")) {
  15520. return;
  15521. }
  15522. const numLabels = labels.length;
  15523. let standardLabels = 0,
  15524. emptyLabels = 0;
  15525. for (let i = 0; i < numLabels; i++) {
  15526. const label = labels[i];
  15527. if (label === (i + 1).toString()) {
  15528. standardLabels++;
  15529. } else if (label === "") {
  15530. emptyLabels++;
  15531. } else {
  15532. break;
  15533. }
  15534. }
  15535. if (standardLabels >= numLabels || emptyLabels >= numLabels) {
  15536. return;
  15537. }
  15538. const {
  15539. pdfViewer,
  15540. pdfThumbnailViewer,
  15541. toolbar
  15542. } = this;
  15543. pdfViewer.setPageLabels(labels);
  15544. pdfThumbnailViewer?.setPageLabels(labels);
  15545. toolbar?.setPagesCount(numLabels, true);
  15546. toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  15547. },
  15548. _initializePdfHistory({
  15549. fingerprint,
  15550. viewOnLoad,
  15551. initialDest = null
  15552. }) {
  15553. if (!this.pdfHistory) {
  15554. return;
  15555. }
  15556. this.pdfHistory.initialize({
  15557. fingerprint,
  15558. resetHistory: viewOnLoad === ViewOnLoad.INITIAL,
  15559. updateUrl: AppOptions.get("historyUpdateUrl")
  15560. });
  15561. if (this.pdfHistory.initialBookmark) {
  15562. this.initialBookmark = this.pdfHistory.initialBookmark;
  15563. this.initialRotation = this.pdfHistory.initialRotation;
  15564. }
  15565. if (initialDest && !this.initialBookmark && viewOnLoad === ViewOnLoad.UNKNOWN) {
  15566. this.initialBookmark = JSON.stringify(initialDest);
  15567. this.pdfHistory.push({
  15568. explicitDest: initialDest,
  15569. pageNumber: null
  15570. });
  15571. }
  15572. },
  15573. _initializeAnnotationStorageCallbacks(pdfDocument) {
  15574. if (pdfDocument !== this.pdfDocument) {
  15575. return;
  15576. }
  15577. const {
  15578. annotationStorage
  15579. } = pdfDocument;
  15580. annotationStorage.onSetModified = () => {
  15581. window.addEventListener("beforeunload", beforeUnload);
  15582. this._annotationStorageModified = true;
  15583. };
  15584. annotationStorage.onResetModified = () => {
  15585. window.removeEventListener("beforeunload", beforeUnload);
  15586. delete this._annotationStorageModified;
  15587. };
  15588. annotationStorage.onAnnotationEditor = typeStr => {
  15589. this._hasAnnotationEditors = !!typeStr;
  15590. this.setTitle();
  15591. };
  15592. },
  15593. setInitialView(storedHash, {
  15594. rotation,
  15595. sidebarView,
  15596. scrollMode,
  15597. spreadMode
  15598. } = {}) {
  15599. const setRotation = angle => {
  15600. if (isValidRotation(angle)) {
  15601. this.pdfViewer.pagesRotation = angle;
  15602. }
  15603. };
  15604. const setViewerModes = (scroll, spread) => {
  15605. if (isValidScrollMode(scroll)) {
  15606. this.pdfViewer.scrollMode = scroll;
  15607. }
  15608. if (isValidSpreadMode(spread)) {
  15609. this.pdfViewer.spreadMode = spread;
  15610. }
  15611. };
  15612. this.isInitialViewSet = true;
  15613. this.pdfSidebar?.setInitialView(sidebarView);
  15614. setViewerModes(scrollMode, spreadMode);
  15615. if (this.initialBookmark) {
  15616. setRotation(this.initialRotation);
  15617. delete this.initialRotation;
  15618. this.pdfLinkService.setHash(this.initialBookmark);
  15619. this.initialBookmark = null;
  15620. } else if (storedHash) {
  15621. setRotation(rotation);
  15622. this.pdfLinkService.setHash(storedHash);
  15623. }
  15624. this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber, this.pdfViewer.currentPageLabel);
  15625. this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber);
  15626. if (!this.pdfViewer.currentScaleValue) {
  15627. this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  15628. }
  15629. },
  15630. _cleanup() {
  15631. if (!this.pdfDocument) {
  15632. return;
  15633. }
  15634. this.pdfViewer.cleanup();
  15635. this.pdfThumbnailViewer?.cleanup();
  15636. this.pdfDocument.cleanup(AppOptions.get("fontExtraProperties"));
  15637. },
  15638. forceRendering() {
  15639. this.pdfRenderingQueue.printing = !!this.printService;
  15640. this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar?.visibleView === SidebarView.THUMBS;
  15641. this.pdfRenderingQueue.renderHighestPriority();
  15642. },
  15643. beforePrint() {
  15644. this._printAnnotationStoragePromise = this.pdfScriptingManager.dispatchWillPrint().catch(() => {}).then(() => this.pdfDocument?.annotationStorage.print);
  15645. if (this.printService) {
  15646. return;
  15647. }
  15648. if (!this.supportsPrinting) {
  15649. this._otherError("pdfjs-printing-not-supported");
  15650. return;
  15651. }
  15652. if (!this.pdfViewer.pageViewsReady) {
  15653. this.l10n.get("pdfjs-printing-not-ready").then(msg => {
  15654. window.alert(msg);
  15655. });
  15656. return;
  15657. }
  15658. this.printService = PDFPrintServiceFactory.createPrintService({
  15659. pdfDocument: this.pdfDocument,
  15660. pagesOverview: this.pdfViewer.getPagesOverview(),
  15661. printContainer: this.appConfig.printContainer,
  15662. printResolution: AppOptions.get("printResolution"),
  15663. printAnnotationStoragePromise: this._printAnnotationStoragePromise
  15664. });
  15665. this.forceRendering();
  15666. this.setTitle();
  15667. this.printService.layout();
  15668. if (this._hasAnnotationEditors) {
  15669. this.externalServices.reportTelemetry({
  15670. type: "editing",
  15671. data: {
  15672. type: "print",
  15673. stats: this.pdfDocument?.annotationStorage.editorStats
  15674. }
  15675. });
  15676. }
  15677. },
  15678. afterPrint() {
  15679. if (this._printAnnotationStoragePromise) {
  15680. this._printAnnotationStoragePromise.then(() => {
  15681. this.pdfScriptingManager.dispatchDidPrint();
  15682. });
  15683. this._printAnnotationStoragePromise = null;
  15684. }
  15685. if (this.printService) {
  15686. this.printService.destroy();
  15687. this.printService = null;
  15688. this.pdfDocument?.annotationStorage.resetModified();
  15689. }
  15690. this.forceRendering();
  15691. this.setTitle();
  15692. },
  15693. rotatePages(delta) {
  15694. this.pdfViewer.pagesRotation += delta;
  15695. },
  15696. requestPresentationMode() {
  15697. this.pdfPresentationMode?.request();
  15698. },
  15699. triggerPrinting() {
  15700. if (this.supportsPrinting) {
  15701. window.print();
  15702. }
  15703. },
  15704. bindEvents() {
  15705. if (this._eventBusAbortController) {
  15706. return;
  15707. }
  15708. const ac = this._eventBusAbortController = new AbortController();
  15709. const opts = {
  15710. signal: ac.signal
  15711. };
  15712. const {
  15713. eventBus,
  15714. externalServices,
  15715. pdfDocumentProperties,
  15716. pdfViewer,
  15717. preferences
  15718. } = this;
  15719. eventBus._on("resize", onResize.bind(this), opts);
  15720. eventBus._on("hashchange", onHashchange.bind(this), opts);
  15721. eventBus._on("beforeprint", this.beforePrint.bind(this), opts);
  15722. eventBus._on("afterprint", this.afterPrint.bind(this), opts);
  15723. eventBus._on("pagerender", onPageRender.bind(this), opts);
  15724. eventBus._on("pagerendered", onPageRendered.bind(this), opts);
  15725. eventBus._on("updateviewarea", onUpdateViewarea.bind(this), opts);
  15726. eventBus._on("pagechanging", onPageChanging.bind(this), opts);
  15727. eventBus._on("scalechanging", onScaleChanging.bind(this), opts);
  15728. eventBus._on("rotationchanging", onRotationChanging.bind(this), opts);
  15729. eventBus._on("sidebarviewchanged", onSidebarViewChanged.bind(this), opts);
  15730. eventBus._on("pagemode", onPageMode.bind(this), opts);
  15731. eventBus._on("namedaction", onNamedAction.bind(this), opts);
  15732. eventBus._on("presentationmodechanged", evt => pdfViewer.presentationModeState = evt.state, opts);
  15733. eventBus._on("presentationmode", this.requestPresentationMode.bind(this), opts);
  15734. eventBus._on("switchannotationeditormode", evt => pdfViewer.annotationEditorMode = evt, opts);
  15735. eventBus._on("print", this.triggerPrinting.bind(this), opts);
  15736. eventBus._on("download", this.downloadOrSave.bind(this), opts);
  15737. eventBus._on("firstpage", () => this.page = 1, opts);
  15738. eventBus._on("lastpage", () => this.page = this.pagesCount, opts);
  15739. eventBus._on("nextpage", () => pdfViewer.nextPage(), opts);
  15740. eventBus._on("previouspage", () => pdfViewer.previousPage(), opts);
  15741. eventBus._on("zoomin", this.zoomIn.bind(this), opts);
  15742. eventBus._on("zoomout", this.zoomOut.bind(this), opts);
  15743. eventBus._on("zoomreset", this.zoomReset.bind(this), opts);
  15744. eventBus._on("pagenumberchanged", onPageNumberChanged.bind(this), opts);
  15745. eventBus._on("scalechanged", evt => pdfViewer.currentScaleValue = evt.value, opts);
  15746. eventBus._on("rotatecw", this.rotatePages.bind(this, 90), opts);
  15747. eventBus._on("rotateccw", this.rotatePages.bind(this, -90), opts);
  15748. eventBus._on("optionalcontentconfig", evt => pdfViewer.optionalContentConfigPromise = evt.promise, opts);
  15749. eventBus._on("switchscrollmode", evt => pdfViewer.scrollMode = evt.mode, opts);
  15750. eventBus._on("scrollmodechanged", onViewerModesChanged.bind(this, "scrollMode"), opts);
  15751. eventBus._on("switchspreadmode", evt => pdfViewer.spreadMode = evt.mode, opts);
  15752. eventBus._on("spreadmodechanged", onViewerModesChanged.bind(this, "spreadMode"), opts);
  15753. eventBus._on("imagealttextsettings", onImageAltTextSettings.bind(this), opts);
  15754. eventBus._on("documentproperties", () => pdfDocumentProperties?.open(), opts);
  15755. eventBus._on("findfromurlhash", onFindFromUrlHash.bind(this), opts);
  15756. eventBus._on("updatefindmatchescount", onUpdateFindMatchesCount.bind(this), opts);
  15757. eventBus._on("updatefindcontrolstate", onUpdateFindControlState.bind(this), opts);
  15758. eventBus._on("fileinputchange", onFileInputChange.bind(this), opts);
  15759. eventBus._on("openfile", onOpenFile.bind(this), opts);
  15760. },
  15761. bindWindowEvents() {
  15762. if (this._windowAbortController) {
  15763. return;
  15764. }
  15765. this._windowAbortController = new AbortController();
  15766. const {
  15767. eventBus,
  15768. appConfig: {
  15769. mainContainer
  15770. },
  15771. pdfViewer,
  15772. _windowAbortController: {
  15773. signal
  15774. }
  15775. } = this;
  15776. this._touchManager = new TouchManager({
  15777. container: window,
  15778. isPinchingDisabled: () => pdfViewer.isInPresentationMode,
  15779. isPinchingStopped: () => this.overlayManager?.active,
  15780. onPinching: this.touchPinchCallback.bind(this),
  15781. onPinchEnd: this.touchPinchEndCallback.bind(this),
  15782. signal
  15783. });
  15784. function addWindowResolutionChange(evt = null) {
  15785. if (evt) {
  15786. pdfViewer.refresh();
  15787. }
  15788. const mediaQueryList = window.matchMedia(`(resolution: ${OutputScale.pixelRatio}dppx)`);
  15789. mediaQueryList.addEventListener("change", addWindowResolutionChange, {
  15790. once: true,
  15791. signal
  15792. });
  15793. }
  15794. addWindowResolutionChange();
  15795. window.addEventListener("wheel", onWheel.bind(this), {
  15796. passive: false,
  15797. signal
  15798. });
  15799. window.addEventListener("click", onClick.bind(this), {
  15800. signal
  15801. });
  15802. window.addEventListener("keydown", onKeyDown.bind(this), {
  15803. signal
  15804. });
  15805. window.addEventListener("keyup", onKeyUp.bind(this), {
  15806. signal
  15807. });
  15808. window.addEventListener("resize", () => eventBus.dispatch("resize", {
  15809. source: window
  15810. }), {
  15811. signal
  15812. });
  15813. window.addEventListener("hashchange", () => {
  15814. eventBus.dispatch("hashchange", {
  15815. source: window,
  15816. hash: document.location.hash.substring(1)
  15817. });
  15818. }, {
  15819. signal
  15820. });
  15821. window.addEventListener("beforeprint", () => eventBus.dispatch("beforeprint", {
  15822. source: window
  15823. }), {
  15824. signal
  15825. });
  15826. window.addEventListener("afterprint", () => eventBus.dispatch("afterprint", {
  15827. source: window
  15828. }), {
  15829. signal
  15830. });
  15831. window.addEventListener("updatefromsandbox", evt => {
  15832. eventBus.dispatch("updatefromsandbox", {
  15833. source: window,
  15834. detail: evt.detail
  15835. });
  15836. }, {
  15837. signal
  15838. });
  15839. if (!("onscrollend" in document.documentElement)) {
  15840. return;
  15841. }
  15842. ({
  15843. scrollTop: this._lastScrollTop,
  15844. scrollLeft: this._lastScrollLeft
  15845. } = mainContainer);
  15846. const scrollend = () => {
  15847. ({
  15848. scrollTop: this._lastScrollTop,
  15849. scrollLeft: this._lastScrollLeft
  15850. } = mainContainer);
  15851. this._isScrolling = false;
  15852. mainContainer.addEventListener("scroll", scroll, {
  15853. passive: true,
  15854. signal
  15855. });
  15856. mainContainer.removeEventListener("scrollend", scrollend);
  15857. mainContainer.removeEventListener("blur", scrollend);
  15858. };
  15859. const scroll = () => {
  15860. if (this._isCtrlKeyDown) {
  15861. return;
  15862. }
  15863. if (this._lastScrollTop === mainContainer.scrollTop && this._lastScrollLeft === mainContainer.scrollLeft) {
  15864. return;
  15865. }
  15866. mainContainer.removeEventListener("scroll", scroll);
  15867. this._isScrolling = true;
  15868. mainContainer.addEventListener("scrollend", scrollend, {
  15869. signal
  15870. });
  15871. mainContainer.addEventListener("blur", scrollend, {
  15872. signal
  15873. });
  15874. };
  15875. mainContainer.addEventListener("scroll", scroll, {
  15876. passive: true,
  15877. signal
  15878. });
  15879. },
  15880. unbindEvents() {
  15881. this._eventBusAbortController?.abort();
  15882. this._eventBusAbortController = null;
  15883. },
  15884. unbindWindowEvents() {
  15885. this._windowAbortController?.abort();
  15886. this._windowAbortController = null;
  15887. this._touchManager = null;
  15888. },
  15889. async testingClose() {
  15890. this.unbindEvents();
  15891. this.unbindWindowEvents();
  15892. this._globalAbortController?.abort();
  15893. this._globalAbortController = null;
  15894. this.findBar?.close();
  15895. await Promise.all([this.l10n?.destroy(), this.close()]);
  15896. },
  15897. _accumulateTicks(ticks, prop) {
  15898. if (this[prop] > 0 && ticks < 0 || this[prop] < 0 && ticks > 0) {
  15899. this[prop] = 0;
  15900. }
  15901. this[prop] += ticks;
  15902. const wholeTicks = Math.trunc(this[prop]);
  15903. this[prop] -= wholeTicks;
  15904. return wholeTicks;
  15905. },
  15906. _accumulateFactor(previousScale, factor, prop) {
  15907. if (factor === 1) {
  15908. return 1;
  15909. }
  15910. if (this[prop] > 1 && factor < 1 || this[prop] < 1 && factor > 1) {
  15911. this[prop] = 1;
  15912. }
  15913. const newFactor = Math.floor(previousScale * factor * this[prop] * 100) / (100 * previousScale);
  15914. this[prop] = factor / newFactor;
  15915. return newFactor;
  15916. },
  15917. _unblockDocumentLoadEvent() {
  15918. document.blockUnblockOnload?.(false);
  15919. this._unblockDocumentLoadEvent = () => {};
  15920. },
  15921. get scriptingReady() {
  15922. return this.pdfScriptingManager.ready;
  15923. }
  15924. };
  15925. initCom(PDFViewerApplication);
  15926. {
  15927. PDFPrintServiceFactory.initGlobals(PDFViewerApplication);
  15928. }
  15929. {
  15930. const HOSTED_VIEWER_ORIGINS = new Set(["null", "http://mozilla.github.io", "https://mozilla.github.io"]);
  15931. var validateFileURL = function (file) {
  15932. if (!file) {
  15933. return;
  15934. }
  15935. const viewerOrigin = URL.parse(window.location)?.origin || "null";
  15936. if (HOSTED_VIEWER_ORIGINS.has(viewerOrigin)) {
  15937. return;
  15938. }
  15939. const fileOrigin = URL.parse(file, window.location)?.origin;
  15940. if (fileOrigin === viewerOrigin) {
  15941. return;
  15942. }
  15943. const ex = new Error("file origin does not match viewer's");
  15944. PDFViewerApplication._documentError("pdfjs-loading-error", {
  15945. message: ex.message
  15946. });
  15947. throw ex;
  15948. };
  15949. var onFileInputChange = function (evt) {
  15950. if (this.pdfViewer?.isInPresentationMode) {
  15951. return;
  15952. }
  15953. const file = evt.fileInput.files[0];
  15954. this.open({
  15955. url: URL.createObjectURL(file),
  15956. originalUrl: file.name
  15957. });
  15958. };
  15959. var onOpenFile = function (evt) {
  15960. this._openFileInput?.click();
  15961. };
  15962. }
  15963. function onPageRender({
  15964. pageNumber
  15965. }) {
  15966. if (pageNumber === this.page) {
  15967. this.toolbar?.updateLoadingIndicatorState(true);
  15968. }
  15969. }
  15970. function onPageRendered({
  15971. pageNumber,
  15972. isDetailView,
  15973. error
  15974. }) {
  15975. if (pageNumber === this.page) {
  15976. this.toolbar?.updateLoadingIndicatorState(false);
  15977. }
  15978. if (!isDetailView && this.pdfSidebar?.visibleView === SidebarView.THUMBS) {
  15979. const pageView = this.pdfViewer.getPageView(pageNumber - 1);
  15980. const thumbnailView = this.pdfThumbnailViewer?.getThumbnail(pageNumber - 1);
  15981. if (pageView) {
  15982. thumbnailView?.setImage(pageView);
  15983. }
  15984. }
  15985. if (error) {
  15986. this._otherError("pdfjs-rendering-error", error);
  15987. }
  15988. }
  15989. function onPageMode({
  15990. mode
  15991. }) {
  15992. let view;
  15993. switch (mode) {
  15994. case "thumbs":
  15995. view = SidebarView.THUMBS;
  15996. break;
  15997. case "bookmarks":
  15998. case "outline":
  15999. view = SidebarView.OUTLINE;
  16000. break;
  16001. case "attachments":
  16002. view = SidebarView.ATTACHMENTS;
  16003. break;
  16004. case "layers":
  16005. view = SidebarView.LAYERS;
  16006. break;
  16007. case "none":
  16008. view = SidebarView.NONE;
  16009. break;
  16010. default:
  16011. console.error('Invalid "pagemode" hash parameter: ' + mode);
  16012. return;
  16013. }
  16014. this.pdfSidebar?.switchView(view, true);
  16015. }
  16016. function onNamedAction(evt) {
  16017. switch (evt.action) {
  16018. case "GoToPage":
  16019. this.appConfig.toolbar?.pageNumber.select();
  16020. break;
  16021. case "Find":
  16022. if (!this.supportsIntegratedFind) {
  16023. this.findBar?.toggle();
  16024. }
  16025. break;
  16026. case "Print":
  16027. this.triggerPrinting();
  16028. break;
  16029. case "SaveAs":
  16030. this.downloadOrSave();
  16031. break;
  16032. }
  16033. }
  16034. function onSidebarViewChanged({
  16035. view
  16036. }) {
  16037. this.pdfRenderingQueue.isThumbnailViewEnabled = view === SidebarView.THUMBS;
  16038. if (this.isInitialViewSet) {
  16039. this.store?.set("sidebarView", view).catch(() => {});
  16040. }
  16041. }
  16042. function onUpdateViewarea({
  16043. location
  16044. }) {
  16045. if (this.isInitialViewSet) {
  16046. this.store?.setMultiple({
  16047. page: location.pageNumber,
  16048. zoom: location.scale,
  16049. scrollLeft: location.left,
  16050. scrollTop: location.top,
  16051. rotation: location.rotation
  16052. }).catch(() => {});
  16053. }
  16054. if (this.appConfig.secondaryToolbar) {
  16055. this.appConfig.secondaryToolbar.viewBookmarkButton.href = this.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
  16056. }
  16057. }
  16058. function onViewerModesChanged(name, evt) {
  16059. if (this.isInitialViewSet && !this.pdfViewer.isInPresentationMode) {
  16060. this.store?.set(name, evt.mode).catch(() => {});
  16061. }
  16062. }
  16063. function onResize() {
  16064. const {
  16065. pdfDocument,
  16066. pdfViewer,
  16067. pdfRenderingQueue
  16068. } = this;
  16069. if (pdfRenderingQueue.printing && window.matchMedia("print").matches) {
  16070. return;
  16071. }
  16072. if (!pdfDocument) {
  16073. return;
  16074. }
  16075. const currentScaleValue = pdfViewer.currentScaleValue;
  16076. if (currentScaleValue === "auto" || currentScaleValue === "page-fit" || currentScaleValue === "page-width") {
  16077. pdfViewer.currentScaleValue = currentScaleValue;
  16078. }
  16079. pdfViewer.update();
  16080. }
  16081. function onHashchange(evt) {
  16082. const hash = evt.hash;
  16083. if (!hash) {
  16084. return;
  16085. }
  16086. if (!this.isInitialViewSet) {
  16087. this.initialBookmark = hash;
  16088. } else if (!this.pdfHistory?.popStateInProgress) {
  16089. this.pdfLinkService.setHash(hash);
  16090. }
  16091. }
  16092. function onPageNumberChanged(evt) {
  16093. const {
  16094. pdfViewer
  16095. } = this;
  16096. if (evt.value !== "") {
  16097. this.pdfLinkService.goToPage(evt.value);
  16098. }
  16099. if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) {
  16100. this.toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  16101. }
  16102. }
  16103. function onImageAltTextSettings() {
  16104. this.imageAltTextSettings?.open({
  16105. enableGuessAltText: AppOptions.get("enableGuessAltText"),
  16106. enableNewAltTextWhenAddingImage: AppOptions.get("enableNewAltTextWhenAddingImage")
  16107. });
  16108. }
  16109. function onFindFromUrlHash(evt) {
  16110. this.eventBus.dispatch("find", {
  16111. source: evt.source,
  16112. type: "",
  16113. query: evt.query,
  16114. caseSensitive: false,
  16115. entireWord: false,
  16116. highlightAll: true,
  16117. findPrevious: false,
  16118. matchDiacritics: true
  16119. });
  16120. }
  16121. function onUpdateFindMatchesCount({
  16122. matchesCount
  16123. }) {
  16124. if (this.supportsIntegratedFind) {
  16125. this.externalServices.updateFindMatchesCount(matchesCount);
  16126. } else {
  16127. this.findBar?.updateResultsCount(matchesCount);
  16128. }
  16129. }
  16130. function onUpdateFindControlState({
  16131. state,
  16132. previous,
  16133. entireWord,
  16134. matchesCount,
  16135. rawQuery
  16136. }) {
  16137. if (this.supportsIntegratedFind) {
  16138. this.externalServices.updateFindControlState({
  16139. result: state,
  16140. findPrevious: previous,
  16141. entireWord,
  16142. matchesCount,
  16143. rawQuery
  16144. });
  16145. } else {
  16146. this.findBar?.updateUIState(state, previous, matchesCount);
  16147. }
  16148. }
  16149. function onScaleChanging(evt) {
  16150. this.toolbar?.setPageScale(evt.presetValue, evt.scale);
  16151. this.pdfViewer.update();
  16152. }
  16153. function onRotationChanging(evt) {
  16154. if (this.pdfThumbnailViewer) {
  16155. this.pdfThumbnailViewer.pagesRotation = evt.pagesRotation;
  16156. }
  16157. this.forceRendering();
  16158. this.pdfViewer.currentPageNumber = evt.pageNumber;
  16159. }
  16160. function onPageChanging({
  16161. pageNumber,
  16162. pageLabel
  16163. }) {
  16164. this.toolbar?.setPageNumber(pageNumber, pageLabel);
  16165. this.secondaryToolbar?.setPageNumber(pageNumber);
  16166. if (this.pdfSidebar?.visibleView === SidebarView.THUMBS) {
  16167. this.pdfThumbnailViewer?.scrollThumbnailIntoView(pageNumber);
  16168. }
  16169. const currentPage = this.pdfViewer.getPageView(pageNumber - 1);
  16170. this.toolbar?.updateLoadingIndicatorState(currentPage?.renderingState === RenderingStates.RUNNING);
  16171. }
  16172. function onWheel(evt) {
  16173. const {
  16174. pdfViewer,
  16175. supportsMouseWheelZoomCtrlKey,
  16176. supportsMouseWheelZoomMetaKey,
  16177. supportsPinchToZoom
  16178. } = this;
  16179. if (pdfViewer.isInPresentationMode) {
  16180. return;
  16181. }
  16182. const deltaMode = evt.deltaMode;
  16183. let scaleFactor = Math.exp(-evt.deltaY / 100);
  16184. const isBuiltInMac = false;
  16185. const isPinchToZoom = evt.ctrlKey && !this._isCtrlKeyDown && deltaMode === WheelEvent.DOM_DELTA_PIXEL && evt.deltaX === 0 && (Math.abs(scaleFactor - 1) < 0.05 || isBuiltInMac) && evt.deltaZ === 0;
  16186. const origin = [evt.clientX, evt.clientY];
  16187. if (isPinchToZoom || evt.ctrlKey && supportsMouseWheelZoomCtrlKey || evt.metaKey && supportsMouseWheelZoomMetaKey) {
  16188. evt.preventDefault();
  16189. if (this._isScrolling || document.visibilityState === "hidden" || this.overlayManager.active) {
  16190. return;
  16191. }
  16192. if (isPinchToZoom && supportsPinchToZoom) {
  16193. scaleFactor = this._accumulateFactor(pdfViewer.currentScale, scaleFactor, "_wheelUnusedFactor");
  16194. this.updateZoom(null, scaleFactor, origin);
  16195. } else {
  16196. const delta = normalizeWheelEventDirection(evt);
  16197. let ticks = 0;
  16198. if (deltaMode === WheelEvent.DOM_DELTA_LINE || deltaMode === WheelEvent.DOM_DELTA_PAGE) {
  16199. ticks = Math.abs(delta) >= 1 ? Math.sign(delta) : this._accumulateTicks(delta, "_wheelUnusedTicks");
  16200. } else {
  16201. const PIXELS_PER_LINE_SCALE = 30;
  16202. ticks = this._accumulateTicks(delta / PIXELS_PER_LINE_SCALE, "_wheelUnusedTicks");
  16203. }
  16204. this.updateZoom(ticks, null, origin);
  16205. }
  16206. }
  16207. }
  16208. function closeSecondaryToolbar({
  16209. target
  16210. }) {
  16211. if (!this.secondaryToolbar?.isOpen) {
  16212. return;
  16213. }
  16214. const {
  16215. toolbar,
  16216. secondaryToolbar
  16217. } = this.appConfig;
  16218. if (this.pdfViewer.containsElement(target) || toolbar?.container.contains(target) && !secondaryToolbar?.toolbar.contains(target) && !secondaryToolbar?.toggleButton.contains(target)) {
  16219. this.secondaryToolbar.close();
  16220. }
  16221. }
  16222. function closeEditorUndoBar(evt) {
  16223. if (!this.editorUndoBar?.isOpen) {
  16224. return;
  16225. }
  16226. if (this.appConfig.secondaryToolbar?.toolbar.contains(evt.target)) {
  16227. this.editorUndoBar.hide();
  16228. }
  16229. }
  16230. function onClick(evt) {
  16231. closeSecondaryToolbar.call(this, evt);
  16232. closeEditorUndoBar.call(this, evt);
  16233. }
  16234. function onKeyUp(evt) {
  16235. if (evt.key === "Control") {
  16236. this._isCtrlKeyDown = false;
  16237. }
  16238. }
  16239. function onKeyDown(evt) {
  16240. this._isCtrlKeyDown = evt.key === "Control";
  16241. if (this.editorUndoBar?.isOpen && evt.keyCode !== 9 && evt.keyCode !== 16 && !((evt.keyCode === 13 || evt.keyCode === 32) && getActiveOrFocusedElement() === this.appConfig.editorUndoBar.undoButton)) {
  16242. this.editorUndoBar.hide();
  16243. }
  16244. if (this.overlayManager.active) {
  16245. return;
  16246. }
  16247. const {
  16248. eventBus,
  16249. pdfViewer
  16250. } = this;
  16251. const isViewerInPresentationMode = pdfViewer.isInPresentationMode;
  16252. let handled = false,
  16253. ensureViewerFocused = false;
  16254. const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0);
  16255. if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
  16256. switch (evt.keyCode) {
  16257. case 70:
  16258. if (!this.supportsIntegratedFind && !evt.shiftKey) {
  16259. this.findBar?.open();
  16260. handled = true;
  16261. }
  16262. break;
  16263. case 71:
  16264. if (!this.supportsIntegratedFind) {
  16265. const {
  16266. state
  16267. } = this.findController;
  16268. if (state) {
  16269. const newState = {
  16270. source: window,
  16271. type: "again",
  16272. findPrevious: cmd === 5 || cmd === 12
  16273. };
  16274. eventBus.dispatch("find", {
  16275. ...state,
  16276. ...newState
  16277. });
  16278. }
  16279. handled = true;
  16280. }
  16281. break;
  16282. case 61:
  16283. case 107:
  16284. case 187:
  16285. case 171:
  16286. this.zoomIn();
  16287. handled = true;
  16288. break;
  16289. case 173:
  16290. case 109:
  16291. case 189:
  16292. this.zoomOut();
  16293. handled = true;
  16294. break;
  16295. case 48:
  16296. case 96:
  16297. if (!isViewerInPresentationMode) {
  16298. setTimeout(() => {
  16299. this.zoomReset();
  16300. });
  16301. handled = false;
  16302. }
  16303. break;
  16304. case 38:
  16305. if (isViewerInPresentationMode || this.page > 1) {
  16306. this.page = 1;
  16307. handled = true;
  16308. ensureViewerFocused = true;
  16309. }
  16310. break;
  16311. case 40:
  16312. if (isViewerInPresentationMode || this.page < this.pagesCount) {
  16313. this.page = this.pagesCount;
  16314. handled = true;
  16315. ensureViewerFocused = true;
  16316. }
  16317. break;
  16318. }
  16319. }
  16320. if (cmd === 1 || cmd === 8) {
  16321. switch (evt.keyCode) {
  16322. case 83:
  16323. eventBus.dispatch("download", {
  16324. source: window
  16325. });
  16326. handled = true;
  16327. break;
  16328. case 79:
  16329. {
  16330. eventBus.dispatch("openfile", {
  16331. source: window
  16332. });
  16333. handled = true;
  16334. }
  16335. break;
  16336. }
  16337. }
  16338. if (cmd === 3 || cmd === 10) {
  16339. switch (evt.keyCode) {
  16340. case 80:
  16341. this.requestPresentationMode();
  16342. handled = true;
  16343. this.externalServices.reportTelemetry({
  16344. type: "buttons",
  16345. data: {
  16346. id: "presentationModeKeyboard"
  16347. }
  16348. });
  16349. break;
  16350. case 71:
  16351. if (this.appConfig.toolbar) {
  16352. this.appConfig.toolbar.pageNumber.select();
  16353. handled = true;
  16354. }
  16355. break;
  16356. }
  16357. }
  16358. if (handled) {
  16359. if (ensureViewerFocused && !isViewerInPresentationMode) {
  16360. pdfViewer.focus();
  16361. }
  16362. evt.preventDefault();
  16363. return;
  16364. }
  16365. const curElement = getActiveOrFocusedElement();
  16366. const curElementTagName = curElement?.tagName.toUpperCase();
  16367. if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElementTagName === "BUTTON" && (evt.keyCode === 13 || evt.keyCode === 32) || curElement?.isContentEditable) {
  16368. if (evt.keyCode !== 27) {
  16369. return;
  16370. }
  16371. }
  16372. if (cmd === 0) {
  16373. let turnPage = 0,
  16374. turnOnlyIfPageFit = false;
  16375. switch (evt.keyCode) {
  16376. case 38:
  16377. if (this.supportsCaretBrowsingMode) {
  16378. this.moveCaret(true, false);
  16379. handled = true;
  16380. break;
  16381. }
  16382. case 33:
  16383. if (pdfViewer.isVerticalScrollbarEnabled) {
  16384. turnOnlyIfPageFit = true;
  16385. }
  16386. turnPage = -1;
  16387. break;
  16388. case 8:
  16389. if (!isViewerInPresentationMode) {
  16390. turnOnlyIfPageFit = true;
  16391. }
  16392. turnPage = -1;
  16393. break;
  16394. case 37:
  16395. if (this.supportsCaretBrowsingMode) {
  16396. return;
  16397. }
  16398. if (pdfViewer.isHorizontalScrollbarEnabled) {
  16399. turnOnlyIfPageFit = true;
  16400. }
  16401. case 75:
  16402. case 80:
  16403. turnPage = -1;
  16404. break;
  16405. case 27:
  16406. if (this.secondaryToolbar?.isOpen) {
  16407. this.secondaryToolbar.close();
  16408. handled = true;
  16409. }
  16410. if (!this.supportsIntegratedFind && this.findBar?.opened) {
  16411. this.findBar.close();
  16412. handled = true;
  16413. }
  16414. break;
  16415. case 40:
  16416. if (this.supportsCaretBrowsingMode) {
  16417. this.moveCaret(false, false);
  16418. handled = true;
  16419. break;
  16420. }
  16421. case 34:
  16422. if (pdfViewer.isVerticalScrollbarEnabled) {
  16423. turnOnlyIfPageFit = true;
  16424. }
  16425. turnPage = 1;
  16426. break;
  16427. case 13:
  16428. case 32:
  16429. if (!isViewerInPresentationMode) {
  16430. turnOnlyIfPageFit = true;
  16431. }
  16432. turnPage = 1;
  16433. break;
  16434. case 39:
  16435. if (this.supportsCaretBrowsingMode) {
  16436. return;
  16437. }
  16438. if (pdfViewer.isHorizontalScrollbarEnabled) {
  16439. turnOnlyIfPageFit = true;
  16440. }
  16441. case 74:
  16442. case 78:
  16443. turnPage = 1;
  16444. break;
  16445. case 36:
  16446. if (isViewerInPresentationMode || this.page > 1) {
  16447. this.page = 1;
  16448. handled = true;
  16449. ensureViewerFocused = true;
  16450. }
  16451. break;
  16452. case 35:
  16453. if (isViewerInPresentationMode || this.page < this.pagesCount) {
  16454. this.page = this.pagesCount;
  16455. handled = true;
  16456. ensureViewerFocused = true;
  16457. }
  16458. break;
  16459. case 83:
  16460. this.pdfCursorTools?.switchTool(CursorTool.SELECT);
  16461. break;
  16462. case 72:
  16463. this.pdfCursorTools?.switchTool(CursorTool.HAND);
  16464. break;
  16465. case 82:
  16466. this.rotatePages(90);
  16467. break;
  16468. case 115:
  16469. this.pdfSidebar?.toggle();
  16470. break;
  16471. }
  16472. if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === "page-fit")) {
  16473. if (turnPage > 0) {
  16474. pdfViewer.nextPage();
  16475. } else {
  16476. pdfViewer.previousPage();
  16477. }
  16478. handled = true;
  16479. }
  16480. }
  16481. if (cmd === 4) {
  16482. switch (evt.keyCode) {
  16483. case 13:
  16484. case 32:
  16485. if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== "page-fit") {
  16486. break;
  16487. }
  16488. pdfViewer.previousPage();
  16489. handled = true;
  16490. break;
  16491. case 38:
  16492. this.moveCaret(true, true);
  16493. handled = true;
  16494. break;
  16495. case 40:
  16496. this.moveCaret(false, true);
  16497. handled = true;
  16498. break;
  16499. case 82:
  16500. this.rotatePages(-90);
  16501. break;
  16502. }
  16503. }
  16504. if (!handled && !isViewerInPresentationMode) {
  16505. if (evt.keyCode >= 33 && evt.keyCode <= 40 || evt.keyCode === 32 && curElementTagName !== "BUTTON") {
  16506. ensureViewerFocused = true;
  16507. }
  16508. }
  16509. if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) {
  16510. pdfViewer.focus();
  16511. }
  16512. if (handled) {
  16513. evt.preventDefault();
  16514. }
  16515. }
  16516. function beforeUnload(evt) {
  16517. evt.preventDefault();
  16518. evt.returnValue = "";
  16519. return false;
  16520. }
  16521. ;// ./web/viewer.js
  16522. const pdfjsVersion = "5.2.133";
  16523. const pdfjsBuild = "4f7761353";
  16524. const AppConstants = {
  16525. LinkTarget: LinkTarget,
  16526. RenderingStates: RenderingStates,
  16527. ScrollMode: ScrollMode,
  16528. SpreadMode: SpreadMode
  16529. };
  16530. window.PDFViewerApplication = PDFViewerApplication;
  16531. window.PDFViewerApplicationConstants = AppConstants;
  16532. window.PDFViewerApplicationOptions = AppOptions;
  16533. function getViewerConfiguration() {
  16534. return {
  16535. appContainer: document.body,
  16536. principalContainer: document.getElementById("mainContainer"),
  16537. mainContainer: document.getElementById("viewerContainer"),
  16538. viewerContainer: document.getElementById("viewer"),
  16539. toolbar: {
  16540. container: document.getElementById("toolbarContainer"),
  16541. numPages: document.getElementById("numPages"),
  16542. pageNumber: document.getElementById("pageNumber"),
  16543. scaleSelect: document.getElementById("scaleSelect"),
  16544. customScaleOption: document.getElementById("customScaleOption"),
  16545. previous: document.getElementById("previous"),
  16546. next: document.getElementById("next"),
  16547. zoomIn: document.getElementById("zoomInButton"),
  16548. zoomOut: document.getElementById("zoomOutButton"),
  16549. print: document.getElementById("printButton"),
  16550. editorFreeTextButton: document.getElementById("editorFreeTextButton"),
  16551. editorFreeTextParamsToolbar: document.getElementById("editorFreeTextParamsToolbar"),
  16552. editorHighlightButton: document.getElementById("editorHighlightButton"),
  16553. editorHighlightParamsToolbar: document.getElementById("editorHighlightParamsToolbar"),
  16554. editorHighlightColorPicker: document.getElementById("editorHighlightColorPicker"),
  16555. editorInkButton: document.getElementById("editorInkButton"),
  16556. editorInkParamsToolbar: document.getElementById("editorInkParamsToolbar"),
  16557. editorStampButton: document.getElementById("editorStampButton"),
  16558. editorStampParamsToolbar: document.getElementById("editorStampParamsToolbar"),
  16559. editorSignatureButton: document.getElementById("editorSignatureButton"),
  16560. editorSignatureParamsToolbar: document.getElementById("editorSignatureParamsToolbar"),
  16561. download: document.getElementById("downloadButton")
  16562. },
  16563. secondaryToolbar: {
  16564. toolbar: document.getElementById("secondaryToolbar"),
  16565. toggleButton: document.getElementById("secondaryToolbarToggleButton"),
  16566. presentationModeButton: document.getElementById("presentationMode"),
  16567. openFileButton: document.getElementById("secondaryOpenFile"),
  16568. printButton: document.getElementById("secondaryPrint"),
  16569. downloadButton: document.getElementById("secondaryDownload"),
  16570. viewBookmarkButton: document.getElementById("viewBookmark"),
  16571. firstPageButton: document.getElementById("firstPage"),
  16572. lastPageButton: document.getElementById("lastPage"),
  16573. pageRotateCwButton: document.getElementById("pageRotateCw"),
  16574. pageRotateCcwButton: document.getElementById("pageRotateCcw"),
  16575. cursorSelectToolButton: document.getElementById("cursorSelectTool"),
  16576. cursorHandToolButton: document.getElementById("cursorHandTool"),
  16577. scrollPageButton: document.getElementById("scrollPage"),
  16578. scrollVerticalButton: document.getElementById("scrollVertical"),
  16579. scrollHorizontalButton: document.getElementById("scrollHorizontal"),
  16580. scrollWrappedButton: document.getElementById("scrollWrapped"),
  16581. spreadNoneButton: document.getElementById("spreadNone"),
  16582. spreadOddButton: document.getElementById("spreadOdd"),
  16583. spreadEvenButton: document.getElementById("spreadEven"),
  16584. imageAltTextSettingsButton: document.getElementById("imageAltTextSettings"),
  16585. imageAltTextSettingsSeparator: document.getElementById("imageAltTextSettingsSeparator"),
  16586. documentPropertiesButton: document.getElementById("documentProperties")
  16587. },
  16588. sidebar: {
  16589. outerContainer: document.getElementById("outerContainer"),
  16590. sidebarContainer: document.getElementById("sidebarContainer"),
  16591. toggleButton: document.getElementById("sidebarToggleButton"),
  16592. resizer: document.getElementById("sidebarResizer"),
  16593. thumbnailButton: document.getElementById("viewThumbnail"),
  16594. outlineButton: document.getElementById("viewOutline"),
  16595. attachmentsButton: document.getElementById("viewAttachments"),
  16596. layersButton: document.getElementById("viewLayers"),
  16597. thumbnailView: document.getElementById("thumbnailView"),
  16598. outlineView: document.getElementById("outlineView"),
  16599. attachmentsView: document.getElementById("attachmentsView"),
  16600. layersView: document.getElementById("layersView"),
  16601. currentOutlineItemButton: document.getElementById("currentOutlineItem")
  16602. },
  16603. findBar: {
  16604. bar: document.getElementById("findbar"),
  16605. toggleButton: document.getElementById("viewFindButton"),
  16606. findField: document.getElementById("findInput"),
  16607. highlightAllCheckbox: document.getElementById("findHighlightAll"),
  16608. caseSensitiveCheckbox: document.getElementById("findMatchCase"),
  16609. matchDiacriticsCheckbox: document.getElementById("findMatchDiacritics"),
  16610. entireWordCheckbox: document.getElementById("findEntireWord"),
  16611. findMsg: document.getElementById("findMsg"),
  16612. findResultsCount: document.getElementById("findResultsCount"),
  16613. findPreviousButton: document.getElementById("findPreviousButton"),
  16614. findNextButton: document.getElementById("findNextButton")
  16615. },
  16616. passwordOverlay: {
  16617. dialog: document.getElementById("passwordDialog"),
  16618. label: document.getElementById("passwordText"),
  16619. input: document.getElementById("password"),
  16620. submitButton: document.getElementById("passwordSubmit"),
  16621. cancelButton: document.getElementById("passwordCancel")
  16622. },
  16623. documentProperties: {
  16624. dialog: document.getElementById("documentPropertiesDialog"),
  16625. closeButton: document.getElementById("documentPropertiesClose"),
  16626. fields: {
  16627. fileName: document.getElementById("fileNameField"),
  16628. fileSize: document.getElementById("fileSizeField"),
  16629. title: document.getElementById("titleField"),
  16630. author: document.getElementById("authorField"),
  16631. subject: document.getElementById("subjectField"),
  16632. keywords: document.getElementById("keywordsField"),
  16633. creationDate: document.getElementById("creationDateField"),
  16634. modificationDate: document.getElementById("modificationDateField"),
  16635. creator: document.getElementById("creatorField"),
  16636. producer: document.getElementById("producerField"),
  16637. version: document.getElementById("versionField"),
  16638. pageCount: document.getElementById("pageCountField"),
  16639. pageSize: document.getElementById("pageSizeField"),
  16640. linearized: document.getElementById("linearizedField")
  16641. }
  16642. },
  16643. altTextDialog: {
  16644. dialog: document.getElementById("altTextDialog"),
  16645. optionDescription: document.getElementById("descriptionButton"),
  16646. optionDecorative: document.getElementById("decorativeButton"),
  16647. textarea: document.getElementById("descriptionTextarea"),
  16648. cancelButton: document.getElementById("altTextCancel"),
  16649. saveButton: document.getElementById("altTextSave")
  16650. },
  16651. newAltTextDialog: {
  16652. dialog: document.getElementById("newAltTextDialog"),
  16653. title: document.getElementById("newAltTextTitle"),
  16654. descriptionContainer: document.getElementById("newAltTextDescriptionContainer"),
  16655. textarea: document.getElementById("newAltTextDescriptionTextarea"),
  16656. disclaimer: document.getElementById("newAltTextDisclaimer"),
  16657. learnMore: document.getElementById("newAltTextLearnMore"),
  16658. imagePreview: document.getElementById("newAltTextImagePreview"),
  16659. createAutomatically: document.getElementById("newAltTextCreateAutomatically"),
  16660. createAutomaticallyButton: document.getElementById("newAltTextCreateAutomaticallyButton"),
  16661. downloadModel: document.getElementById("newAltTextDownloadModel"),
  16662. downloadModelDescription: document.getElementById("newAltTextDownloadModelDescription"),
  16663. error: document.getElementById("newAltTextError"),
  16664. errorCloseButton: document.getElementById("newAltTextCloseButton"),
  16665. cancelButton: document.getElementById("newAltTextCancel"),
  16666. notNowButton: document.getElementById("newAltTextNotNow"),
  16667. saveButton: document.getElementById("newAltTextSave")
  16668. },
  16669. altTextSettingsDialog: {
  16670. dialog: document.getElementById("altTextSettingsDialog"),
  16671. createModelButton: document.getElementById("createModelButton"),
  16672. aiModelSettings: document.getElementById("aiModelSettings"),
  16673. learnMore: document.getElementById("altTextSettingsLearnMore"),
  16674. deleteModelButton: document.getElementById("deleteModelButton"),
  16675. downloadModelButton: document.getElementById("downloadModelButton"),
  16676. showAltTextDialogButton: document.getElementById("showAltTextDialogButton"),
  16677. altTextSettingsCloseButton: document.getElementById("altTextSettingsCloseButton"),
  16678. closeButton: document.getElementById("altTextSettingsCloseButton")
  16679. },
  16680. addSignatureDialog: {
  16681. dialog: document.getElementById("addSignatureDialog"),
  16682. panels: document.getElementById("addSignatureActionContainer"),
  16683. typeButton: document.getElementById("addSignatureTypeButton"),
  16684. typeInput: document.getElementById("addSignatureTypeInput"),
  16685. drawButton: document.getElementById("addSignatureDrawButton"),
  16686. drawSVG: document.getElementById("addSignatureDraw"),
  16687. drawPlaceholder: document.getElementById("addSignatureDrawPlaceholder"),
  16688. drawThickness: document.getElementById("addSignatureDrawThickness"),
  16689. imageButton: document.getElementById("addSignatureImageButton"),
  16690. imageSVG: document.getElementById("addSignatureImage"),
  16691. imagePlaceholder: document.getElementById("addSignatureImagePlaceholder"),
  16692. imagePicker: document.getElementById("addSignatureFilePicker"),
  16693. imagePickerLink: document.getElementById("addSignatureImageBrowse"),
  16694. description: document.getElementById("addSignatureDescription"),
  16695. clearButton: document.getElementById("clearSignatureButton"),
  16696. saveContainer: document.getElementById("addSignatureSaveContainer"),
  16697. saveCheckbox: document.getElementById("addSignatureSaveCheckbox"),
  16698. errorBar: document.getElementById("addSignatureError"),
  16699. errorCloseButton: document.getElementById("addSignatureErrorCloseButton"),
  16700. cancelButton: document.getElementById("addSignatureCancelButton"),
  16701. addButton: document.getElementById("addSignatureAddButton")
  16702. },
  16703. editSignatureDialog: {
  16704. dialog: document.getElementById("editSignatureDescriptionDialog"),
  16705. description: document.getElementById("editSignatureDescription"),
  16706. editSignatureView: document.getElementById("editSignatureView"),
  16707. cancelButton: document.getElementById("editSignatureCancelButton"),
  16708. updateButton: document.getElementById("editSignatureUpdateButton")
  16709. },
  16710. annotationEditorParams: {
  16711. editorFreeTextFontSize: document.getElementById("editorFreeTextFontSize"),
  16712. editorFreeTextColor: document.getElementById("editorFreeTextColor"),
  16713. editorInkColor: document.getElementById("editorInkColor"),
  16714. editorInkThickness: document.getElementById("editorInkThickness"),
  16715. editorInkOpacity: document.getElementById("editorInkOpacity"),
  16716. editorStampAddImage: document.getElementById("editorStampAddImage"),
  16717. editorSignatureAddSignature: document.getElementById("editorSignatureAddSignature"),
  16718. editorFreeHighlightThickness: document.getElementById("editorFreeHighlightThickness"),
  16719. editorHighlightShowAll: document.getElementById("editorHighlightShowAll")
  16720. },
  16721. printContainer: document.getElementById("printContainer"),
  16722. editorUndoBar: {
  16723. container: document.getElementById("editorUndoBar"),
  16724. message: document.getElementById("editorUndoBarMessage"),
  16725. undoButton: document.getElementById("editorUndoBarUndoButton"),
  16726. closeButton: document.getElementById("editorUndoBarCloseButton")
  16727. }
  16728. };
  16729. }
  16730. function webViewerLoad() {
  16731. const config = getViewerConfiguration();
  16732. const event = new CustomEvent("webviewerloaded", {
  16733. bubbles: true,
  16734. cancelable: true,
  16735. detail: {
  16736. source: window
  16737. }
  16738. });
  16739. try {
  16740. parent.document.dispatchEvent(event);
  16741. } catch (ex) {
  16742. console.error("webviewerloaded:", ex);
  16743. document.dispatchEvent(event);
  16744. }
  16745. PDFViewerApplication.run(config);
  16746. }
  16747. document.blockUnblockOnload?.(true);
  16748. if (document.readyState === "interactive" || document.readyState === "complete") {
  16749. webViewerLoad();
  16750. } else {
  16751. document.addEventListener("DOMContentLoaded", webViewerLoad, true);
  16752. }
  16753. export { PDFViewerApplication, AppConstants as PDFViewerApplicationConstants, AppOptions as PDFViewerApplicationOptions };
  16754. //# sourceMappingURL=viewer.mjs.map