pdf.mjs 816 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148
  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. /**
  23. * pdfjsVersion = 5.3.31
  24. * pdfjsBuild = 47ad820d9
  25. */
  26. /******/ var __webpack_modules__ = ({
  27. /***/ 34:
  28. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  29. var isCallable = __webpack_require__(4901);
  30. module.exports = function (it) {
  31. return typeof it == 'object' ? it !== null : isCallable(it);
  32. };
  33. /***/ }),
  34. /***/ 81:
  35. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  36. var call = __webpack_require__(9565);
  37. var aCallable = __webpack_require__(9306);
  38. var anObject = __webpack_require__(8551);
  39. var tryToString = __webpack_require__(6823);
  40. var getIteratorMethod = __webpack_require__(851);
  41. var $TypeError = TypeError;
  42. module.exports = function (argument, usingIterator) {
  43. var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
  44. if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
  45. throw new $TypeError(tryToString(argument) + ' is not iterable');
  46. };
  47. /***/ }),
  48. /***/ 283:
  49. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  50. var uncurryThis = __webpack_require__(9504);
  51. var fails = __webpack_require__(9039);
  52. var isCallable = __webpack_require__(4901);
  53. var hasOwn = __webpack_require__(9297);
  54. var DESCRIPTORS = __webpack_require__(3724);
  55. var CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(350).CONFIGURABLE);
  56. var inspectSource = __webpack_require__(3706);
  57. var InternalStateModule = __webpack_require__(1181);
  58. var enforceInternalState = InternalStateModule.enforce;
  59. var getInternalState = InternalStateModule.get;
  60. var $String = String;
  61. // eslint-disable-next-line es/no-object-defineproperty -- safe
  62. var defineProperty = Object.defineProperty;
  63. var stringSlice = uncurryThis(''.slice);
  64. var replace = uncurryThis(''.replace);
  65. var join = uncurryThis([].join);
  66. var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
  67. return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
  68. });
  69. var TEMPLATE = String(String).split('String');
  70. var makeBuiltIn = module.exports = function (value, name, options) {
  71. if (stringSlice($String(name), 0, 7) === 'Symbol(') {
  72. name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
  73. }
  74. if (options && options.getter) name = 'get ' + name;
  75. if (options && options.setter) name = 'set ' + name;
  76. if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
  77. if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
  78. else value.name = name;
  79. }
  80. if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
  81. defineProperty(value, 'length', { value: options.arity });
  82. }
  83. try {
  84. if (options && hasOwn(options, 'constructor') && options.constructor) {
  85. if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
  86. // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
  87. } else if (value.prototype) value.prototype = undefined;
  88. } catch (error) { /* empty */ }
  89. var state = enforceInternalState(value);
  90. if (!hasOwn(state, 'source')) {
  91. state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
  92. } return value;
  93. };
  94. // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
  95. // eslint-disable-next-line no-extend-native -- required
  96. Function.prototype.toString = makeBuiltIn(function toString() {
  97. return isCallable(this) && getInternalState(this).source || inspectSource(this);
  98. }, 'toString');
  99. /***/ }),
  100. /***/ 350:
  101. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  102. var DESCRIPTORS = __webpack_require__(3724);
  103. var hasOwn = __webpack_require__(9297);
  104. var FunctionPrototype = Function.prototype;
  105. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  106. var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
  107. var EXISTS = hasOwn(FunctionPrototype, 'name');
  108. // additional protection from minified / mangled / dropped function names
  109. var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
  110. var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
  111. module.exports = {
  112. EXISTS: EXISTS,
  113. PROPER: PROPER,
  114. CONFIGURABLE: CONFIGURABLE
  115. };
  116. /***/ }),
  117. /***/ 397:
  118. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  119. var getBuiltIn = __webpack_require__(7751);
  120. module.exports = getBuiltIn('document', 'documentElement');
  121. /***/ }),
  122. /***/ 421:
  123. /***/ ((module) => {
  124. module.exports = {};
  125. /***/ }),
  126. /***/ 507:
  127. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  128. var call = __webpack_require__(9565);
  129. module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
  130. var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
  131. var next = record.next;
  132. var step, result;
  133. while (!(step = call(next, iterator)).done) {
  134. result = fn(step.value);
  135. if (result !== undefined) return result;
  136. }
  137. };
  138. /***/ }),
  139. /***/ 531:
  140. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  141. var $ = __webpack_require__(6518);
  142. var call = __webpack_require__(9565);
  143. var aCallable = __webpack_require__(9306);
  144. var anObject = __webpack_require__(8551);
  145. var getIteratorDirect = __webpack_require__(1767);
  146. var getIteratorFlattenable = __webpack_require__(8646);
  147. var createIteratorProxy = __webpack_require__(9462);
  148. var iteratorClose = __webpack_require__(9539);
  149. var IS_PURE = __webpack_require__(6395);
  150. var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);
  151. var flatMapWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('flatMap', TypeError);
  152. var IteratorProxy = createIteratorProxy(function () {
  153. var iterator = this.iterator;
  154. var mapper = this.mapper;
  155. var result, inner;
  156. while (true) {
  157. if (inner = this.inner) try {
  158. result = anObject(call(inner.next, inner.iterator));
  159. if (!result.done) return result.value;
  160. this.inner = null;
  161. } catch (error) { iteratorClose(iterator, 'throw', error); }
  162. result = anObject(call(this.next, iterator));
  163. if (this.done = !!result.done) return;
  164. try {
  165. this.inner = getIteratorFlattenable(mapper(result.value, this.counter++), false);
  166. } catch (error) { iteratorClose(iterator, 'throw', error); }
  167. }
  168. });
  169. // `Iterator.prototype.flatMap` method
  170. // https://tc39.es/ecma262/#sec-iterator.prototype.flatmap
  171. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || flatMapWithoutClosingOnEarlyError }, {
  172. flatMap: function flatMap(mapper) {
  173. anObject(this);
  174. try {
  175. aCallable(mapper);
  176. } catch (error) {
  177. iteratorClose(this, 'throw', error);
  178. }
  179. if (flatMapWithoutClosingOnEarlyError) return call(flatMapWithoutClosingOnEarlyError, this, mapper);
  180. return new IteratorProxy(getIteratorDirect(this), {
  181. mapper: mapper,
  182. inner: null
  183. });
  184. }
  185. });
  186. /***/ }),
  187. /***/ 616:
  188. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  189. var fails = __webpack_require__(9039);
  190. module.exports = !fails(function () {
  191. // eslint-disable-next-line es/no-function-prototype-bind -- safe
  192. var test = (function () { /* empty */ }).bind();
  193. // eslint-disable-next-line no-prototype-builtins -- safe
  194. return typeof test != 'function' || test.hasOwnProperty('prototype');
  195. });
  196. /***/ }),
  197. /***/ 655:
  198. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  199. var classof = __webpack_require__(6955);
  200. var $String = String;
  201. module.exports = function (argument) {
  202. if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
  203. return $String(argument);
  204. };
  205. /***/ }),
  206. /***/ 679:
  207. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  208. var isPrototypeOf = __webpack_require__(1625);
  209. var $TypeError = TypeError;
  210. module.exports = function (it, Prototype) {
  211. if (isPrototypeOf(Prototype, it)) return it;
  212. throw new $TypeError('Incorrect invocation');
  213. };
  214. /***/ }),
  215. /***/ 741:
  216. /***/ ((module) => {
  217. var ceil = Math.ceil;
  218. var floor = Math.floor;
  219. // `Math.trunc` method
  220. // https://tc39.es/ecma262/#sec-math.trunc
  221. // eslint-disable-next-line es/no-math-trunc -- safe
  222. module.exports = Math.trunc || function trunc(x) {
  223. var n = +x;
  224. return (n > 0 ? floor : ceil)(n);
  225. };
  226. /***/ }),
  227. /***/ 757:
  228. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  229. var getBuiltIn = __webpack_require__(7751);
  230. var isCallable = __webpack_require__(4901);
  231. var isPrototypeOf = __webpack_require__(1625);
  232. var USE_SYMBOL_AS_UID = __webpack_require__(7040);
  233. var $Object = Object;
  234. module.exports = USE_SYMBOL_AS_UID ? function (it) {
  235. return typeof it == 'symbol';
  236. } : function (it) {
  237. var $Symbol = getBuiltIn('Symbol');
  238. return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
  239. };
  240. /***/ }),
  241. /***/ 851:
  242. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  243. var classof = __webpack_require__(6955);
  244. var getMethod = __webpack_require__(5966);
  245. var isNullOrUndefined = __webpack_require__(4117);
  246. var Iterators = __webpack_require__(6269);
  247. var wellKnownSymbol = __webpack_require__(8227);
  248. var ITERATOR = wellKnownSymbol('iterator');
  249. module.exports = function (it) {
  250. if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
  251. || getMethod(it, '@@iterator')
  252. || Iterators[classof(it)];
  253. };
  254. /***/ }),
  255. /***/ 944:
  256. /***/ ((module) => {
  257. var $TypeError = TypeError;
  258. module.exports = function (options) {
  259. var alphabet = options && options.alphabet;
  260. if (alphabet === undefined || alphabet === 'base64' || alphabet === 'base64url') return alphabet || 'base64';
  261. throw new $TypeError('Incorrect `alphabet` option');
  262. };
  263. /***/ }),
  264. /***/ 1072:
  265. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  266. var internalObjectKeys = __webpack_require__(1828);
  267. var enumBugKeys = __webpack_require__(8727);
  268. // `Object.keys` method
  269. // https://tc39.es/ecma262/#sec-object.keys
  270. // eslint-disable-next-line es/no-object-keys -- safe
  271. module.exports = Object.keys || function keys(O) {
  272. return internalObjectKeys(O, enumBugKeys);
  273. };
  274. /***/ }),
  275. /***/ 1103:
  276. /***/ ((module) => {
  277. module.exports = function (exec) {
  278. try {
  279. return { error: false, value: exec() };
  280. } catch (error) {
  281. return { error: true, value: error };
  282. }
  283. };
  284. /***/ }),
  285. /***/ 1148:
  286. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  287. var $ = __webpack_require__(6518);
  288. var call = __webpack_require__(9565);
  289. var iterate = __webpack_require__(2652);
  290. var aCallable = __webpack_require__(9306);
  291. var anObject = __webpack_require__(8551);
  292. var getIteratorDirect = __webpack_require__(1767);
  293. var iteratorClose = __webpack_require__(9539);
  294. var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);
  295. var everyWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('every', TypeError);
  296. // `Iterator.prototype.every` method
  297. // https://tc39.es/ecma262/#sec-iterator.prototype.every
  298. $({ target: 'Iterator', proto: true, real: true, forced: everyWithoutClosingOnEarlyError }, {
  299. every: function every(predicate) {
  300. anObject(this);
  301. try {
  302. aCallable(predicate);
  303. } catch (error) {
  304. iteratorClose(this, 'throw', error);
  305. }
  306. if (everyWithoutClosingOnEarlyError) return call(everyWithoutClosingOnEarlyError, this, predicate);
  307. var record = getIteratorDirect(this);
  308. var counter = 0;
  309. return !iterate(record, function (value, stop) {
  310. if (!predicate(value, counter++)) return stop();
  311. }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
  312. }
  313. });
  314. /***/ }),
  315. /***/ 1181:
  316. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  317. var NATIVE_WEAK_MAP = __webpack_require__(8622);
  318. var globalThis = __webpack_require__(4576);
  319. var isObject = __webpack_require__(34);
  320. var createNonEnumerableProperty = __webpack_require__(6699);
  321. var hasOwn = __webpack_require__(9297);
  322. var shared = __webpack_require__(7629);
  323. var sharedKey = __webpack_require__(6119);
  324. var hiddenKeys = __webpack_require__(421);
  325. var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
  326. var TypeError = globalThis.TypeError;
  327. var WeakMap = globalThis.WeakMap;
  328. var set, get, has;
  329. var enforce = function (it) {
  330. return has(it) ? get(it) : set(it, {});
  331. };
  332. var getterFor = function (TYPE) {
  333. return function (it) {
  334. var state;
  335. if (!isObject(it) || (state = get(it)).type !== TYPE) {
  336. throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
  337. } return state;
  338. };
  339. };
  340. if (NATIVE_WEAK_MAP || shared.state) {
  341. var store = shared.state || (shared.state = new WeakMap());
  342. /* eslint-disable no-self-assign -- prototype methods protection */
  343. store.get = store.get;
  344. store.has = store.has;
  345. store.set = store.set;
  346. /* eslint-enable no-self-assign -- prototype methods protection */
  347. set = function (it, metadata) {
  348. if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
  349. metadata.facade = it;
  350. store.set(it, metadata);
  351. return metadata;
  352. };
  353. get = function (it) {
  354. return store.get(it) || {};
  355. };
  356. has = function (it) {
  357. return store.has(it);
  358. };
  359. } else {
  360. var STATE = sharedKey('state');
  361. hiddenKeys[STATE] = true;
  362. set = function (it, metadata) {
  363. if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
  364. metadata.facade = it;
  365. createNonEnumerableProperty(it, STATE, metadata);
  366. return metadata;
  367. };
  368. get = function (it) {
  369. return hasOwn(it, STATE) ? it[STATE] : {};
  370. };
  371. has = function (it) {
  372. return hasOwn(it, STATE);
  373. };
  374. }
  375. module.exports = {
  376. set: set,
  377. get: get,
  378. has: has,
  379. enforce: enforce,
  380. getterFor: getterFor
  381. };
  382. /***/ }),
  383. /***/ 1291:
  384. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  385. var trunc = __webpack_require__(741);
  386. // `ToIntegerOrInfinity` abstract operation
  387. // https://tc39.es/ecma262/#sec-tointegerorinfinity
  388. module.exports = function (argument) {
  389. var number = +argument;
  390. // eslint-disable-next-line no-self-compare -- NaN check
  391. return number !== number || number === 0 ? 0 : trunc(number);
  392. };
  393. /***/ }),
  394. /***/ 1548:
  395. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  396. var globalThis = __webpack_require__(4576);
  397. var fails = __webpack_require__(9039);
  398. var V8 = __webpack_require__(9519);
  399. var ENVIRONMENT = __webpack_require__(4215);
  400. var structuredClone = globalThis.structuredClone;
  401. module.exports = !!structuredClone && !fails(function () {
  402. // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation
  403. // https://github.com/zloirock/core-js/issues/679
  404. if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false;
  405. var buffer = new ArrayBuffer(8);
  406. var clone = structuredClone(buffer, { transfer: [buffer] });
  407. return buffer.byteLength !== 0 || clone.byteLength !== 8;
  408. });
  409. /***/ }),
  410. /***/ 1549:
  411. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  412. var $ = __webpack_require__(6518);
  413. var globalThis = __webpack_require__(4576);
  414. var $fromBase64 = __webpack_require__(9143);
  415. var anUint8Array = __webpack_require__(4154);
  416. var Uint8Array = globalThis.Uint8Array;
  417. var INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.prototype.setFromBase64 || !(function () {
  418. var target = new Uint8Array([255, 255, 255, 255, 255]);
  419. try {
  420. target.setFromBase64('MjYyZg===');
  421. } catch (error) {
  422. return target[0] === 50 && target[1] === 54 && target[2] === 50 && target[3] === 255 && target[4] === 255;
  423. }
  424. })();
  425. // `Uint8Array.prototype.setFromBase64` method
  426. // https://github.com/tc39/proposal-arraybuffer-base64
  427. if (Uint8Array) $({ target: 'Uint8Array', proto: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, {
  428. setFromBase64: function setFromBase64(string /* , options */) {
  429. anUint8Array(this);
  430. var result = $fromBase64(string, arguments.length > 1 ? arguments[1] : undefined, this, this.length);
  431. return { read: result.read, written: result.written };
  432. }
  433. });
  434. /***/ }),
  435. /***/ 1625:
  436. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  437. var uncurryThis = __webpack_require__(9504);
  438. module.exports = uncurryThis({}.isPrototypeOf);
  439. /***/ }),
  440. /***/ 1689:
  441. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  442. var $ = __webpack_require__(6518);
  443. var globalThis = __webpack_require__(4576);
  444. var apply = __webpack_require__(8745);
  445. var slice = __webpack_require__(7680);
  446. var newPromiseCapabilityModule = __webpack_require__(6043);
  447. var aCallable = __webpack_require__(9306);
  448. var perform = __webpack_require__(1103);
  449. var Promise = globalThis.Promise;
  450. var ACCEPT_ARGUMENTS = false;
  451. // Avoiding the use of polyfills of the previous iteration of this proposal
  452. // that does not accept arguments of the callback
  453. var FORCED = !Promise || !Promise['try'] || perform(function () {
  454. Promise['try'](function (argument) {
  455. ACCEPT_ARGUMENTS = argument === 8;
  456. }, 8);
  457. }).error || !ACCEPT_ARGUMENTS;
  458. // `Promise.try` method
  459. // https://tc39.es/ecma262/#sec-promise.try
  460. $({ target: 'Promise', stat: true, forced: FORCED }, {
  461. 'try': function (callbackfn /* , ...args */) {
  462. var args = arguments.length > 1 ? slice(arguments, 1) : [];
  463. var promiseCapability = newPromiseCapabilityModule.f(this);
  464. var result = perform(function () {
  465. return apply(aCallable(callbackfn), undefined, args);
  466. });
  467. (result.error ? promiseCapability.reject : promiseCapability.resolve)(result.value);
  468. return promiseCapability.promise;
  469. }
  470. });
  471. /***/ }),
  472. /***/ 1698:
  473. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  474. var $ = __webpack_require__(6518);
  475. var union = __webpack_require__(4204);
  476. var setMethodAcceptSetLike = __webpack_require__(4916);
  477. // `Set.prototype.union` method
  478. // https://tc39.es/ecma262/#sec-set.prototype.union
  479. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
  480. union: union
  481. });
  482. /***/ }),
  483. /***/ 1701:
  484. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  485. var $ = __webpack_require__(6518);
  486. var call = __webpack_require__(9565);
  487. var aCallable = __webpack_require__(9306);
  488. var anObject = __webpack_require__(8551);
  489. var getIteratorDirect = __webpack_require__(1767);
  490. var createIteratorProxy = __webpack_require__(9462);
  491. var callWithSafeIterationClosing = __webpack_require__(6319);
  492. var iteratorClose = __webpack_require__(9539);
  493. var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);
  494. var IS_PURE = __webpack_require__(6395);
  495. var mapWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('map', TypeError);
  496. var IteratorProxy = createIteratorProxy(function () {
  497. var iterator = this.iterator;
  498. var result = anObject(call(this.next, iterator));
  499. var done = this.done = !!result.done;
  500. if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
  501. });
  502. // `Iterator.prototype.map` method
  503. // https://tc39.es/ecma262/#sec-iterator.prototype.map
  504. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || mapWithoutClosingOnEarlyError }, {
  505. map: function map(mapper) {
  506. anObject(this);
  507. try {
  508. aCallable(mapper);
  509. } catch (error) {
  510. iteratorClose(this, 'throw', error);
  511. }
  512. if (mapWithoutClosingOnEarlyError) return call(mapWithoutClosingOnEarlyError, this, mapper);
  513. return new IteratorProxy(getIteratorDirect(this), {
  514. mapper: mapper
  515. });
  516. }
  517. });
  518. /***/ }),
  519. /***/ 1767:
  520. /***/ ((module) => {
  521. // `GetIteratorDirect(obj)` abstract operation
  522. // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
  523. module.exports = function (obj) {
  524. return {
  525. iterator: obj,
  526. next: obj.next,
  527. done: false
  528. };
  529. };
  530. /***/ }),
  531. /***/ 1828:
  532. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  533. var uncurryThis = __webpack_require__(9504);
  534. var hasOwn = __webpack_require__(9297);
  535. var toIndexedObject = __webpack_require__(5397);
  536. var indexOf = (__webpack_require__(9617).indexOf);
  537. var hiddenKeys = __webpack_require__(421);
  538. var push = uncurryThis([].push);
  539. module.exports = function (object, names) {
  540. var O = toIndexedObject(object);
  541. var i = 0;
  542. var result = [];
  543. var key;
  544. for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
  545. // Don't enum bug & hidden keys
  546. while (names.length > i) if (hasOwn(O, key = names[i++])) {
  547. ~indexOf(result, key) || push(result, key);
  548. }
  549. return result;
  550. };
  551. /***/ }),
  552. /***/ 2106:
  553. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  554. var makeBuiltIn = __webpack_require__(283);
  555. var defineProperty = __webpack_require__(4913);
  556. module.exports = function (target, name, descriptor) {
  557. if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
  558. if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
  559. return defineProperty.f(target, name, descriptor);
  560. };
  561. /***/ }),
  562. /***/ 2140:
  563. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  564. var wellKnownSymbol = __webpack_require__(8227);
  565. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  566. var test = {};
  567. test[TO_STRING_TAG] = 'z';
  568. module.exports = String(test) === '[object z]';
  569. /***/ }),
  570. /***/ 2195:
  571. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  572. var uncurryThis = __webpack_require__(9504);
  573. var toString = uncurryThis({}.toString);
  574. var stringSlice = uncurryThis(''.slice);
  575. module.exports = function (it) {
  576. return stringSlice(toString(it), 8, -1);
  577. };
  578. /***/ }),
  579. /***/ 2211:
  580. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  581. var fails = __webpack_require__(9039);
  582. module.exports = !fails(function () {
  583. function F() { /* empty */ }
  584. F.prototype.constructor = null;
  585. // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
  586. return Object.getPrototypeOf(new F()) !== F.prototype;
  587. });
  588. /***/ }),
  589. /***/ 2303:
  590. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  591. var globalThis = __webpack_require__(4576);
  592. var uncurryThis = __webpack_require__(9504);
  593. var Uint8Array = globalThis.Uint8Array;
  594. var SyntaxError = globalThis.SyntaxError;
  595. var parseInt = globalThis.parseInt;
  596. var min = Math.min;
  597. var NOT_HEX = /[^\da-f]/i;
  598. var exec = uncurryThis(NOT_HEX.exec);
  599. var stringSlice = uncurryThis(''.slice);
  600. module.exports = function (string, into) {
  601. var stringLength = string.length;
  602. if (stringLength % 2 !== 0) throw new SyntaxError('String should be an even number of characters');
  603. var maxLength = into ? min(into.length, stringLength / 2) : stringLength / 2;
  604. var bytes = into || new Uint8Array(maxLength);
  605. var read = 0;
  606. var written = 0;
  607. while (written < maxLength) {
  608. var hexits = stringSlice(string, read, read += 2);
  609. if (exec(NOT_HEX, hexits)) throw new SyntaxError('String should only contain hex characters');
  610. bytes[written++] = parseInt(hexits, 16);
  611. }
  612. return { bytes: bytes, read: read };
  613. };
  614. /***/ }),
  615. /***/ 2360:
  616. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  617. /* global ActiveXObject -- old IE, WSH */
  618. var anObject = __webpack_require__(8551);
  619. var definePropertiesModule = __webpack_require__(6801);
  620. var enumBugKeys = __webpack_require__(8727);
  621. var hiddenKeys = __webpack_require__(421);
  622. var html = __webpack_require__(397);
  623. var documentCreateElement = __webpack_require__(4055);
  624. var sharedKey = __webpack_require__(6119);
  625. var GT = '>';
  626. var LT = '<';
  627. var PROTOTYPE = 'prototype';
  628. var SCRIPT = 'script';
  629. var IE_PROTO = sharedKey('IE_PROTO');
  630. var EmptyConstructor = function () { /* empty */ };
  631. var scriptTag = function (content) {
  632. return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
  633. };
  634. // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
  635. var NullProtoObjectViaActiveX = function (activeXDocument) {
  636. activeXDocument.write(scriptTag(''));
  637. activeXDocument.close();
  638. var temp = activeXDocument.parentWindow.Object;
  639. // eslint-disable-next-line no-useless-assignment -- avoid memory leak
  640. activeXDocument = null;
  641. return temp;
  642. };
  643. // Create object with fake `null` prototype: use iframe Object with cleared prototype
  644. var NullProtoObjectViaIFrame = function () {
  645. // Thrash, waste and sodomy: IE GC bug
  646. var iframe = documentCreateElement('iframe');
  647. var JS = 'java' + SCRIPT + ':';
  648. var iframeDocument;
  649. iframe.style.display = 'none';
  650. html.appendChild(iframe);
  651. // https://github.com/zloirock/core-js/issues/475
  652. iframe.src = String(JS);
  653. iframeDocument = iframe.contentWindow.document;
  654. iframeDocument.open();
  655. iframeDocument.write(scriptTag('document.F=Object'));
  656. iframeDocument.close();
  657. return iframeDocument.F;
  658. };
  659. // Check for document.domain and active x support
  660. // No need to use active x approach when document.domain is not set
  661. // see https://github.com/es-shims/es5-shim/issues/150
  662. // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
  663. // avoid IE GC bug
  664. var activeXDocument;
  665. var NullProtoObject = function () {
  666. try {
  667. activeXDocument = new ActiveXObject('htmlfile');
  668. } catch (error) { /* ignore */ }
  669. NullProtoObject = typeof document != 'undefined'
  670. ? document.domain && activeXDocument
  671. ? NullProtoObjectViaActiveX(activeXDocument) // old IE
  672. : NullProtoObjectViaIFrame()
  673. : NullProtoObjectViaActiveX(activeXDocument); // WSH
  674. var length = enumBugKeys.length;
  675. while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
  676. return NullProtoObject();
  677. };
  678. hiddenKeys[IE_PROTO] = true;
  679. // `Object.create` method
  680. // https://tc39.es/ecma262/#sec-object.create
  681. // eslint-disable-next-line es/no-object-create -- safe
  682. module.exports = Object.create || function create(O, Properties) {
  683. var result;
  684. if (O !== null) {
  685. EmptyConstructor[PROTOTYPE] = anObject(O);
  686. result = new EmptyConstructor();
  687. EmptyConstructor[PROTOTYPE] = null;
  688. // add "__proto__" for Object.getPrototypeOf polyfill
  689. result[IE_PROTO] = O;
  690. } else result = NullProtoObject();
  691. return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
  692. };
  693. /***/ }),
  694. /***/ 2475:
  695. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  696. var $ = __webpack_require__(6518);
  697. var isSupersetOf = __webpack_require__(8527);
  698. var setMethodAcceptSetLike = __webpack_require__(4916);
  699. var INCORRECT = !setMethodAcceptSetLike('isSupersetOf', function (result) {
  700. return !result;
  701. });
  702. // `Set.prototype.isSupersetOf` method
  703. // https://tc39.es/ecma262/#sec-set.prototype.issupersetof
  704. $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
  705. isSupersetOf: isSupersetOf
  706. });
  707. /***/ }),
  708. /***/ 2489:
  709. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  710. var $ = __webpack_require__(6518);
  711. var call = __webpack_require__(9565);
  712. var aCallable = __webpack_require__(9306);
  713. var anObject = __webpack_require__(8551);
  714. var getIteratorDirect = __webpack_require__(1767);
  715. var createIteratorProxy = __webpack_require__(9462);
  716. var callWithSafeIterationClosing = __webpack_require__(6319);
  717. var IS_PURE = __webpack_require__(6395);
  718. var iteratorClose = __webpack_require__(9539);
  719. var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);
  720. var filterWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('filter', TypeError);
  721. var IteratorProxy = createIteratorProxy(function () {
  722. var iterator = this.iterator;
  723. var predicate = this.predicate;
  724. var next = this.next;
  725. var result, done, value;
  726. while (true) {
  727. result = anObject(call(next, iterator));
  728. done = this.done = !!result.done;
  729. if (done) return;
  730. value = result.value;
  731. if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
  732. }
  733. });
  734. // `Iterator.prototype.filter` method
  735. // https://tc39.es/ecma262/#sec-iterator.prototype.filter
  736. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || filterWithoutClosingOnEarlyError }, {
  737. filter: function filter(predicate) {
  738. anObject(this);
  739. try {
  740. aCallable(predicate);
  741. } catch (error) {
  742. iteratorClose(this, 'throw', error);
  743. }
  744. if (filterWithoutClosingOnEarlyError) return call(filterWithoutClosingOnEarlyError, this, predicate);
  745. return new IteratorProxy(getIteratorDirect(this), {
  746. predicate: predicate
  747. });
  748. }
  749. });
  750. /***/ }),
  751. /***/ 2529:
  752. /***/ ((module) => {
  753. // `CreateIterResultObject` abstract operation
  754. // https://tc39.es/ecma262/#sec-createiterresultobject
  755. module.exports = function (value, done) {
  756. return { value: value, done: done };
  757. };
  758. /***/ }),
  759. /***/ 2603:
  760. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  761. var toString = __webpack_require__(655);
  762. module.exports = function (argument, $default) {
  763. return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
  764. };
  765. /***/ }),
  766. /***/ 2652:
  767. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  768. var bind = __webpack_require__(6080);
  769. var call = __webpack_require__(9565);
  770. var anObject = __webpack_require__(8551);
  771. var tryToString = __webpack_require__(6823);
  772. var isArrayIteratorMethod = __webpack_require__(4209);
  773. var lengthOfArrayLike = __webpack_require__(6198);
  774. var isPrototypeOf = __webpack_require__(1625);
  775. var getIterator = __webpack_require__(81);
  776. var getIteratorMethod = __webpack_require__(851);
  777. var iteratorClose = __webpack_require__(9539);
  778. var $TypeError = TypeError;
  779. var Result = function (stopped, result) {
  780. this.stopped = stopped;
  781. this.result = result;
  782. };
  783. var ResultPrototype = Result.prototype;
  784. module.exports = function (iterable, unboundFunction, options) {
  785. var that = options && options.that;
  786. var AS_ENTRIES = !!(options && options.AS_ENTRIES);
  787. var IS_RECORD = !!(options && options.IS_RECORD);
  788. var IS_ITERATOR = !!(options && options.IS_ITERATOR);
  789. var INTERRUPTED = !!(options && options.INTERRUPTED);
  790. var fn = bind(unboundFunction, that);
  791. var iterator, iterFn, index, length, result, next, step;
  792. var stop = function (condition) {
  793. if (iterator) iteratorClose(iterator, 'normal', condition);
  794. return new Result(true, condition);
  795. };
  796. var callFn = function (value) {
  797. if (AS_ENTRIES) {
  798. anObject(value);
  799. return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
  800. } return INTERRUPTED ? fn(value, stop) : fn(value);
  801. };
  802. if (IS_RECORD) {
  803. iterator = iterable.iterator;
  804. } else if (IS_ITERATOR) {
  805. iterator = iterable;
  806. } else {
  807. iterFn = getIteratorMethod(iterable);
  808. if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
  809. // optimisation for array iterators
  810. if (isArrayIteratorMethod(iterFn)) {
  811. for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
  812. result = callFn(iterable[index]);
  813. if (result && isPrototypeOf(ResultPrototype, result)) return result;
  814. } return new Result(false);
  815. }
  816. iterator = getIterator(iterable, iterFn);
  817. }
  818. next = IS_RECORD ? iterable.next : iterator.next;
  819. while (!(step = call(next, iterator)).done) {
  820. try {
  821. result = callFn(step.value);
  822. } catch (error) {
  823. iteratorClose(iterator, 'throw', error);
  824. }
  825. if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
  826. } return new Result(false);
  827. };
  828. /***/ }),
  829. /***/ 2777:
  830. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  831. var call = __webpack_require__(9565);
  832. var isObject = __webpack_require__(34);
  833. var isSymbol = __webpack_require__(757);
  834. var getMethod = __webpack_require__(5966);
  835. var ordinaryToPrimitive = __webpack_require__(4270);
  836. var wellKnownSymbol = __webpack_require__(8227);
  837. var $TypeError = TypeError;
  838. var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
  839. // `ToPrimitive` abstract operation
  840. // https://tc39.es/ecma262/#sec-toprimitive
  841. module.exports = function (input, pref) {
  842. if (!isObject(input) || isSymbol(input)) return input;
  843. var exoticToPrim = getMethod(input, TO_PRIMITIVE);
  844. var result;
  845. if (exoticToPrim) {
  846. if (pref === undefined) pref = 'default';
  847. result = call(exoticToPrim, input, pref);
  848. if (!isObject(result) || isSymbol(result)) return result;
  849. throw new $TypeError("Can't convert object to primitive value");
  850. }
  851. if (pref === undefined) pref = 'number';
  852. return ordinaryToPrimitive(input, pref);
  853. };
  854. /***/ }),
  855. /***/ 2787:
  856. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  857. var hasOwn = __webpack_require__(9297);
  858. var isCallable = __webpack_require__(4901);
  859. var toObject = __webpack_require__(8981);
  860. var sharedKey = __webpack_require__(6119);
  861. var CORRECT_PROTOTYPE_GETTER = __webpack_require__(2211);
  862. var IE_PROTO = sharedKey('IE_PROTO');
  863. var $Object = Object;
  864. var ObjectPrototype = $Object.prototype;
  865. // `Object.getPrototypeOf` method
  866. // https://tc39.es/ecma262/#sec-object.getprototypeof
  867. // eslint-disable-next-line es/no-object-getprototypeof -- safe
  868. module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
  869. var object = toObject(O);
  870. if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
  871. var constructor = object.constructor;
  872. if (isCallable(constructor) && object instanceof constructor) {
  873. return constructor.prototype;
  874. } return object instanceof $Object ? ObjectPrototype : null;
  875. };
  876. /***/ }),
  877. /***/ 2796:
  878. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  879. var fails = __webpack_require__(9039);
  880. var isCallable = __webpack_require__(4901);
  881. var replacement = /#|\.prototype\./;
  882. var isForced = function (feature, detection) {
  883. var value = data[normalize(feature)];
  884. return value === POLYFILL ? true
  885. : value === NATIVE ? false
  886. : isCallable(detection) ? fails(detection)
  887. : !!detection;
  888. };
  889. var normalize = isForced.normalize = function (string) {
  890. return String(string).replace(replacement, '.').toLowerCase();
  891. };
  892. var data = isForced.data = {};
  893. var NATIVE = isForced.NATIVE = 'N';
  894. var POLYFILL = isForced.POLYFILL = 'P';
  895. module.exports = isForced;
  896. /***/ }),
  897. /***/ 2804:
  898. /***/ ((module) => {
  899. var commonAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  900. var base64Alphabet = commonAlphabet + '+/';
  901. var base64UrlAlphabet = commonAlphabet + '-_';
  902. var inverse = function (characters) {
  903. // TODO: use `Object.create(null)` in `core-js@4`
  904. var result = {};
  905. var index = 0;
  906. for (; index < 64; index++) result[characters.charAt(index)] = index;
  907. return result;
  908. };
  909. module.exports = {
  910. i2c: base64Alphabet,
  911. c2i: inverse(base64Alphabet),
  912. i2cUrl: base64UrlAlphabet,
  913. c2iUrl: inverse(base64UrlAlphabet)
  914. };
  915. /***/ }),
  916. /***/ 2812:
  917. /***/ ((module) => {
  918. var $TypeError = TypeError;
  919. module.exports = function (passed, required) {
  920. if (passed < required) throw new $TypeError('Not enough arguments');
  921. return passed;
  922. };
  923. /***/ }),
  924. /***/ 2839:
  925. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  926. var globalThis = __webpack_require__(4576);
  927. var navigator = globalThis.navigator;
  928. var userAgent = navigator && navigator.userAgent;
  929. module.exports = userAgent ? String(userAgent) : '';
  930. /***/ }),
  931. /***/ 2967:
  932. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  933. /* eslint-disable no-proto -- safe */
  934. var uncurryThisAccessor = __webpack_require__(6706);
  935. var isObject = __webpack_require__(34);
  936. var requireObjectCoercible = __webpack_require__(7750);
  937. var aPossiblePrototype = __webpack_require__(3506);
  938. // `Object.setPrototypeOf` method
  939. // https://tc39.es/ecma262/#sec-object.setprototypeof
  940. // Works with __proto__ only. Old v8 can't work with null proto objects.
  941. // eslint-disable-next-line es/no-object-setprototypeof -- safe
  942. module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
  943. var CORRECT_SETTER = false;
  944. var test = {};
  945. var setter;
  946. try {
  947. setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
  948. setter(test, []);
  949. CORRECT_SETTER = test instanceof Array;
  950. } catch (error) { /* empty */ }
  951. return function setPrototypeOf(O, proto) {
  952. requireObjectCoercible(O);
  953. aPossiblePrototype(proto);
  954. if (!isObject(O)) return O;
  955. if (CORRECT_SETTER) setter(O, proto);
  956. else O.__proto__ = proto;
  957. return O;
  958. };
  959. }() : undefined);
  960. /***/ }),
  961. /***/ 3167:
  962. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  963. var isCallable = __webpack_require__(4901);
  964. var isObject = __webpack_require__(34);
  965. var setPrototypeOf = __webpack_require__(2967);
  966. // makes subclassing work correct for wrapped built-ins
  967. module.exports = function ($this, dummy, Wrapper) {
  968. var NewTarget, NewTargetPrototype;
  969. if (
  970. // it can work only with native `setPrototypeOf`
  971. setPrototypeOf &&
  972. // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
  973. isCallable(NewTarget = dummy.constructor) &&
  974. NewTarget !== Wrapper &&
  975. isObject(NewTargetPrototype = NewTarget.prototype) &&
  976. NewTargetPrototype !== Wrapper.prototype
  977. ) setPrototypeOf($this, NewTargetPrototype);
  978. return $this;
  979. };
  980. /***/ }),
  981. /***/ 3238:
  982. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  983. var globalThis = __webpack_require__(4576);
  984. var NATIVE_ARRAY_BUFFER = __webpack_require__(7811);
  985. var arrayBufferByteLength = __webpack_require__(7394);
  986. var DataView = globalThis.DataView;
  987. module.exports = function (O) {
  988. if (!NATIVE_ARRAY_BUFFER || arrayBufferByteLength(O) !== 0) return false;
  989. try {
  990. // eslint-disable-next-line no-new -- thrower
  991. new DataView(O);
  992. return false;
  993. } catch (error) {
  994. return true;
  995. }
  996. };
  997. /***/ }),
  998. /***/ 3392:
  999. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1000. var uncurryThis = __webpack_require__(9504);
  1001. var id = 0;
  1002. var postfix = Math.random();
  1003. var toString = uncurryThis(1.0.toString);
  1004. module.exports = function (key) {
  1005. return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
  1006. };
  1007. /***/ }),
  1008. /***/ 3440:
  1009. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1010. var aSet = __webpack_require__(7080);
  1011. var SetHelpers = __webpack_require__(4402);
  1012. var clone = __webpack_require__(9286);
  1013. var size = __webpack_require__(5170);
  1014. var getSetRecord = __webpack_require__(3789);
  1015. var iterateSet = __webpack_require__(8469);
  1016. var iterateSimple = __webpack_require__(507);
  1017. var has = SetHelpers.has;
  1018. var remove = SetHelpers.remove;
  1019. // `Set.prototype.difference` method
  1020. // https://github.com/tc39/proposal-set-methods
  1021. module.exports = function difference(other) {
  1022. var O = aSet(this);
  1023. var otherRec = getSetRecord(other);
  1024. var result = clone(O);
  1025. if (size(O) <= otherRec.size) iterateSet(O, function (e) {
  1026. if (otherRec.includes(e)) remove(result, e);
  1027. });
  1028. else iterateSimple(otherRec.getIterator(), function (e) {
  1029. if (has(O, e)) remove(result, e);
  1030. });
  1031. return result;
  1032. };
  1033. /***/ }),
  1034. /***/ 3463:
  1035. /***/ ((module) => {
  1036. var $TypeError = TypeError;
  1037. module.exports = function (argument) {
  1038. if (typeof argument == 'string') return argument;
  1039. throw new $TypeError('Argument is not a string');
  1040. };
  1041. /***/ }),
  1042. /***/ 3506:
  1043. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1044. var isPossiblePrototype = __webpack_require__(3925);
  1045. var $String = String;
  1046. var $TypeError = TypeError;
  1047. module.exports = function (argument) {
  1048. if (isPossiblePrototype(argument)) return argument;
  1049. throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
  1050. };
  1051. /***/ }),
  1052. /***/ 3579:
  1053. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1054. var $ = __webpack_require__(6518);
  1055. var call = __webpack_require__(9565);
  1056. var iterate = __webpack_require__(2652);
  1057. var aCallable = __webpack_require__(9306);
  1058. var anObject = __webpack_require__(8551);
  1059. var getIteratorDirect = __webpack_require__(1767);
  1060. var iteratorClose = __webpack_require__(9539);
  1061. var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);
  1062. var someWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('some', TypeError);
  1063. // `Iterator.prototype.some` method
  1064. // https://tc39.es/ecma262/#sec-iterator.prototype.some
  1065. $({ target: 'Iterator', proto: true, real: true, forced: someWithoutClosingOnEarlyError }, {
  1066. some: function some(predicate) {
  1067. anObject(this);
  1068. try {
  1069. aCallable(predicate);
  1070. } catch (error) {
  1071. iteratorClose(this, 'throw', error);
  1072. }
  1073. if (someWithoutClosingOnEarlyError) return call(someWithoutClosingOnEarlyError, this, predicate);
  1074. var record = getIteratorDirect(this);
  1075. var counter = 0;
  1076. return iterate(record, function (value, stop) {
  1077. if (predicate(value, counter++)) return stop();
  1078. }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
  1079. }
  1080. });
  1081. /***/ }),
  1082. /***/ 3650:
  1083. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1084. var aSet = __webpack_require__(7080);
  1085. var SetHelpers = __webpack_require__(4402);
  1086. var clone = __webpack_require__(9286);
  1087. var getSetRecord = __webpack_require__(3789);
  1088. var iterateSimple = __webpack_require__(507);
  1089. var add = SetHelpers.add;
  1090. var has = SetHelpers.has;
  1091. var remove = SetHelpers.remove;
  1092. // `Set.prototype.symmetricDifference` method
  1093. // https://github.com/tc39/proposal-set-methods
  1094. module.exports = function symmetricDifference(other) {
  1095. var O = aSet(this);
  1096. var keysIter = getSetRecord(other).getIterator();
  1097. var result = clone(O);
  1098. iterateSimple(keysIter, function (e) {
  1099. if (has(O, e)) remove(result, e);
  1100. else add(result, e);
  1101. });
  1102. return result;
  1103. };
  1104. /***/ }),
  1105. /***/ 3706:
  1106. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1107. var uncurryThis = __webpack_require__(9504);
  1108. var isCallable = __webpack_require__(4901);
  1109. var store = __webpack_require__(7629);
  1110. var functionToString = uncurryThis(Function.toString);
  1111. // this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
  1112. if (!isCallable(store.inspectSource)) {
  1113. store.inspectSource = function (it) {
  1114. return functionToString(it);
  1115. };
  1116. }
  1117. module.exports = store.inspectSource;
  1118. /***/ }),
  1119. /***/ 3717:
  1120. /***/ ((__unused_webpack_module, exports) => {
  1121. // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
  1122. exports.f = Object.getOwnPropertySymbols;
  1123. /***/ }),
  1124. /***/ 3724:
  1125. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1126. var fails = __webpack_require__(9039);
  1127. // Detect IE8's incomplete defineProperty implementation
  1128. module.exports = !fails(function () {
  1129. // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  1130. return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
  1131. });
  1132. /***/ }),
  1133. /***/ 3789:
  1134. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1135. var aCallable = __webpack_require__(9306);
  1136. var anObject = __webpack_require__(8551);
  1137. var call = __webpack_require__(9565);
  1138. var toIntegerOrInfinity = __webpack_require__(1291);
  1139. var getIteratorDirect = __webpack_require__(1767);
  1140. var INVALID_SIZE = 'Invalid size';
  1141. var $RangeError = RangeError;
  1142. var $TypeError = TypeError;
  1143. var max = Math.max;
  1144. var SetRecord = function (set, intSize) {
  1145. this.set = set;
  1146. this.size = max(intSize, 0);
  1147. this.has = aCallable(set.has);
  1148. this.keys = aCallable(set.keys);
  1149. };
  1150. SetRecord.prototype = {
  1151. getIterator: function () {
  1152. return getIteratorDirect(anObject(call(this.keys, this.set)));
  1153. },
  1154. includes: function (it) {
  1155. return call(this.has, this.set, it);
  1156. }
  1157. };
  1158. // `GetSetRecord` abstract operation
  1159. // https://tc39.es/proposal-set-methods/#sec-getsetrecord
  1160. module.exports = function (obj) {
  1161. anObject(obj);
  1162. var numSize = +obj.size;
  1163. // NOTE: If size is undefined, then numSize will be NaN
  1164. // eslint-disable-next-line no-self-compare -- NaN check
  1165. if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
  1166. var intSize = toIntegerOrInfinity(numSize);
  1167. if (intSize < 0) throw new $RangeError(INVALID_SIZE);
  1168. return new SetRecord(obj, intSize);
  1169. };
  1170. /***/ }),
  1171. /***/ 3838:
  1172. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1173. var aSet = __webpack_require__(7080);
  1174. var size = __webpack_require__(5170);
  1175. var iterate = __webpack_require__(8469);
  1176. var getSetRecord = __webpack_require__(3789);
  1177. // `Set.prototype.isSubsetOf` method
  1178. // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
  1179. module.exports = function isSubsetOf(other) {
  1180. var O = aSet(this);
  1181. var otherRec = getSetRecord(other);
  1182. if (size(O) > otherRec.size) return false;
  1183. return iterate(O, function (e) {
  1184. if (!otherRec.includes(e)) return false;
  1185. }, true) !== false;
  1186. };
  1187. /***/ }),
  1188. /***/ 3853:
  1189. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1190. var $ = __webpack_require__(6518);
  1191. var isDisjointFrom = __webpack_require__(4449);
  1192. var setMethodAcceptSetLike = __webpack_require__(4916);
  1193. var INCORRECT = !setMethodAcceptSetLike('isDisjointFrom', function (result) {
  1194. return !result;
  1195. });
  1196. // `Set.prototype.isDisjointFrom` method
  1197. // https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
  1198. $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
  1199. isDisjointFrom: isDisjointFrom
  1200. });
  1201. /***/ }),
  1202. /***/ 3925:
  1203. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1204. var isObject = __webpack_require__(34);
  1205. module.exports = function (argument) {
  1206. return isObject(argument) || argument === null;
  1207. };
  1208. /***/ }),
  1209. /***/ 3972:
  1210. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1211. var isObject = __webpack_require__(34);
  1212. var $String = String;
  1213. var $TypeError = TypeError;
  1214. module.exports = function (argument) {
  1215. if (argument === undefined || isObject(argument)) return argument;
  1216. throw new $TypeError($String(argument) + ' is not an object or undefined');
  1217. };
  1218. /***/ }),
  1219. /***/ 4055:
  1220. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1221. var globalThis = __webpack_require__(4576);
  1222. var isObject = __webpack_require__(34);
  1223. var document = globalThis.document;
  1224. // typeof document.createElement is 'object' in old IE
  1225. var EXISTS = isObject(document) && isObject(document.createElement);
  1226. module.exports = function (it) {
  1227. return EXISTS ? document.createElement(it) : {};
  1228. };
  1229. /***/ }),
  1230. /***/ 4114:
  1231. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1232. var $ = __webpack_require__(6518);
  1233. var toObject = __webpack_require__(8981);
  1234. var lengthOfArrayLike = __webpack_require__(6198);
  1235. var setArrayLength = __webpack_require__(4527);
  1236. var doesNotExceedSafeInteger = __webpack_require__(6837);
  1237. var fails = __webpack_require__(9039);
  1238. var INCORRECT_TO_LENGTH = fails(function () {
  1239. return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
  1240. });
  1241. // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
  1242. // https://bugs.chromium.org/p/v8/issues/detail?id=12681
  1243. var properErrorOnNonWritableLength = function () {
  1244. try {
  1245. // eslint-disable-next-line es/no-object-defineproperty -- safe
  1246. Object.defineProperty([], 'length', { writable: false }).push();
  1247. } catch (error) {
  1248. return error instanceof TypeError;
  1249. }
  1250. };
  1251. var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
  1252. // `Array.prototype.push` method
  1253. // https://tc39.es/ecma262/#sec-array.prototype.push
  1254. $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
  1255. // eslint-disable-next-line no-unused-vars -- required for `.length`
  1256. push: function push(item) {
  1257. var O = toObject(this);
  1258. var len = lengthOfArrayLike(O);
  1259. var argCount = arguments.length;
  1260. doesNotExceedSafeInteger(len + argCount);
  1261. for (var i = 0; i < argCount; i++) {
  1262. O[len] = arguments[i];
  1263. len++;
  1264. }
  1265. setArrayLength(O, len);
  1266. return len;
  1267. }
  1268. });
  1269. /***/ }),
  1270. /***/ 4117:
  1271. /***/ ((module) => {
  1272. // we can't use just `it == null` since of `document.all` special case
  1273. // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1274. module.exports = function (it) {
  1275. return it === null || it === undefined;
  1276. };
  1277. /***/ }),
  1278. /***/ 4149:
  1279. /***/ ((module) => {
  1280. var $RangeError = RangeError;
  1281. module.exports = function (it) {
  1282. // eslint-disable-next-line no-self-compare -- NaN check
  1283. if (it === it) return it;
  1284. throw new $RangeError('NaN is not allowed');
  1285. };
  1286. /***/ }),
  1287. /***/ 4154:
  1288. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1289. var classof = __webpack_require__(6955);
  1290. var $TypeError = TypeError;
  1291. // Perform ? RequireInternalSlot(argument, [[TypedArrayName]])
  1292. // If argument.[[TypedArrayName]] is not "Uint8Array", throw a TypeError exception
  1293. module.exports = function (argument) {
  1294. if (classof(argument) === 'Uint8Array') return argument;
  1295. throw new $TypeError('Argument is not an Uint8Array');
  1296. };
  1297. /***/ }),
  1298. /***/ 4204:
  1299. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1300. var aSet = __webpack_require__(7080);
  1301. var add = (__webpack_require__(4402).add);
  1302. var clone = __webpack_require__(9286);
  1303. var getSetRecord = __webpack_require__(3789);
  1304. var iterateSimple = __webpack_require__(507);
  1305. // `Set.prototype.union` method
  1306. // https://github.com/tc39/proposal-set-methods
  1307. module.exports = function union(other) {
  1308. var O = aSet(this);
  1309. var keysIter = getSetRecord(other).getIterator();
  1310. var result = clone(O);
  1311. iterateSimple(keysIter, function (it) {
  1312. add(result, it);
  1313. });
  1314. return result;
  1315. };
  1316. /***/ }),
  1317. /***/ 4209:
  1318. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1319. var wellKnownSymbol = __webpack_require__(8227);
  1320. var Iterators = __webpack_require__(6269);
  1321. var ITERATOR = wellKnownSymbol('iterator');
  1322. var ArrayPrototype = Array.prototype;
  1323. // check on default Array iterator
  1324. module.exports = function (it) {
  1325. return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
  1326. };
  1327. /***/ }),
  1328. /***/ 4215:
  1329. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1330. /* global Bun, Deno -- detection */
  1331. var globalThis = __webpack_require__(4576);
  1332. var userAgent = __webpack_require__(2839);
  1333. var classof = __webpack_require__(2195);
  1334. var userAgentStartsWith = function (string) {
  1335. return userAgent.slice(0, string.length) === string;
  1336. };
  1337. module.exports = (function () {
  1338. if (userAgentStartsWith('Bun/')) return 'BUN';
  1339. if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE';
  1340. if (userAgentStartsWith('Deno/')) return 'DENO';
  1341. if (userAgentStartsWith('Node.js/')) return 'NODE';
  1342. if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN';
  1343. if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO';
  1344. if (classof(globalThis.process) === 'process') return 'NODE';
  1345. if (globalThis.window && globalThis.document) return 'BROWSER';
  1346. return 'REST';
  1347. })();
  1348. /***/ }),
  1349. /***/ 4270:
  1350. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1351. var call = __webpack_require__(9565);
  1352. var isCallable = __webpack_require__(4901);
  1353. var isObject = __webpack_require__(34);
  1354. var $TypeError = TypeError;
  1355. // `OrdinaryToPrimitive` abstract operation
  1356. // https://tc39.es/ecma262/#sec-ordinarytoprimitive
  1357. module.exports = function (input, pref) {
  1358. var fn, val;
  1359. if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  1360. if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
  1361. if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  1362. throw new $TypeError("Can't convert object to primitive value");
  1363. };
  1364. /***/ }),
  1365. /***/ 4376:
  1366. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1367. var classof = __webpack_require__(2195);
  1368. // `IsArray` abstract operation
  1369. // https://tc39.es/ecma262/#sec-isarray
  1370. // eslint-disable-next-line es/no-array-isarray -- safe
  1371. module.exports = Array.isArray || function isArray(argument) {
  1372. return classof(argument) === 'Array';
  1373. };
  1374. /***/ }),
  1375. /***/ 4402:
  1376. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1377. var uncurryThis = __webpack_require__(9504);
  1378. // eslint-disable-next-line es/no-set -- safe
  1379. var SetPrototype = Set.prototype;
  1380. module.exports = {
  1381. // eslint-disable-next-line es/no-set -- safe
  1382. Set: Set,
  1383. add: uncurryThis(SetPrototype.add),
  1384. has: uncurryThis(SetPrototype.has),
  1385. remove: uncurryThis(SetPrototype['delete']),
  1386. proto: SetPrototype
  1387. };
  1388. /***/ }),
  1389. /***/ 4449:
  1390. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1391. var aSet = __webpack_require__(7080);
  1392. var has = (__webpack_require__(4402).has);
  1393. var size = __webpack_require__(5170);
  1394. var getSetRecord = __webpack_require__(3789);
  1395. var iterateSet = __webpack_require__(8469);
  1396. var iterateSimple = __webpack_require__(507);
  1397. var iteratorClose = __webpack_require__(9539);
  1398. // `Set.prototype.isDisjointFrom` method
  1399. // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
  1400. module.exports = function isDisjointFrom(other) {
  1401. var O = aSet(this);
  1402. var otherRec = getSetRecord(other);
  1403. if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
  1404. if (otherRec.includes(e)) return false;
  1405. }, true) !== false;
  1406. var iterator = otherRec.getIterator();
  1407. return iterateSimple(iterator, function (e) {
  1408. if (has(O, e)) return iteratorClose(iterator, 'normal', false);
  1409. }) !== false;
  1410. };
  1411. /***/ }),
  1412. /***/ 4483:
  1413. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1414. var globalThis = __webpack_require__(4576);
  1415. var getBuiltInNodeModule = __webpack_require__(9429);
  1416. var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);
  1417. var structuredClone = globalThis.structuredClone;
  1418. var $ArrayBuffer = globalThis.ArrayBuffer;
  1419. var $MessageChannel = globalThis.MessageChannel;
  1420. var detach = false;
  1421. var WorkerThreads, channel, buffer, $detach;
  1422. if (PROPER_STRUCTURED_CLONE_TRANSFER) {
  1423. detach = function (transferable) {
  1424. structuredClone(transferable, { transfer: [transferable] });
  1425. };
  1426. } else if ($ArrayBuffer) try {
  1427. if (!$MessageChannel) {
  1428. WorkerThreads = getBuiltInNodeModule('worker_threads');
  1429. if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;
  1430. }
  1431. if ($MessageChannel) {
  1432. channel = new $MessageChannel();
  1433. buffer = new $ArrayBuffer(2);
  1434. $detach = function (transferable) {
  1435. channel.port1.postMessage(null, [transferable]);
  1436. };
  1437. if (buffer.byteLength === 2) {
  1438. $detach(buffer);
  1439. if (buffer.byteLength === 0) detach = $detach;
  1440. }
  1441. }
  1442. } catch (error) { /* empty */ }
  1443. module.exports = detach;
  1444. /***/ }),
  1445. /***/ 4495:
  1446. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1447. /* eslint-disable es/no-symbol -- required for testing */
  1448. var V8_VERSION = __webpack_require__(9519);
  1449. var fails = __webpack_require__(9039);
  1450. var globalThis = __webpack_require__(4576);
  1451. var $String = globalThis.String;
  1452. // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
  1453. module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
  1454. var symbol = Symbol('symbol detection');
  1455. // Chrome 38 Symbol has incorrect toString conversion
  1456. // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
  1457. // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
  1458. // of course, fail.
  1459. return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
  1460. // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
  1461. !Symbol.sham && V8_VERSION && V8_VERSION < 41;
  1462. });
  1463. /***/ }),
  1464. /***/ 4527:
  1465. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1466. var DESCRIPTORS = __webpack_require__(3724);
  1467. var isArray = __webpack_require__(4376);
  1468. var $TypeError = TypeError;
  1469. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  1470. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1471. // Safari < 13 does not throw an error in this case
  1472. var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
  1473. // makes no sense without proper strict mode support
  1474. if (this !== undefined) return true;
  1475. try {
  1476. // eslint-disable-next-line es/no-object-defineproperty -- safe
  1477. Object.defineProperty([], 'length', { writable: false }).length = 1;
  1478. } catch (error) {
  1479. return error instanceof TypeError;
  1480. }
  1481. }();
  1482. module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
  1483. if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
  1484. throw new $TypeError('Cannot set read only .length');
  1485. } return O.length = length;
  1486. } : function (O, length) {
  1487. return O.length = length;
  1488. };
  1489. /***/ }),
  1490. /***/ 4549:
  1491. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1492. var globalThis = __webpack_require__(4576);
  1493. // https://github.com/tc39/ecma262/pull/3467
  1494. module.exports = function (METHOD_NAME, ExpectedError) {
  1495. var Iterator = globalThis.Iterator;
  1496. var IteratorPrototype = Iterator && Iterator.prototype;
  1497. var method = IteratorPrototype && IteratorPrototype[METHOD_NAME];
  1498. var CLOSED = false;
  1499. if (method) try {
  1500. method.call({
  1501. next: function () { return { done: true }; },
  1502. 'return': function () { CLOSED = true; }
  1503. }, -1);
  1504. } catch (error) {
  1505. // https://bugs.webkit.org/show_bug.cgi?id=291195
  1506. if (!(error instanceof ExpectedError)) CLOSED = false;
  1507. }
  1508. if (!CLOSED) return method;
  1509. };
  1510. /***/ }),
  1511. /***/ 4576:
  1512. /***/ (function(module) {
  1513. var check = function (it) {
  1514. return it && it.Math === Math && it;
  1515. };
  1516. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  1517. module.exports =
  1518. // eslint-disable-next-line es/no-global-this -- safe
  1519. check(typeof globalThis == 'object' && globalThis) ||
  1520. check(typeof window == 'object' && window) ||
  1521. // eslint-disable-next-line no-restricted-globals -- safe
  1522. check(typeof self == 'object' && self) ||
  1523. check(typeof global == 'object' && global) ||
  1524. check(typeof this == 'object' && this) ||
  1525. // eslint-disable-next-line no-new-func -- fallback
  1526. (function () { return this; })() || Function('return this')();
  1527. /***/ }),
  1528. /***/ 4603:
  1529. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1530. var defineBuiltIn = __webpack_require__(6840);
  1531. var uncurryThis = __webpack_require__(9504);
  1532. var toString = __webpack_require__(655);
  1533. var validateArgumentsLength = __webpack_require__(2812);
  1534. var $URLSearchParams = URLSearchParams;
  1535. var URLSearchParamsPrototype = $URLSearchParams.prototype;
  1536. var append = uncurryThis(URLSearchParamsPrototype.append);
  1537. var $delete = uncurryThis(URLSearchParamsPrototype['delete']);
  1538. var forEach = uncurryThis(URLSearchParamsPrototype.forEach);
  1539. var push = uncurryThis([].push);
  1540. var params = new $URLSearchParams('a=1&a=2&b=3');
  1541. params['delete']('a', 1);
  1542. // `undefined` case is a Chromium 117 bug
  1543. // https://bugs.chromium.org/p/v8/issues/detail?id=14222
  1544. params['delete']('b', undefined);
  1545. if (params + '' !== 'a=2') {
  1546. defineBuiltIn(URLSearchParamsPrototype, 'delete', function (name /* , value */) {
  1547. var length = arguments.length;
  1548. var $value = length < 2 ? undefined : arguments[1];
  1549. if (length && $value === undefined) return $delete(this, name);
  1550. var entries = [];
  1551. forEach(this, function (v, k) { // also validates `this`
  1552. push(entries, { key: k, value: v });
  1553. });
  1554. validateArgumentsLength(length, 1);
  1555. var key = toString(name);
  1556. var value = toString($value);
  1557. var index = 0;
  1558. var dindex = 0;
  1559. var found = false;
  1560. var entriesLength = entries.length;
  1561. var entry;
  1562. while (index < entriesLength) {
  1563. entry = entries[index++];
  1564. if (found || entry.key === key) {
  1565. found = true;
  1566. $delete(this, entry.key);
  1567. } else dindex++;
  1568. }
  1569. while (dindex < entriesLength) {
  1570. entry = entries[dindex++];
  1571. if (!(entry.key === key && entry.value === value)) append(this, entry.key, entry.value);
  1572. }
  1573. }, { enumerable: true, unsafe: true });
  1574. }
  1575. /***/ }),
  1576. /***/ 4628:
  1577. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1578. var $ = __webpack_require__(6518);
  1579. var newPromiseCapabilityModule = __webpack_require__(6043);
  1580. // `Promise.withResolvers` method
  1581. // https://tc39.es/ecma262/#sec-promise.withResolvers
  1582. $({ target: 'Promise', stat: true }, {
  1583. withResolvers: function withResolvers() {
  1584. var promiseCapability = newPromiseCapabilityModule.f(this);
  1585. return {
  1586. promise: promiseCapability.promise,
  1587. resolve: promiseCapability.resolve,
  1588. reject: promiseCapability.reject
  1589. };
  1590. }
  1591. });
  1592. /***/ }),
  1593. /***/ 4659:
  1594. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1595. var DESCRIPTORS = __webpack_require__(3724);
  1596. var definePropertyModule = __webpack_require__(4913);
  1597. var createPropertyDescriptor = __webpack_require__(6980);
  1598. module.exports = function (object, key, value) {
  1599. if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
  1600. else object[key] = value;
  1601. };
  1602. /***/ }),
  1603. /***/ 4901:
  1604. /***/ ((module) => {
  1605. // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
  1606. var documentAll = typeof document == 'object' && document.all;
  1607. // `IsCallable` abstract operation
  1608. // https://tc39.es/ecma262/#sec-iscallable
  1609. // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
  1610. module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
  1611. return typeof argument == 'function' || argument === documentAll;
  1612. } : function (argument) {
  1613. return typeof argument == 'function';
  1614. };
  1615. /***/ }),
  1616. /***/ 4913:
  1617. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1618. var DESCRIPTORS = __webpack_require__(3724);
  1619. var IE8_DOM_DEFINE = __webpack_require__(5917);
  1620. var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);
  1621. var anObject = __webpack_require__(8551);
  1622. var toPropertyKey = __webpack_require__(6969);
  1623. var $TypeError = TypeError;
  1624. // eslint-disable-next-line es/no-object-defineproperty -- safe
  1625. var $defineProperty = Object.defineProperty;
  1626. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  1627. var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1628. var ENUMERABLE = 'enumerable';
  1629. var CONFIGURABLE = 'configurable';
  1630. var WRITABLE = 'writable';
  1631. // `Object.defineProperty` method
  1632. // https://tc39.es/ecma262/#sec-object.defineproperty
  1633. exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
  1634. anObject(O);
  1635. P = toPropertyKey(P);
  1636. anObject(Attributes);
  1637. if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
  1638. var current = $getOwnPropertyDescriptor(O, P);
  1639. if (current && current[WRITABLE]) {
  1640. O[P] = Attributes.value;
  1641. Attributes = {
  1642. configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
  1643. enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
  1644. writable: false
  1645. };
  1646. }
  1647. } return $defineProperty(O, P, Attributes);
  1648. } : $defineProperty : function defineProperty(O, P, Attributes) {
  1649. anObject(O);
  1650. P = toPropertyKey(P);
  1651. anObject(Attributes);
  1652. if (IE8_DOM_DEFINE) try {
  1653. return $defineProperty(O, P, Attributes);
  1654. } catch (error) { /* empty */ }
  1655. if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
  1656. if ('value' in Attributes) O[P] = Attributes.value;
  1657. return O;
  1658. };
  1659. /***/ }),
  1660. /***/ 4916:
  1661. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1662. var getBuiltIn = __webpack_require__(7751);
  1663. var createSetLike = function (size) {
  1664. return {
  1665. size: size,
  1666. has: function () {
  1667. return false;
  1668. },
  1669. keys: function () {
  1670. return {
  1671. next: function () {
  1672. return { done: true };
  1673. }
  1674. };
  1675. }
  1676. };
  1677. };
  1678. var createSetLikeWithInfinitySize = function (size) {
  1679. return {
  1680. size: size,
  1681. has: function () {
  1682. return true;
  1683. },
  1684. keys: function () {
  1685. throw new Error('e');
  1686. }
  1687. };
  1688. };
  1689. module.exports = function (name, callback) {
  1690. var Set = getBuiltIn('Set');
  1691. try {
  1692. new Set()[name](createSetLike(0));
  1693. try {
  1694. // late spec change, early WebKit ~ Safari 17 implementation does not pass it
  1695. // https://github.com/tc39/proposal-set-methods/pull/88
  1696. // also covered engines with
  1697. // https://bugs.webkit.org/show_bug.cgi?id=272679
  1698. new Set()[name](createSetLike(-1));
  1699. return false;
  1700. } catch (error2) {
  1701. if (!callback) return true;
  1702. // early V8 implementation bug
  1703. // https://issues.chromium.org/issues/351332634
  1704. try {
  1705. new Set()[name](createSetLikeWithInfinitySize(-Infinity));
  1706. return false;
  1707. } catch (error) {
  1708. var set = new Set();
  1709. set.add(1);
  1710. set.add(2);
  1711. return callback(set[name](createSetLikeWithInfinitySize(Infinity)));
  1712. }
  1713. }
  1714. } catch (error) {
  1715. return false;
  1716. }
  1717. };
  1718. /***/ }),
  1719. /***/ 4979:
  1720. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1721. var $ = __webpack_require__(6518);
  1722. var globalThis = __webpack_require__(4576);
  1723. var getBuiltIn = __webpack_require__(7751);
  1724. var createPropertyDescriptor = __webpack_require__(6980);
  1725. var defineProperty = (__webpack_require__(4913).f);
  1726. var hasOwn = __webpack_require__(9297);
  1727. var anInstance = __webpack_require__(679);
  1728. var inheritIfRequired = __webpack_require__(3167);
  1729. var normalizeStringArgument = __webpack_require__(2603);
  1730. var DOMExceptionConstants = __webpack_require__(5002);
  1731. var clearErrorStack = __webpack_require__(8574);
  1732. var DESCRIPTORS = __webpack_require__(3724);
  1733. var IS_PURE = __webpack_require__(6395);
  1734. var DOM_EXCEPTION = 'DOMException';
  1735. var Error = getBuiltIn('Error');
  1736. var NativeDOMException = getBuiltIn(DOM_EXCEPTION);
  1737. var $DOMException = function DOMException() {
  1738. anInstance(this, DOMExceptionPrototype);
  1739. var argumentsLength = arguments.length;
  1740. var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
  1741. var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
  1742. var that = new NativeDOMException(message, name);
  1743. var error = new Error(message);
  1744. error.name = DOM_EXCEPTION;
  1745. defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
  1746. inheritIfRequired(that, this, $DOMException);
  1747. return that;
  1748. };
  1749. var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;
  1750. var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
  1751. var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);
  1752. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  1753. var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION);
  1754. // Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it
  1755. // https://github.com/Jarred-Sumner/bun/issues/399
  1756. var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);
  1757. var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;
  1758. // `DOMException` constructor patch for `.stack` where it's required
  1759. // https://webidl.spec.whatwg.org/#es-DOMException-specialness
  1760. $({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic
  1761. DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
  1762. });
  1763. var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
  1764. var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
  1765. if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {
  1766. if (!IS_PURE) {
  1767. defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));
  1768. }
  1769. for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
  1770. var constant = DOMExceptionConstants[key];
  1771. var constantName = constant.s;
  1772. if (!hasOwn(PolyfilledDOMException, constantName)) {
  1773. defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));
  1774. }
  1775. }
  1776. }
  1777. /***/ }),
  1778. /***/ 5002:
  1779. /***/ ((module) => {
  1780. module.exports = {
  1781. IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },
  1782. DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },
  1783. HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },
  1784. WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },
  1785. InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },
  1786. NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },
  1787. NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },
  1788. NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },
  1789. NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },
  1790. InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },
  1791. InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },
  1792. SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },
  1793. InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },
  1794. NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },
  1795. InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },
  1796. ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },
  1797. TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },
  1798. SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },
  1799. NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },
  1800. AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },
  1801. URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },
  1802. QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },
  1803. TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
  1804. InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },
  1805. DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }
  1806. };
  1807. /***/ }),
  1808. /***/ 5024:
  1809. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1810. var $ = __webpack_require__(6518);
  1811. var symmetricDifference = __webpack_require__(3650);
  1812. var setMethodAcceptSetLike = __webpack_require__(4916);
  1813. // `Set.prototype.symmetricDifference` method
  1814. // https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
  1815. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
  1816. symmetricDifference: symmetricDifference
  1817. });
  1818. /***/ }),
  1819. /***/ 5031:
  1820. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1821. var getBuiltIn = __webpack_require__(7751);
  1822. var uncurryThis = __webpack_require__(9504);
  1823. var getOwnPropertyNamesModule = __webpack_require__(8480);
  1824. var getOwnPropertySymbolsModule = __webpack_require__(3717);
  1825. var anObject = __webpack_require__(8551);
  1826. var concat = uncurryThis([].concat);
  1827. // all object keys, includes non-enumerable and symbols
  1828. module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
  1829. var keys = getOwnPropertyNamesModule.f(anObject(it));
  1830. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  1831. return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
  1832. };
  1833. /***/ }),
  1834. /***/ 5169:
  1835. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1836. var isDetached = __webpack_require__(3238);
  1837. var $TypeError = TypeError;
  1838. module.exports = function (it) {
  1839. if (isDetached(it)) throw new $TypeError('ArrayBuffer is detached');
  1840. return it;
  1841. };
  1842. /***/ }),
  1843. /***/ 5170:
  1844. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1845. var uncurryThisAccessor = __webpack_require__(6706);
  1846. var SetHelpers = __webpack_require__(4402);
  1847. module.exports = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
  1848. return set.size;
  1849. };
  1850. /***/ }),
  1851. /***/ 5370:
  1852. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1853. var lengthOfArrayLike = __webpack_require__(6198);
  1854. module.exports = function (Constructor, list, $length) {
  1855. var index = 0;
  1856. var length = arguments.length > 2 ? $length : lengthOfArrayLike(list);
  1857. var result = new Constructor(length);
  1858. while (length > index) result[index] = list[index++];
  1859. return result;
  1860. };
  1861. /***/ }),
  1862. /***/ 5397:
  1863. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1864. // toObject with fallback for non-array-like ES3 strings
  1865. var IndexedObject = __webpack_require__(7055);
  1866. var requireObjectCoercible = __webpack_require__(7750);
  1867. module.exports = function (it) {
  1868. return IndexedObject(requireObjectCoercible(it));
  1869. };
  1870. /***/ }),
  1871. /***/ 5610:
  1872. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1873. var toIntegerOrInfinity = __webpack_require__(1291);
  1874. var max = Math.max;
  1875. var min = Math.min;
  1876. // Helper for a popular repeating case of the spec:
  1877. // Let integer be ? ToInteger(index).
  1878. // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
  1879. module.exports = function (index, length) {
  1880. var integer = toIntegerOrInfinity(index);
  1881. return integer < 0 ? max(integer + length, 0) : min(integer, length);
  1882. };
  1883. /***/ }),
  1884. /***/ 5623:
  1885. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1886. var $ = __webpack_require__(6518);
  1887. var globalThis = __webpack_require__(4576);
  1888. var uncurryThis = __webpack_require__(9504);
  1889. var anUint8Array = __webpack_require__(4154);
  1890. var notDetached = __webpack_require__(5169);
  1891. var numberToString = uncurryThis(1.0.toString);
  1892. // `Uint8Array.prototype.toHex` method
  1893. // https://github.com/tc39/proposal-arraybuffer-base64
  1894. if (globalThis.Uint8Array) $({ target: 'Uint8Array', proto: true }, {
  1895. toHex: function toHex() {
  1896. anUint8Array(this);
  1897. notDetached(this.buffer);
  1898. var result = '';
  1899. for (var i = 0, length = this.length; i < length; i++) {
  1900. var hex = numberToString(this[i], 16);
  1901. result += hex.length === 1 ? '0' + hex : hex;
  1902. }
  1903. return result;
  1904. }
  1905. });
  1906. /***/ }),
  1907. /***/ 5636:
  1908. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1909. var globalThis = __webpack_require__(4576);
  1910. var uncurryThis = __webpack_require__(9504);
  1911. var uncurryThisAccessor = __webpack_require__(6706);
  1912. var toIndex = __webpack_require__(7696);
  1913. var notDetached = __webpack_require__(5169);
  1914. var arrayBufferByteLength = __webpack_require__(7394);
  1915. var detachTransferable = __webpack_require__(4483);
  1916. var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);
  1917. var structuredClone = globalThis.structuredClone;
  1918. var ArrayBuffer = globalThis.ArrayBuffer;
  1919. var DataView = globalThis.DataView;
  1920. var min = Math.min;
  1921. var ArrayBufferPrototype = ArrayBuffer.prototype;
  1922. var DataViewPrototype = DataView.prototype;
  1923. var slice = uncurryThis(ArrayBufferPrototype.slice);
  1924. var isResizable = uncurryThisAccessor(ArrayBufferPrototype, 'resizable', 'get');
  1925. var maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, 'maxByteLength', 'get');
  1926. var getInt8 = uncurryThis(DataViewPrototype.getInt8);
  1927. var setInt8 = uncurryThis(DataViewPrototype.setInt8);
  1928. module.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) {
  1929. var byteLength = arrayBufferByteLength(arrayBuffer);
  1930. var newByteLength = newLength === undefined ? byteLength : toIndex(newLength);
  1931. var fixedLength = !isResizable || !isResizable(arrayBuffer);
  1932. var newBuffer;
  1933. notDetached(arrayBuffer);
  1934. if (PROPER_STRUCTURED_CLONE_TRANSFER) {
  1935. arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
  1936. if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer;
  1937. }
  1938. if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) {
  1939. newBuffer = slice(arrayBuffer, 0, newByteLength);
  1940. } else {
  1941. var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined;
  1942. newBuffer = new ArrayBuffer(newByteLength, options);
  1943. var a = new DataView(arrayBuffer);
  1944. var b = new DataView(newBuffer);
  1945. var copyLength = min(newByteLength, byteLength);
  1946. for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i));
  1947. }
  1948. if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer);
  1949. return newBuffer;
  1950. };
  1951. /***/ }),
  1952. /***/ 5745:
  1953. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1954. var store = __webpack_require__(7629);
  1955. module.exports = function (key, value) {
  1956. return store[key] || (store[key] = value || {});
  1957. };
  1958. /***/ }),
  1959. /***/ 5781:
  1960. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1961. var $ = __webpack_require__(6518);
  1962. var getBuiltIn = __webpack_require__(7751);
  1963. var validateArgumentsLength = __webpack_require__(2812);
  1964. var toString = __webpack_require__(655);
  1965. var USE_NATIVE_URL = __webpack_require__(7416);
  1966. var URL = getBuiltIn('URL');
  1967. // `URL.parse` method
  1968. // https://url.spec.whatwg.org/#dom-url-canparse
  1969. $({ target: 'URL', stat: true, forced: !USE_NATIVE_URL }, {
  1970. parse: function parse(url) {
  1971. var length = validateArgumentsLength(arguments.length, 1);
  1972. var urlString = toString(url);
  1973. var base = length < 2 || arguments[1] === undefined ? undefined : toString(arguments[1]);
  1974. try {
  1975. return new URL(urlString, base);
  1976. } catch (error) {
  1977. return null;
  1978. }
  1979. }
  1980. });
  1981. /***/ }),
  1982. /***/ 5876:
  1983. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  1984. var $ = __webpack_require__(6518);
  1985. var isSubsetOf = __webpack_require__(3838);
  1986. var setMethodAcceptSetLike = __webpack_require__(4916);
  1987. var INCORRECT = !setMethodAcceptSetLike('isSubsetOf', function (result) {
  1988. return result;
  1989. });
  1990. // `Set.prototype.isSubsetOf` method
  1991. // https://tc39.es/ecma262/#sec-set.prototype.issubsetof
  1992. $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
  1993. isSubsetOf: isSubsetOf
  1994. });
  1995. /***/ }),
  1996. /***/ 5917:
  1997. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1998. var DESCRIPTORS = __webpack_require__(3724);
  1999. var fails = __webpack_require__(9039);
  2000. var createElement = __webpack_require__(4055);
  2001. // Thanks to IE8 for its funny defineProperty
  2002. module.exports = !DESCRIPTORS && !fails(function () {
  2003. // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  2004. return Object.defineProperty(createElement('div'), 'a', {
  2005. get: function () { return 7; }
  2006. }).a !== 7;
  2007. });
  2008. /***/ }),
  2009. /***/ 5966:
  2010. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2011. var aCallable = __webpack_require__(9306);
  2012. var isNullOrUndefined = __webpack_require__(4117);
  2013. // `GetMethod` abstract operation
  2014. // https://tc39.es/ecma262/#sec-getmethod
  2015. module.exports = function (V, P) {
  2016. var func = V[P];
  2017. return isNullOrUndefined(func) ? undefined : aCallable(func);
  2018. };
  2019. /***/ }),
  2020. /***/ 6043:
  2021. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2022. var aCallable = __webpack_require__(9306);
  2023. var $TypeError = TypeError;
  2024. var PromiseCapability = function (C) {
  2025. var resolve, reject;
  2026. this.promise = new C(function ($$resolve, $$reject) {
  2027. if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor');
  2028. resolve = $$resolve;
  2029. reject = $$reject;
  2030. });
  2031. this.resolve = aCallable(resolve);
  2032. this.reject = aCallable(reject);
  2033. };
  2034. // `NewPromiseCapability` abstract operation
  2035. // https://tc39.es/ecma262/#sec-newpromisecapability
  2036. module.exports.f = function (C) {
  2037. return new PromiseCapability(C);
  2038. };
  2039. /***/ }),
  2040. /***/ 6080:
  2041. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2042. var uncurryThis = __webpack_require__(7476);
  2043. var aCallable = __webpack_require__(9306);
  2044. var NATIVE_BIND = __webpack_require__(616);
  2045. var bind = uncurryThis(uncurryThis.bind);
  2046. // optional / simple context binding
  2047. module.exports = function (fn, that) {
  2048. aCallable(fn);
  2049. return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
  2050. return fn.apply(that, arguments);
  2051. };
  2052. };
  2053. /***/ }),
  2054. /***/ 6119:
  2055. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2056. var shared = __webpack_require__(5745);
  2057. var uid = __webpack_require__(3392);
  2058. var keys = shared('keys');
  2059. module.exports = function (key) {
  2060. return keys[key] || (keys[key] = uid(key));
  2061. };
  2062. /***/ }),
  2063. /***/ 6193:
  2064. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2065. var ENVIRONMENT = __webpack_require__(4215);
  2066. module.exports = ENVIRONMENT === 'NODE';
  2067. /***/ }),
  2068. /***/ 6198:
  2069. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2070. var toLength = __webpack_require__(8014);
  2071. // `LengthOfArrayLike` abstract operation
  2072. // https://tc39.es/ecma262/#sec-lengthofarraylike
  2073. module.exports = function (obj) {
  2074. return toLength(obj.length);
  2075. };
  2076. /***/ }),
  2077. /***/ 6269:
  2078. /***/ ((module) => {
  2079. module.exports = {};
  2080. /***/ }),
  2081. /***/ 6279:
  2082. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2083. var defineBuiltIn = __webpack_require__(6840);
  2084. module.exports = function (target, src, options) {
  2085. for (var key in src) defineBuiltIn(target, key, src[key], options);
  2086. return target;
  2087. };
  2088. /***/ }),
  2089. /***/ 6319:
  2090. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2091. var anObject = __webpack_require__(8551);
  2092. var iteratorClose = __webpack_require__(9539);
  2093. // call something on iterator step with safe closing on error
  2094. module.exports = function (iterator, fn, value, ENTRIES) {
  2095. try {
  2096. return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
  2097. } catch (error) {
  2098. iteratorClose(iterator, 'throw', error);
  2099. }
  2100. };
  2101. /***/ }),
  2102. /***/ 6395:
  2103. /***/ ((module) => {
  2104. module.exports = false;
  2105. /***/ }),
  2106. /***/ 6518:
  2107. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2108. var globalThis = __webpack_require__(4576);
  2109. var getOwnPropertyDescriptor = (__webpack_require__(7347).f);
  2110. var createNonEnumerableProperty = __webpack_require__(6699);
  2111. var defineBuiltIn = __webpack_require__(6840);
  2112. var defineGlobalProperty = __webpack_require__(9433);
  2113. var copyConstructorProperties = __webpack_require__(7740);
  2114. var isForced = __webpack_require__(2796);
  2115. /*
  2116. options.target - name of the target object
  2117. options.global - target is the global object
  2118. options.stat - export as static methods of target
  2119. options.proto - export as prototype methods of target
  2120. options.real - real prototype method for the `pure` version
  2121. options.forced - export even if the native feature is available
  2122. options.bind - bind methods to the target, required for the `pure` version
  2123. options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
  2124. options.unsafe - use the simple assignment of property instead of delete + defineProperty
  2125. options.sham - add a flag to not completely full polyfills
  2126. options.enumerable - export as enumerable property
  2127. options.dontCallGetSet - prevent calling a getter on target
  2128. options.name - the .name of the function if it does not match the key
  2129. */
  2130. module.exports = function (options, source) {
  2131. var TARGET = options.target;
  2132. var GLOBAL = options.global;
  2133. var STATIC = options.stat;
  2134. var FORCED, target, key, targetProperty, sourceProperty, descriptor;
  2135. if (GLOBAL) {
  2136. target = globalThis;
  2137. } else if (STATIC) {
  2138. target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
  2139. } else {
  2140. target = globalThis[TARGET] && globalThis[TARGET].prototype;
  2141. }
  2142. if (target) for (key in source) {
  2143. sourceProperty = source[key];
  2144. if (options.dontCallGetSet) {
  2145. descriptor = getOwnPropertyDescriptor(target, key);
  2146. targetProperty = descriptor && descriptor.value;
  2147. } else targetProperty = target[key];
  2148. FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
  2149. // contained in target
  2150. if (!FORCED && targetProperty !== undefined) {
  2151. if (typeof sourceProperty == typeof targetProperty) continue;
  2152. copyConstructorProperties(sourceProperty, targetProperty);
  2153. }
  2154. // add a flag to not completely full polyfills
  2155. if (options.sham || (targetProperty && targetProperty.sham)) {
  2156. createNonEnumerableProperty(sourceProperty, 'sham', true);
  2157. }
  2158. defineBuiltIn(target, key, sourceProperty, options);
  2159. }
  2160. };
  2161. /***/ }),
  2162. /***/ 6573:
  2163. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2164. var DESCRIPTORS = __webpack_require__(3724);
  2165. var defineBuiltInAccessor = __webpack_require__(2106);
  2166. var isDetached = __webpack_require__(3238);
  2167. var ArrayBufferPrototype = ArrayBuffer.prototype;
  2168. // `ArrayBuffer.prototype.detached` getter
  2169. // https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.detached
  2170. if (DESCRIPTORS && !('detached' in ArrayBufferPrototype)) {
  2171. defineBuiltInAccessor(ArrayBufferPrototype, 'detached', {
  2172. configurable: true,
  2173. get: function detached() {
  2174. return isDetached(this);
  2175. }
  2176. });
  2177. }
  2178. /***/ }),
  2179. /***/ 6699:
  2180. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2181. var DESCRIPTORS = __webpack_require__(3724);
  2182. var definePropertyModule = __webpack_require__(4913);
  2183. var createPropertyDescriptor = __webpack_require__(6980);
  2184. module.exports = DESCRIPTORS ? function (object, key, value) {
  2185. return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
  2186. } : function (object, key, value) {
  2187. object[key] = value;
  2188. return object;
  2189. };
  2190. /***/ }),
  2191. /***/ 6706:
  2192. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2193. var uncurryThis = __webpack_require__(9504);
  2194. var aCallable = __webpack_require__(9306);
  2195. module.exports = function (object, key, method) {
  2196. try {
  2197. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  2198. return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
  2199. } catch (error) { /* empty */ }
  2200. };
  2201. /***/ }),
  2202. /***/ 6801:
  2203. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2204. var DESCRIPTORS = __webpack_require__(3724);
  2205. var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);
  2206. var definePropertyModule = __webpack_require__(4913);
  2207. var anObject = __webpack_require__(8551);
  2208. var toIndexedObject = __webpack_require__(5397);
  2209. var objectKeys = __webpack_require__(1072);
  2210. // `Object.defineProperties` method
  2211. // https://tc39.es/ecma262/#sec-object.defineproperties
  2212. // eslint-disable-next-line es/no-object-defineproperties -- safe
  2213. exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
  2214. anObject(O);
  2215. var props = toIndexedObject(Properties);
  2216. var keys = objectKeys(Properties);
  2217. var length = keys.length;
  2218. var index = 0;
  2219. var key;
  2220. while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
  2221. return O;
  2222. };
  2223. /***/ }),
  2224. /***/ 6823:
  2225. /***/ ((module) => {
  2226. var $String = String;
  2227. module.exports = function (argument) {
  2228. try {
  2229. return $String(argument);
  2230. } catch (error) {
  2231. return 'Object';
  2232. }
  2233. };
  2234. /***/ }),
  2235. /***/ 6837:
  2236. /***/ ((module) => {
  2237. var $TypeError = TypeError;
  2238. var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
  2239. module.exports = function (it) {
  2240. if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
  2241. return it;
  2242. };
  2243. /***/ }),
  2244. /***/ 6840:
  2245. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2246. var isCallable = __webpack_require__(4901);
  2247. var definePropertyModule = __webpack_require__(4913);
  2248. var makeBuiltIn = __webpack_require__(283);
  2249. var defineGlobalProperty = __webpack_require__(9433);
  2250. module.exports = function (O, key, value, options) {
  2251. if (!options) options = {};
  2252. var simple = options.enumerable;
  2253. var name = options.name !== undefined ? options.name : key;
  2254. if (isCallable(value)) makeBuiltIn(value, name, options);
  2255. if (options.global) {
  2256. if (simple) O[key] = value;
  2257. else defineGlobalProperty(key, value);
  2258. } else {
  2259. try {
  2260. if (!options.unsafe) delete O[key];
  2261. else if (O[key]) simple = true;
  2262. } catch (error) { /* empty */ }
  2263. if (simple) O[key] = value;
  2264. else definePropertyModule.f(O, key, {
  2265. value: value,
  2266. enumerable: false,
  2267. configurable: !options.nonConfigurable,
  2268. writable: !options.nonWritable
  2269. });
  2270. } return O;
  2271. };
  2272. /***/ }),
  2273. /***/ 6955:
  2274. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2275. var TO_STRING_TAG_SUPPORT = __webpack_require__(2140);
  2276. var isCallable = __webpack_require__(4901);
  2277. var classofRaw = __webpack_require__(2195);
  2278. var wellKnownSymbol = __webpack_require__(8227);
  2279. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  2280. var $Object = Object;
  2281. // ES3 wrong here
  2282. var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
  2283. // fallback for IE11 Script Access Denied error
  2284. var tryGet = function (it, key) {
  2285. try {
  2286. return it[key];
  2287. } catch (error) { /* empty */ }
  2288. };
  2289. // getting tag from ES6+ `Object.prototype.toString`
  2290. module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
  2291. var O, tag, result;
  2292. return it === undefined ? 'Undefined' : it === null ? 'Null'
  2293. // @@toStringTag case
  2294. : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
  2295. // builtinTag case
  2296. : CORRECT_ARGUMENTS ? classofRaw(O)
  2297. // ES3 arguments fallback
  2298. : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
  2299. };
  2300. /***/ }),
  2301. /***/ 6969:
  2302. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2303. var toPrimitive = __webpack_require__(2777);
  2304. var isSymbol = __webpack_require__(757);
  2305. // `ToPropertyKey` abstract operation
  2306. // https://tc39.es/ecma262/#sec-topropertykey
  2307. module.exports = function (argument) {
  2308. var key = toPrimitive(argument, 'string');
  2309. return isSymbol(key) ? key : key + '';
  2310. };
  2311. /***/ }),
  2312. /***/ 6980:
  2313. /***/ ((module) => {
  2314. module.exports = function (bitmap, value) {
  2315. return {
  2316. enumerable: !(bitmap & 1),
  2317. configurable: !(bitmap & 2),
  2318. writable: !(bitmap & 4),
  2319. value: value
  2320. };
  2321. };
  2322. /***/ }),
  2323. /***/ 7040:
  2324. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2325. /* eslint-disable es/no-symbol -- required for testing */
  2326. var NATIVE_SYMBOL = __webpack_require__(4495);
  2327. module.exports = NATIVE_SYMBOL &&
  2328. !Symbol.sham &&
  2329. typeof Symbol.iterator == 'symbol';
  2330. /***/ }),
  2331. /***/ 7055:
  2332. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2333. var uncurryThis = __webpack_require__(9504);
  2334. var fails = __webpack_require__(9039);
  2335. var classof = __webpack_require__(2195);
  2336. var $Object = Object;
  2337. var split = uncurryThis(''.split);
  2338. // fallback for non-array-like ES3 and non-enumerable old V8 strings
  2339. module.exports = fails(function () {
  2340. // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
  2341. // eslint-disable-next-line no-prototype-builtins -- safe
  2342. return !$Object('z').propertyIsEnumerable(0);
  2343. }) ? function (it) {
  2344. return classof(it) === 'String' ? split(it, '') : $Object(it);
  2345. } : $Object;
  2346. /***/ }),
  2347. /***/ 7080:
  2348. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2349. var has = (__webpack_require__(4402).has);
  2350. // Perform ? RequireInternalSlot(M, [[SetData]])
  2351. module.exports = function (it) {
  2352. has(it);
  2353. return it;
  2354. };
  2355. /***/ }),
  2356. /***/ 7347:
  2357. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2358. var DESCRIPTORS = __webpack_require__(3724);
  2359. var call = __webpack_require__(9565);
  2360. var propertyIsEnumerableModule = __webpack_require__(8773);
  2361. var createPropertyDescriptor = __webpack_require__(6980);
  2362. var toIndexedObject = __webpack_require__(5397);
  2363. var toPropertyKey = __webpack_require__(6969);
  2364. var hasOwn = __webpack_require__(9297);
  2365. var IE8_DOM_DEFINE = __webpack_require__(5917);
  2366. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  2367. var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  2368. // `Object.getOwnPropertyDescriptor` method
  2369. // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
  2370. exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
  2371. O = toIndexedObject(O);
  2372. P = toPropertyKey(P);
  2373. if (IE8_DOM_DEFINE) try {
  2374. return $getOwnPropertyDescriptor(O, P);
  2375. } catch (error) { /* empty */ }
  2376. if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
  2377. };
  2378. /***/ }),
  2379. /***/ 7394:
  2380. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2381. var globalThis = __webpack_require__(4576);
  2382. var uncurryThisAccessor = __webpack_require__(6706);
  2383. var classof = __webpack_require__(2195);
  2384. var ArrayBuffer = globalThis.ArrayBuffer;
  2385. var TypeError = globalThis.TypeError;
  2386. // Includes
  2387. // - Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).
  2388. // - If IsSharedArrayBuffer(O) is true, throw a TypeError exception.
  2389. module.exports = ArrayBuffer && uncurryThisAccessor(ArrayBuffer.prototype, 'byteLength', 'get') || function (O) {
  2390. if (classof(O) !== 'ArrayBuffer') throw new TypeError('ArrayBuffer expected');
  2391. return O.byteLength;
  2392. };
  2393. /***/ }),
  2394. /***/ 7416:
  2395. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2396. var fails = __webpack_require__(9039);
  2397. var wellKnownSymbol = __webpack_require__(8227);
  2398. var DESCRIPTORS = __webpack_require__(3724);
  2399. var IS_PURE = __webpack_require__(6395);
  2400. var ITERATOR = wellKnownSymbol('iterator');
  2401. module.exports = !fails(function () {
  2402. // eslint-disable-next-line unicorn/relative-url-style -- required for testing
  2403. var url = new URL('b?a=1&b=2&c=3', 'https://a');
  2404. var params = url.searchParams;
  2405. var params2 = new URLSearchParams('a=1&a=2&b=3');
  2406. var result = '';
  2407. url.pathname = 'c%20d';
  2408. params.forEach(function (value, key) {
  2409. params['delete']('b');
  2410. result += key + value;
  2411. });
  2412. params2['delete']('a', 2);
  2413. // `undefined` case is a Chromium 117 bug
  2414. // https://bugs.chromium.org/p/v8/issues/detail?id=14222
  2415. params2['delete']('b', undefined);
  2416. return (IS_PURE && (!url.toJSON || !params2.has('a', 1) || params2.has('a', 2) || !params2.has('a', undefined) || params2.has('b')))
  2417. || (!params.size && (IS_PURE || !DESCRIPTORS))
  2418. || !params.sort
  2419. || url.href !== 'https://a/c%20d?a=1&c=3'
  2420. || params.get('c') !== '3'
  2421. || String(new URLSearchParams('?a=1')) !== 'a=1'
  2422. || !params[ITERATOR]
  2423. // throws in Edge
  2424. || new URL('https://a@b').username !== 'a'
  2425. || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b'
  2426. // not punycoded in Edge
  2427. || new URL('https://тест').host !== 'xn--e1aybc'
  2428. // not escaped in Chrome 62-
  2429. || new URL('https://a#б').hash !== '#%D0%B1'
  2430. // fails in Chrome 66-
  2431. || result !== 'a1c3'
  2432. // throws in Safari
  2433. || new URL('https://x', undefined).host !== 'x';
  2434. });
  2435. /***/ }),
  2436. /***/ 7476:
  2437. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2438. var classofRaw = __webpack_require__(2195);
  2439. var uncurryThis = __webpack_require__(9504);
  2440. module.exports = function (fn) {
  2441. // Nashorn bug:
  2442. // https://github.com/zloirock/core-js/issues/1128
  2443. // https://github.com/zloirock/core-js/issues/1130
  2444. if (classofRaw(fn) === 'Function') return uncurryThis(fn);
  2445. };
  2446. /***/ }),
  2447. /***/ 7566:
  2448. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2449. var defineBuiltIn = __webpack_require__(6840);
  2450. var uncurryThis = __webpack_require__(9504);
  2451. var toString = __webpack_require__(655);
  2452. var validateArgumentsLength = __webpack_require__(2812);
  2453. var $URLSearchParams = URLSearchParams;
  2454. var URLSearchParamsPrototype = $URLSearchParams.prototype;
  2455. var getAll = uncurryThis(URLSearchParamsPrototype.getAll);
  2456. var $has = uncurryThis(URLSearchParamsPrototype.has);
  2457. var params = new $URLSearchParams('a=1');
  2458. // `undefined` case is a Chromium 117 bug
  2459. // https://bugs.chromium.org/p/v8/issues/detail?id=14222
  2460. if (params.has('a', 2) || !params.has('a', undefined)) {
  2461. defineBuiltIn(URLSearchParamsPrototype, 'has', function has(name /* , value */) {
  2462. var length = arguments.length;
  2463. var $value = length < 2 ? undefined : arguments[1];
  2464. if (length && $value === undefined) return $has(this, name);
  2465. var values = getAll(this, name); // also validates `this`
  2466. validateArgumentsLength(length, 1);
  2467. var value = toString($value);
  2468. var index = 0;
  2469. while (index < values.length) {
  2470. if (values[index++] === value) return true;
  2471. } return false;
  2472. }, { enumerable: true, unsafe: true });
  2473. }
  2474. /***/ }),
  2475. /***/ 7629:
  2476. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2477. var IS_PURE = __webpack_require__(6395);
  2478. var globalThis = __webpack_require__(4576);
  2479. var defineGlobalProperty = __webpack_require__(9433);
  2480. var SHARED = '__core-js_shared__';
  2481. var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
  2482. (store.versions || (store.versions = [])).push({
  2483. version: '3.42.0',
  2484. mode: IS_PURE ? 'pure' : 'global',
  2485. copyright: '© 2014-2025 Denis Pushkarev (zloirock.ru)',
  2486. license: 'https://github.com/zloirock/core-js/blob/v3.42.0/LICENSE',
  2487. source: 'https://github.com/zloirock/core-js'
  2488. });
  2489. /***/ }),
  2490. /***/ 7642:
  2491. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2492. var $ = __webpack_require__(6518);
  2493. var difference = __webpack_require__(3440);
  2494. var setMethodAcceptSetLike = __webpack_require__(4916);
  2495. var INCORRECT = !setMethodAcceptSetLike('difference', function (result) {
  2496. return result.size === 0;
  2497. });
  2498. // `Set.prototype.difference` method
  2499. // https://tc39.es/ecma262/#sec-set.prototype.difference
  2500. $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
  2501. difference: difference
  2502. });
  2503. /***/ }),
  2504. /***/ 7657:
  2505. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2506. var fails = __webpack_require__(9039);
  2507. var isCallable = __webpack_require__(4901);
  2508. var isObject = __webpack_require__(34);
  2509. var create = __webpack_require__(2360);
  2510. var getPrototypeOf = __webpack_require__(2787);
  2511. var defineBuiltIn = __webpack_require__(6840);
  2512. var wellKnownSymbol = __webpack_require__(8227);
  2513. var IS_PURE = __webpack_require__(6395);
  2514. var ITERATOR = wellKnownSymbol('iterator');
  2515. var BUGGY_SAFARI_ITERATORS = false;
  2516. // `%IteratorPrototype%` object
  2517. // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
  2518. var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
  2519. /* eslint-disable es/no-array-prototype-keys -- safe */
  2520. if ([].keys) {
  2521. arrayIterator = [].keys();
  2522. // Safari 8 has buggy iterators w/o `next`
  2523. if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
  2524. else {
  2525. PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
  2526. if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
  2527. }
  2528. }
  2529. var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
  2530. var test = {};
  2531. // FF44- legacy iterators case
  2532. return IteratorPrototype[ITERATOR].call(test) !== test;
  2533. });
  2534. if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
  2535. else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
  2536. // `%IteratorPrototype%[@@iterator]()` method
  2537. // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
  2538. if (!isCallable(IteratorPrototype[ITERATOR])) {
  2539. defineBuiltIn(IteratorPrototype, ITERATOR, function () {
  2540. return this;
  2541. });
  2542. }
  2543. module.exports = {
  2544. IteratorPrototype: IteratorPrototype,
  2545. BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
  2546. };
  2547. /***/ }),
  2548. /***/ 7680:
  2549. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2550. var uncurryThis = __webpack_require__(9504);
  2551. module.exports = uncurryThis([].slice);
  2552. /***/ }),
  2553. /***/ 7696:
  2554. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2555. var toIntegerOrInfinity = __webpack_require__(1291);
  2556. var toLength = __webpack_require__(8014);
  2557. var $RangeError = RangeError;
  2558. // `ToIndex` abstract operation
  2559. // https://tc39.es/ecma262/#sec-toindex
  2560. module.exports = function (it) {
  2561. if (it === undefined) return 0;
  2562. var number = toIntegerOrInfinity(it);
  2563. var length = toLength(number);
  2564. if (number !== length) throw new $RangeError('Wrong length or index');
  2565. return length;
  2566. };
  2567. /***/ }),
  2568. /***/ 7740:
  2569. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2570. var hasOwn = __webpack_require__(9297);
  2571. var ownKeys = __webpack_require__(5031);
  2572. var getOwnPropertyDescriptorModule = __webpack_require__(7347);
  2573. var definePropertyModule = __webpack_require__(4913);
  2574. module.exports = function (target, source, exceptions) {
  2575. var keys = ownKeys(source);
  2576. var defineProperty = definePropertyModule.f;
  2577. var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  2578. for (var i = 0; i < keys.length; i++) {
  2579. var key = keys[i];
  2580. if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
  2581. defineProperty(target, key, getOwnPropertyDescriptor(source, key));
  2582. }
  2583. }
  2584. };
  2585. /***/ }),
  2586. /***/ 7750:
  2587. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2588. var isNullOrUndefined = __webpack_require__(4117);
  2589. var $TypeError = TypeError;
  2590. // `RequireObjectCoercible` abstract operation
  2591. // https://tc39.es/ecma262/#sec-requireobjectcoercible
  2592. module.exports = function (it) {
  2593. if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
  2594. return it;
  2595. };
  2596. /***/ }),
  2597. /***/ 7751:
  2598. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2599. var globalThis = __webpack_require__(4576);
  2600. var isCallable = __webpack_require__(4901);
  2601. var aFunction = function (argument) {
  2602. return isCallable(argument) ? argument : undefined;
  2603. };
  2604. module.exports = function (namespace, method) {
  2605. return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
  2606. };
  2607. /***/ }),
  2608. /***/ 7811:
  2609. /***/ ((module) => {
  2610. // eslint-disable-next-line es/no-typed-arrays -- safe
  2611. module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined';
  2612. /***/ }),
  2613. /***/ 7936:
  2614. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2615. var $ = __webpack_require__(6518);
  2616. var $transfer = __webpack_require__(5636);
  2617. // `ArrayBuffer.prototype.transferToFixedLength` method
  2618. // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength
  2619. if ($transfer) $({ target: 'ArrayBuffer', proto: true }, {
  2620. transferToFixedLength: function transferToFixedLength() {
  2621. return $transfer(this, arguments.length ? arguments[0] : undefined, false);
  2622. }
  2623. });
  2624. /***/ }),
  2625. /***/ 8004:
  2626. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2627. var $ = __webpack_require__(6518);
  2628. var fails = __webpack_require__(9039);
  2629. var intersection = __webpack_require__(8750);
  2630. var setMethodAcceptSetLike = __webpack_require__(4916);
  2631. var INCORRECT = !setMethodAcceptSetLike('intersection', function (result) {
  2632. return result.size === 2 && result.has(1) && result.has(2);
  2633. }) || fails(function () {
  2634. // eslint-disable-next-line es/no-array-from, es/no-set, es/no-set-prototype-intersection -- testing
  2635. return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
  2636. });
  2637. // `Set.prototype.intersection` method
  2638. // https://tc39.es/ecma262/#sec-set.prototype.intersection
  2639. $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
  2640. intersection: intersection
  2641. });
  2642. /***/ }),
  2643. /***/ 8014:
  2644. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2645. var toIntegerOrInfinity = __webpack_require__(1291);
  2646. var min = Math.min;
  2647. // `ToLength` abstract operation
  2648. // https://tc39.es/ecma262/#sec-tolength
  2649. module.exports = function (argument) {
  2650. var len = toIntegerOrInfinity(argument);
  2651. return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
  2652. };
  2653. /***/ }),
  2654. /***/ 8100:
  2655. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2656. var $ = __webpack_require__(6518);
  2657. var $transfer = __webpack_require__(5636);
  2658. // `ArrayBuffer.prototype.transfer` method
  2659. // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfer
  2660. if ($transfer) $({ target: 'ArrayBuffer', proto: true }, {
  2661. transfer: function transfer() {
  2662. return $transfer(this, arguments.length ? arguments[0] : undefined, true);
  2663. }
  2664. });
  2665. /***/ }),
  2666. /***/ 8111:
  2667. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2668. var $ = __webpack_require__(6518);
  2669. var globalThis = __webpack_require__(4576);
  2670. var anInstance = __webpack_require__(679);
  2671. var anObject = __webpack_require__(8551);
  2672. var isCallable = __webpack_require__(4901);
  2673. var getPrototypeOf = __webpack_require__(2787);
  2674. var defineBuiltInAccessor = __webpack_require__(2106);
  2675. var createProperty = __webpack_require__(4659);
  2676. var fails = __webpack_require__(9039);
  2677. var hasOwn = __webpack_require__(9297);
  2678. var wellKnownSymbol = __webpack_require__(8227);
  2679. var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);
  2680. var DESCRIPTORS = __webpack_require__(3724);
  2681. var IS_PURE = __webpack_require__(6395);
  2682. var CONSTRUCTOR = 'constructor';
  2683. var ITERATOR = 'Iterator';
  2684. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  2685. var $TypeError = TypeError;
  2686. var NativeIterator = globalThis[ITERATOR];
  2687. // FF56- have non-standard global helper `Iterator`
  2688. var FORCED = IS_PURE
  2689. || !isCallable(NativeIterator)
  2690. || NativeIterator.prototype !== IteratorPrototype
  2691. // FF44- non-standard `Iterator` passes previous tests
  2692. || !fails(function () { NativeIterator({}); });
  2693. var IteratorConstructor = function Iterator() {
  2694. anInstance(this, IteratorPrototype);
  2695. if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
  2696. };
  2697. var defineIteratorPrototypeAccessor = function (key, value) {
  2698. if (DESCRIPTORS) {
  2699. defineBuiltInAccessor(IteratorPrototype, key, {
  2700. configurable: true,
  2701. get: function () {
  2702. return value;
  2703. },
  2704. set: function (replacement) {
  2705. anObject(this);
  2706. if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
  2707. if (hasOwn(this, key)) this[key] = replacement;
  2708. else createProperty(this, key, replacement);
  2709. }
  2710. });
  2711. } else IteratorPrototype[key] = value;
  2712. };
  2713. if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
  2714. if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
  2715. defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
  2716. }
  2717. IteratorConstructor.prototype = IteratorPrototype;
  2718. // `Iterator` constructor
  2719. // https://tc39.es/ecma262/#sec-iterator
  2720. $({ global: true, constructor: true, forced: FORCED }, {
  2721. Iterator: IteratorConstructor
  2722. });
  2723. /***/ }),
  2724. /***/ 8227:
  2725. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2726. var globalThis = __webpack_require__(4576);
  2727. var shared = __webpack_require__(5745);
  2728. var hasOwn = __webpack_require__(9297);
  2729. var uid = __webpack_require__(3392);
  2730. var NATIVE_SYMBOL = __webpack_require__(4495);
  2731. var USE_SYMBOL_AS_UID = __webpack_require__(7040);
  2732. var Symbol = globalThis.Symbol;
  2733. var WellKnownSymbolsStore = shared('wks');
  2734. var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
  2735. module.exports = function (name) {
  2736. if (!hasOwn(WellKnownSymbolsStore, name)) {
  2737. WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
  2738. ? Symbol[name]
  2739. : createWellKnownSymbol('Symbol.' + name);
  2740. } return WellKnownSymbolsStore[name];
  2741. };
  2742. /***/ }),
  2743. /***/ 8235:
  2744. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2745. var uncurryThis = __webpack_require__(9504);
  2746. var hasOwn = __webpack_require__(9297);
  2747. var $SyntaxError = SyntaxError;
  2748. var $parseInt = parseInt;
  2749. var fromCharCode = String.fromCharCode;
  2750. var at = uncurryThis(''.charAt);
  2751. var slice = uncurryThis(''.slice);
  2752. var exec = uncurryThis(/./.exec);
  2753. var codePoints = {
  2754. '\\"': '"',
  2755. '\\\\': '\\',
  2756. '\\/': '/',
  2757. '\\b': '\b',
  2758. '\\f': '\f',
  2759. '\\n': '\n',
  2760. '\\r': '\r',
  2761. '\\t': '\t'
  2762. };
  2763. var IS_4_HEX_DIGITS = /^[\da-f]{4}$/i;
  2764. // eslint-disable-next-line regexp/no-control-character -- safe
  2765. var IS_C0_CONTROL_CODE = /^[\u0000-\u001F]$/;
  2766. module.exports = function (source, i) {
  2767. var unterminated = true;
  2768. var value = '';
  2769. while (i < source.length) {
  2770. var chr = at(source, i);
  2771. if (chr === '\\') {
  2772. var twoChars = slice(source, i, i + 2);
  2773. if (hasOwn(codePoints, twoChars)) {
  2774. value += codePoints[twoChars];
  2775. i += 2;
  2776. } else if (twoChars === '\\u') {
  2777. i += 2;
  2778. var fourHexDigits = slice(source, i, i + 4);
  2779. if (!exec(IS_4_HEX_DIGITS, fourHexDigits)) throw new $SyntaxError('Bad Unicode escape at: ' + i);
  2780. value += fromCharCode($parseInt(fourHexDigits, 16));
  2781. i += 4;
  2782. } else throw new $SyntaxError('Unknown escape sequence: "' + twoChars + '"');
  2783. } else if (chr === '"') {
  2784. unterminated = false;
  2785. i++;
  2786. break;
  2787. } else {
  2788. if (exec(IS_C0_CONTROL_CODE, chr)) throw new $SyntaxError('Bad control character in string literal at: ' + i);
  2789. value += chr;
  2790. i++;
  2791. }
  2792. }
  2793. if (unterminated) throw new $SyntaxError('Unterminated string at: ' + i);
  2794. return { value: value, end: i };
  2795. };
  2796. /***/ }),
  2797. /***/ 8237:
  2798. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2799. var $ = __webpack_require__(6518);
  2800. var iterate = __webpack_require__(2652);
  2801. var aCallable = __webpack_require__(9306);
  2802. var anObject = __webpack_require__(8551);
  2803. var getIteratorDirect = __webpack_require__(1767);
  2804. var iteratorClose = __webpack_require__(9539);
  2805. var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);
  2806. var apply = __webpack_require__(8745);
  2807. var fails = __webpack_require__(9039);
  2808. var $TypeError = TypeError;
  2809. // https://bugs.webkit.org/show_bug.cgi?id=291651
  2810. var FAILS_ON_INITIAL_UNDEFINED = fails(function () {
  2811. // eslint-disable-next-line es/no-iterator-prototype-reduce, es/no-array-prototype-keys, array-callback-return -- required for testing
  2812. [].keys().reduce(function () { /* empty */ }, undefined);
  2813. });
  2814. var reduceWithoutClosingOnEarlyError = !FAILS_ON_INITIAL_UNDEFINED && iteratorHelperWithoutClosingOnEarlyError('reduce', $TypeError);
  2815. // `Iterator.prototype.reduce` method
  2816. // https://tc39.es/ecma262/#sec-iterator.prototype.reduce
  2817. $({ target: 'Iterator', proto: true, real: true, forced: FAILS_ON_INITIAL_UNDEFINED || reduceWithoutClosingOnEarlyError }, {
  2818. reduce: function reduce(reducer /* , initialValue */) {
  2819. anObject(this);
  2820. try {
  2821. aCallable(reducer);
  2822. } catch (error) {
  2823. iteratorClose(this, 'throw', error);
  2824. }
  2825. var noInitial = arguments.length < 2;
  2826. var accumulator = noInitial ? undefined : arguments[1];
  2827. if (reduceWithoutClosingOnEarlyError) {
  2828. return apply(reduceWithoutClosingOnEarlyError, this, noInitial ? [reducer] : [reducer, accumulator]);
  2829. }
  2830. var record = getIteratorDirect(this);
  2831. var counter = 0;
  2832. iterate(record, function (value) {
  2833. if (noInitial) {
  2834. noInitial = false;
  2835. accumulator = value;
  2836. } else {
  2837. accumulator = reducer(accumulator, value, counter);
  2838. }
  2839. counter++;
  2840. }, { IS_RECORD: true });
  2841. if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
  2842. return accumulator;
  2843. }
  2844. });
  2845. /***/ }),
  2846. /***/ 8335:
  2847. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2848. var $ = __webpack_require__(6518);
  2849. var DESCRIPTORS = __webpack_require__(3724);
  2850. var globalThis = __webpack_require__(4576);
  2851. var getBuiltIn = __webpack_require__(7751);
  2852. var uncurryThis = __webpack_require__(9504);
  2853. var call = __webpack_require__(9565);
  2854. var isCallable = __webpack_require__(4901);
  2855. var isObject = __webpack_require__(34);
  2856. var isArray = __webpack_require__(4376);
  2857. var hasOwn = __webpack_require__(9297);
  2858. var toString = __webpack_require__(655);
  2859. var lengthOfArrayLike = __webpack_require__(6198);
  2860. var createProperty = __webpack_require__(4659);
  2861. var fails = __webpack_require__(9039);
  2862. var parseJSONString = __webpack_require__(8235);
  2863. var NATIVE_SYMBOL = __webpack_require__(4495);
  2864. var JSON = globalThis.JSON;
  2865. var Number = globalThis.Number;
  2866. var SyntaxError = globalThis.SyntaxError;
  2867. var nativeParse = JSON && JSON.parse;
  2868. var enumerableOwnProperties = getBuiltIn('Object', 'keys');
  2869. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  2870. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  2871. var at = uncurryThis(''.charAt);
  2872. var slice = uncurryThis(''.slice);
  2873. var exec = uncurryThis(/./.exec);
  2874. var push = uncurryThis([].push);
  2875. var IS_DIGIT = /^\d$/;
  2876. var IS_NON_ZERO_DIGIT = /^[1-9]$/;
  2877. var IS_NUMBER_START = /^[\d-]$/;
  2878. var IS_WHITESPACE = /^[\t\n\r ]$/;
  2879. var PRIMITIVE = 0;
  2880. var OBJECT = 1;
  2881. var $parse = function (source, reviver) {
  2882. source = toString(source);
  2883. var context = new Context(source, 0, '');
  2884. var root = context.parse();
  2885. var value = root.value;
  2886. var endIndex = context.skip(IS_WHITESPACE, root.end);
  2887. if (endIndex < source.length) {
  2888. throw new SyntaxError('Unexpected extra character: "' + at(source, endIndex) + '" after the parsed data at: ' + endIndex);
  2889. }
  2890. return isCallable(reviver) ? internalize({ '': value }, '', reviver, root) : value;
  2891. };
  2892. var internalize = function (holder, name, reviver, node) {
  2893. var val = holder[name];
  2894. var unmodified = node && val === node.value;
  2895. var context = unmodified && typeof node.source == 'string' ? { source: node.source } : {};
  2896. var elementRecordsLen, keys, len, i, P;
  2897. if (isObject(val)) {
  2898. var nodeIsArray = isArray(val);
  2899. var nodes = unmodified ? node.nodes : nodeIsArray ? [] : {};
  2900. if (nodeIsArray) {
  2901. elementRecordsLen = nodes.length;
  2902. len = lengthOfArrayLike(val);
  2903. for (i = 0; i < len; i++) {
  2904. internalizeProperty(val, i, internalize(val, '' + i, reviver, i < elementRecordsLen ? nodes[i] : undefined));
  2905. }
  2906. } else {
  2907. keys = enumerableOwnProperties(val);
  2908. len = lengthOfArrayLike(keys);
  2909. for (i = 0; i < len; i++) {
  2910. P = keys[i];
  2911. internalizeProperty(val, P, internalize(val, P, reviver, hasOwn(nodes, P) ? nodes[P] : undefined));
  2912. }
  2913. }
  2914. }
  2915. return call(reviver, holder, name, val, context);
  2916. };
  2917. var internalizeProperty = function (object, key, value) {
  2918. if (DESCRIPTORS) {
  2919. var descriptor = getOwnPropertyDescriptor(object, key);
  2920. if (descriptor && !descriptor.configurable) return;
  2921. }
  2922. if (value === undefined) delete object[key];
  2923. else createProperty(object, key, value);
  2924. };
  2925. var Node = function (value, end, source, nodes) {
  2926. this.value = value;
  2927. this.end = end;
  2928. this.source = source;
  2929. this.nodes = nodes;
  2930. };
  2931. var Context = function (source, index) {
  2932. this.source = source;
  2933. this.index = index;
  2934. };
  2935. // https://www.json.org/json-en.html
  2936. Context.prototype = {
  2937. fork: function (nextIndex) {
  2938. return new Context(this.source, nextIndex);
  2939. },
  2940. parse: function () {
  2941. var source = this.source;
  2942. var i = this.skip(IS_WHITESPACE, this.index);
  2943. var fork = this.fork(i);
  2944. var chr = at(source, i);
  2945. if (exec(IS_NUMBER_START, chr)) return fork.number();
  2946. switch (chr) {
  2947. case '{':
  2948. return fork.object();
  2949. case '[':
  2950. return fork.array();
  2951. case '"':
  2952. return fork.string();
  2953. case 't':
  2954. return fork.keyword(true);
  2955. case 'f':
  2956. return fork.keyword(false);
  2957. case 'n':
  2958. return fork.keyword(null);
  2959. } throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i);
  2960. },
  2961. node: function (type, value, start, end, nodes) {
  2962. return new Node(value, end, type ? null : slice(this.source, start, end), nodes);
  2963. },
  2964. object: function () {
  2965. var source = this.source;
  2966. var i = this.index + 1;
  2967. var expectKeypair = false;
  2968. var object = {};
  2969. var nodes = {};
  2970. while (i < source.length) {
  2971. i = this.until(['"', '}'], i);
  2972. if (at(source, i) === '}' && !expectKeypair) {
  2973. i++;
  2974. break;
  2975. }
  2976. // Parsing the key
  2977. var result = this.fork(i).string();
  2978. var key = result.value;
  2979. i = result.end;
  2980. i = this.until([':'], i) + 1;
  2981. // Parsing value
  2982. i = this.skip(IS_WHITESPACE, i);
  2983. result = this.fork(i).parse();
  2984. createProperty(nodes, key, result);
  2985. createProperty(object, key, result.value);
  2986. i = this.until([',', '}'], result.end);
  2987. var chr = at(source, i);
  2988. if (chr === ',') {
  2989. expectKeypair = true;
  2990. i++;
  2991. } else if (chr === '}') {
  2992. i++;
  2993. break;
  2994. }
  2995. }
  2996. return this.node(OBJECT, object, this.index, i, nodes);
  2997. },
  2998. array: function () {
  2999. var source = this.source;
  3000. var i = this.index + 1;
  3001. var expectElement = false;
  3002. var array = [];
  3003. var nodes = [];
  3004. while (i < source.length) {
  3005. i = this.skip(IS_WHITESPACE, i);
  3006. if (at(source, i) === ']' && !expectElement) {
  3007. i++;
  3008. break;
  3009. }
  3010. var result = this.fork(i).parse();
  3011. push(nodes, result);
  3012. push(array, result.value);
  3013. i = this.until([',', ']'], result.end);
  3014. if (at(source, i) === ',') {
  3015. expectElement = true;
  3016. i++;
  3017. } else if (at(source, i) === ']') {
  3018. i++;
  3019. break;
  3020. }
  3021. }
  3022. return this.node(OBJECT, array, this.index, i, nodes);
  3023. },
  3024. string: function () {
  3025. var index = this.index;
  3026. var parsed = parseJSONString(this.source, this.index + 1);
  3027. return this.node(PRIMITIVE, parsed.value, index, parsed.end);
  3028. },
  3029. number: function () {
  3030. var source = this.source;
  3031. var startIndex = this.index;
  3032. var i = startIndex;
  3033. if (at(source, i) === '-') i++;
  3034. if (at(source, i) === '0') i++;
  3035. else if (exec(IS_NON_ZERO_DIGIT, at(source, i))) i = this.skip(IS_DIGIT, i + 1);
  3036. else throw new SyntaxError('Failed to parse number at: ' + i);
  3037. if (at(source, i) === '.') i = this.skip(IS_DIGIT, i + 1);
  3038. if (at(source, i) === 'e' || at(source, i) === 'E') {
  3039. i++;
  3040. if (at(source, i) === '+' || at(source, i) === '-') i++;
  3041. var exponentStartIndex = i;
  3042. i = this.skip(IS_DIGIT, i);
  3043. if (exponentStartIndex === i) throw new SyntaxError("Failed to parse number's exponent value at: " + i);
  3044. }
  3045. return this.node(PRIMITIVE, Number(slice(source, startIndex, i)), startIndex, i);
  3046. },
  3047. keyword: function (value) {
  3048. var keyword = '' + value;
  3049. var index = this.index;
  3050. var endIndex = index + keyword.length;
  3051. if (slice(this.source, index, endIndex) !== keyword) throw new SyntaxError('Failed to parse value at: ' + index);
  3052. return this.node(PRIMITIVE, value, index, endIndex);
  3053. },
  3054. skip: function (regex, i) {
  3055. var source = this.source;
  3056. for (; i < source.length; i++) if (!exec(regex, at(source, i))) break;
  3057. return i;
  3058. },
  3059. until: function (array, i) {
  3060. i = this.skip(IS_WHITESPACE, i);
  3061. var chr = at(this.source, i);
  3062. for (var j = 0; j < array.length; j++) if (array[j] === chr) return i;
  3063. throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i);
  3064. }
  3065. };
  3066. var NO_SOURCE_SUPPORT = fails(function () {
  3067. var unsafeInt = '9007199254740993';
  3068. var source;
  3069. nativeParse(unsafeInt, function (key, value, context) {
  3070. source = context.source;
  3071. });
  3072. return source !== unsafeInt;
  3073. });
  3074. var PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails(function () {
  3075. // Safari 9 bug
  3076. return 1 / nativeParse('-0 \t') !== -Infinity;
  3077. });
  3078. // `JSON.parse` method
  3079. // https://tc39.es/ecma262/#sec-json.parse
  3080. // https://github.com/tc39/proposal-json-parse-with-source
  3081. $({ target: 'JSON', stat: true, forced: NO_SOURCE_SUPPORT }, {
  3082. parse: function parse(text, reviver) {
  3083. return PROPER_BASE_PARSE && !isCallable(reviver) ? nativeParse(text) : $parse(text, reviver);
  3084. }
  3085. });
  3086. /***/ }),
  3087. /***/ 8469:
  3088. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3089. var uncurryThis = __webpack_require__(9504);
  3090. var iterateSimple = __webpack_require__(507);
  3091. var SetHelpers = __webpack_require__(4402);
  3092. var Set = SetHelpers.Set;
  3093. var SetPrototype = SetHelpers.proto;
  3094. var forEach = uncurryThis(SetPrototype.forEach);
  3095. var keys = uncurryThis(SetPrototype.keys);
  3096. var next = keys(new Set()).next;
  3097. module.exports = function (set, fn, interruptible) {
  3098. return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
  3099. };
  3100. /***/ }),
  3101. /***/ 8480:
  3102. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  3103. var internalObjectKeys = __webpack_require__(1828);
  3104. var enumBugKeys = __webpack_require__(8727);
  3105. var hiddenKeys = enumBugKeys.concat('length', 'prototype');
  3106. // `Object.getOwnPropertyNames` method
  3107. // https://tc39.es/ecma262/#sec-object.getownpropertynames
  3108. // eslint-disable-next-line es/no-object-getownpropertynames -- safe
  3109. exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  3110. return internalObjectKeys(O, hiddenKeys);
  3111. };
  3112. /***/ }),
  3113. /***/ 8527:
  3114. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3115. var aSet = __webpack_require__(7080);
  3116. var has = (__webpack_require__(4402).has);
  3117. var size = __webpack_require__(5170);
  3118. var getSetRecord = __webpack_require__(3789);
  3119. var iterateSimple = __webpack_require__(507);
  3120. var iteratorClose = __webpack_require__(9539);
  3121. // `Set.prototype.isSupersetOf` method
  3122. // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
  3123. module.exports = function isSupersetOf(other) {
  3124. var O = aSet(this);
  3125. var otherRec = getSetRecord(other);
  3126. if (size(O) < otherRec.size) return false;
  3127. var iterator = otherRec.getIterator();
  3128. return iterateSimple(iterator, function (e) {
  3129. if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
  3130. }) !== false;
  3131. };
  3132. /***/ }),
  3133. /***/ 8551:
  3134. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3135. var isObject = __webpack_require__(34);
  3136. var $String = String;
  3137. var $TypeError = TypeError;
  3138. // `Assert: Type(argument) is Object`
  3139. module.exports = function (argument) {
  3140. if (isObject(argument)) return argument;
  3141. throw new $TypeError($String(argument) + ' is not an object');
  3142. };
  3143. /***/ }),
  3144. /***/ 8574:
  3145. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3146. var uncurryThis = __webpack_require__(9504);
  3147. var $Error = Error;
  3148. var replace = uncurryThis(''.replace);
  3149. var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
  3150. // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
  3151. var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
  3152. var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
  3153. module.exports = function (stack, dropEntries) {
  3154. if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
  3155. while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
  3156. } return stack;
  3157. };
  3158. /***/ }),
  3159. /***/ 8622:
  3160. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3161. var globalThis = __webpack_require__(4576);
  3162. var isCallable = __webpack_require__(4901);
  3163. var WeakMap = globalThis.WeakMap;
  3164. module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap));
  3165. /***/ }),
  3166. /***/ 8646:
  3167. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3168. var call = __webpack_require__(9565);
  3169. var anObject = __webpack_require__(8551);
  3170. var getIteratorDirect = __webpack_require__(1767);
  3171. var getIteratorMethod = __webpack_require__(851);
  3172. module.exports = function (obj, stringHandling) {
  3173. if (!stringHandling || typeof obj !== 'string') anObject(obj);
  3174. var method = getIteratorMethod(obj);
  3175. return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj));
  3176. };
  3177. /***/ }),
  3178. /***/ 8686:
  3179. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3180. var DESCRIPTORS = __webpack_require__(3724);
  3181. var fails = __webpack_require__(9039);
  3182. // V8 ~ Chrome 36-
  3183. // https://bugs.chromium.org/p/v8/issues/detail?id=3334
  3184. module.exports = DESCRIPTORS && fails(function () {
  3185. // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  3186. return Object.defineProperty(function () { /* empty */ }, 'prototype', {
  3187. value: 42,
  3188. writable: false
  3189. }).prototype !== 42;
  3190. });
  3191. /***/ }),
  3192. /***/ 8721:
  3193. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3194. var DESCRIPTORS = __webpack_require__(3724);
  3195. var uncurryThis = __webpack_require__(9504);
  3196. var defineBuiltInAccessor = __webpack_require__(2106);
  3197. var URLSearchParamsPrototype = URLSearchParams.prototype;
  3198. var forEach = uncurryThis(URLSearchParamsPrototype.forEach);
  3199. // `URLSearchParams.prototype.size` getter
  3200. // https://github.com/whatwg/url/pull/734
  3201. if (DESCRIPTORS && !('size' in URLSearchParamsPrototype)) {
  3202. defineBuiltInAccessor(URLSearchParamsPrototype, 'size', {
  3203. get: function size() {
  3204. var count = 0;
  3205. forEach(this, function () { count++; });
  3206. return count;
  3207. },
  3208. configurable: true,
  3209. enumerable: true
  3210. });
  3211. }
  3212. /***/ }),
  3213. /***/ 8727:
  3214. /***/ ((module) => {
  3215. // IE8- don't enum bug keys
  3216. module.exports = [
  3217. 'constructor',
  3218. 'hasOwnProperty',
  3219. 'isPrototypeOf',
  3220. 'propertyIsEnumerable',
  3221. 'toLocaleString',
  3222. 'toString',
  3223. 'valueOf'
  3224. ];
  3225. /***/ }),
  3226. /***/ 8745:
  3227. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3228. var NATIVE_BIND = __webpack_require__(616);
  3229. var FunctionPrototype = Function.prototype;
  3230. var apply = FunctionPrototype.apply;
  3231. var call = FunctionPrototype.call;
  3232. // eslint-disable-next-line es/no-function-prototype-bind, es/no-reflect -- safe
  3233. module.exports = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
  3234. return call.apply(apply, arguments);
  3235. });
  3236. /***/ }),
  3237. /***/ 8750:
  3238. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3239. var aSet = __webpack_require__(7080);
  3240. var SetHelpers = __webpack_require__(4402);
  3241. var size = __webpack_require__(5170);
  3242. var getSetRecord = __webpack_require__(3789);
  3243. var iterateSet = __webpack_require__(8469);
  3244. var iterateSimple = __webpack_require__(507);
  3245. var Set = SetHelpers.Set;
  3246. var add = SetHelpers.add;
  3247. var has = SetHelpers.has;
  3248. // `Set.prototype.intersection` method
  3249. // https://github.com/tc39/proposal-set-methods
  3250. module.exports = function intersection(other) {
  3251. var O = aSet(this);
  3252. var otherRec = getSetRecord(other);
  3253. var result = new Set();
  3254. if (size(O) > otherRec.size) {
  3255. iterateSimple(otherRec.getIterator(), function (e) {
  3256. if (has(O, e)) add(result, e);
  3257. });
  3258. } else {
  3259. iterateSet(O, function (e) {
  3260. if (otherRec.includes(e)) add(result, e);
  3261. });
  3262. }
  3263. return result;
  3264. };
  3265. /***/ }),
  3266. /***/ 8773:
  3267. /***/ ((__unused_webpack_module, exports) => {
  3268. var $propertyIsEnumerable = {}.propertyIsEnumerable;
  3269. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  3270. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  3271. // Nashorn ~ JDK8 bug
  3272. var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
  3273. // `Object.prototype.propertyIsEnumerable` method implementation
  3274. // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
  3275. exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
  3276. var descriptor = getOwnPropertyDescriptor(this, V);
  3277. return !!descriptor && descriptor.enumerable;
  3278. } : $propertyIsEnumerable;
  3279. /***/ }),
  3280. /***/ 8981:
  3281. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3282. var requireObjectCoercible = __webpack_require__(7750);
  3283. var $Object = Object;
  3284. // `ToObject` abstract operation
  3285. // https://tc39.es/ecma262/#sec-toobject
  3286. module.exports = function (argument) {
  3287. return $Object(requireObjectCoercible(argument));
  3288. };
  3289. /***/ }),
  3290. /***/ 9039:
  3291. /***/ ((module) => {
  3292. module.exports = function (exec) {
  3293. try {
  3294. return !!exec();
  3295. } catch (error) {
  3296. return true;
  3297. }
  3298. };
  3299. /***/ }),
  3300. /***/ 9143:
  3301. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3302. var globalThis = __webpack_require__(4576);
  3303. var uncurryThis = __webpack_require__(9504);
  3304. var anObjectOrUndefined = __webpack_require__(3972);
  3305. var aString = __webpack_require__(3463);
  3306. var hasOwn = __webpack_require__(9297);
  3307. var base64Map = __webpack_require__(2804);
  3308. var getAlphabetOption = __webpack_require__(944);
  3309. var notDetached = __webpack_require__(5169);
  3310. var base64Alphabet = base64Map.c2i;
  3311. var base64UrlAlphabet = base64Map.c2iUrl;
  3312. var SyntaxError = globalThis.SyntaxError;
  3313. var TypeError = globalThis.TypeError;
  3314. var at = uncurryThis(''.charAt);
  3315. var skipAsciiWhitespace = function (string, index) {
  3316. var length = string.length;
  3317. for (;index < length; index++) {
  3318. var chr = at(string, index);
  3319. if (chr !== ' ' && chr !== '\t' && chr !== '\n' && chr !== '\f' && chr !== '\r') break;
  3320. } return index;
  3321. };
  3322. var decodeBase64Chunk = function (chunk, alphabet, throwOnExtraBits) {
  3323. var chunkLength = chunk.length;
  3324. if (chunkLength < 4) {
  3325. chunk += chunkLength === 2 ? 'AA' : 'A';
  3326. }
  3327. var triplet = (alphabet[at(chunk, 0)] << 18)
  3328. + (alphabet[at(chunk, 1)] << 12)
  3329. + (alphabet[at(chunk, 2)] << 6)
  3330. + alphabet[at(chunk, 3)];
  3331. var chunkBytes = [
  3332. (triplet >> 16) & 255,
  3333. (triplet >> 8) & 255,
  3334. triplet & 255
  3335. ];
  3336. if (chunkLength === 2) {
  3337. if (throwOnExtraBits && chunkBytes[1] !== 0) {
  3338. throw new SyntaxError('Extra bits');
  3339. }
  3340. return [chunkBytes[0]];
  3341. }
  3342. if (chunkLength === 3) {
  3343. if (throwOnExtraBits && chunkBytes[2] !== 0) {
  3344. throw new SyntaxError('Extra bits');
  3345. }
  3346. return [chunkBytes[0], chunkBytes[1]];
  3347. }
  3348. return chunkBytes;
  3349. };
  3350. var writeBytes = function (bytes, elements, written) {
  3351. var elementsLength = elements.length;
  3352. for (var index = 0; index < elementsLength; index++) {
  3353. bytes[written + index] = elements[index];
  3354. }
  3355. return written + elementsLength;
  3356. };
  3357. /* eslint-disable max-statements, max-depth -- TODO */
  3358. module.exports = function (string, options, into, maxLength) {
  3359. aString(string);
  3360. anObjectOrUndefined(options);
  3361. var alphabet = getAlphabetOption(options) === 'base64' ? base64Alphabet : base64UrlAlphabet;
  3362. var lastChunkHandling = options ? options.lastChunkHandling : undefined;
  3363. if (lastChunkHandling === undefined) lastChunkHandling = 'loose';
  3364. if (lastChunkHandling !== 'loose' && lastChunkHandling !== 'strict' && lastChunkHandling !== 'stop-before-partial') {
  3365. throw new TypeError('Incorrect `lastChunkHandling` option');
  3366. }
  3367. if (into) notDetached(into.buffer);
  3368. var bytes = into || [];
  3369. var written = 0;
  3370. var read = 0;
  3371. var chunk = '';
  3372. var index = 0;
  3373. if (maxLength) while (true) {
  3374. index = skipAsciiWhitespace(string, index);
  3375. if (index === string.length) {
  3376. if (chunk.length > 0) {
  3377. if (lastChunkHandling === 'stop-before-partial') {
  3378. break;
  3379. }
  3380. if (lastChunkHandling === 'loose') {
  3381. if (chunk.length === 1) {
  3382. throw new SyntaxError('Malformed padding: exactly one additional character');
  3383. }
  3384. written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, false), written);
  3385. } else {
  3386. throw new SyntaxError('Missing padding');
  3387. }
  3388. }
  3389. read = string.length;
  3390. break;
  3391. }
  3392. var chr = at(string, index);
  3393. ++index;
  3394. if (chr === '=') {
  3395. if (chunk.length < 2) {
  3396. throw new SyntaxError('Padding is too early');
  3397. }
  3398. index = skipAsciiWhitespace(string, index);
  3399. if (chunk.length === 2) {
  3400. if (index === string.length) {
  3401. if (lastChunkHandling === 'stop-before-partial') {
  3402. break;
  3403. }
  3404. throw new SyntaxError('Malformed padding: only one =');
  3405. }
  3406. if (at(string, index) === '=') {
  3407. ++index;
  3408. index = skipAsciiWhitespace(string, index);
  3409. }
  3410. }
  3411. if (index < string.length) {
  3412. throw new SyntaxError('Unexpected character after padding');
  3413. }
  3414. written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, lastChunkHandling === 'strict'), written);
  3415. read = string.length;
  3416. break;
  3417. }
  3418. if (!hasOwn(alphabet, chr)) {
  3419. throw new SyntaxError('Unexpected character');
  3420. }
  3421. var remainingBytes = maxLength - written;
  3422. if (remainingBytes === 1 && chunk.length === 2 || remainingBytes === 2 && chunk.length === 3) {
  3423. // special case: we can fit exactly the number of bytes currently represented by chunk, so we were just checking for `=`
  3424. break;
  3425. }
  3426. chunk += chr;
  3427. if (chunk.length === 4) {
  3428. written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, false), written);
  3429. chunk = '';
  3430. read = index;
  3431. if (written === maxLength) {
  3432. break;
  3433. }
  3434. }
  3435. }
  3436. return { bytes: bytes, read: read, written: written };
  3437. };
  3438. /***/ }),
  3439. /***/ 9286:
  3440. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3441. var SetHelpers = __webpack_require__(4402);
  3442. var iterate = __webpack_require__(8469);
  3443. var Set = SetHelpers.Set;
  3444. var add = SetHelpers.add;
  3445. module.exports = function (set) {
  3446. var result = new Set();
  3447. iterate(set, function (it) {
  3448. add(result, it);
  3449. });
  3450. return result;
  3451. };
  3452. /***/ }),
  3453. /***/ 9297:
  3454. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3455. var uncurryThis = __webpack_require__(9504);
  3456. var toObject = __webpack_require__(8981);
  3457. var hasOwnProperty = uncurryThis({}.hasOwnProperty);
  3458. // `HasOwnProperty` abstract operation
  3459. // https://tc39.es/ecma262/#sec-hasownproperty
  3460. // eslint-disable-next-line es/no-object-hasown -- safe
  3461. module.exports = Object.hasOwn || function hasOwn(it, key) {
  3462. return hasOwnProperty(toObject(it), key);
  3463. };
  3464. /***/ }),
  3465. /***/ 9306:
  3466. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3467. var isCallable = __webpack_require__(4901);
  3468. var tryToString = __webpack_require__(6823);
  3469. var $TypeError = TypeError;
  3470. // `Assert: IsCallable(argument) is true`
  3471. module.exports = function (argument) {
  3472. if (isCallable(argument)) return argument;
  3473. throw new $TypeError(tryToString(argument) + ' is not a function');
  3474. };
  3475. /***/ }),
  3476. /***/ 9314:
  3477. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3478. var $ = __webpack_require__(6518);
  3479. var call = __webpack_require__(9565);
  3480. var anObject = __webpack_require__(8551);
  3481. var getIteratorDirect = __webpack_require__(1767);
  3482. var notANaN = __webpack_require__(4149);
  3483. var toPositiveInteger = __webpack_require__(9590);
  3484. var iteratorClose = __webpack_require__(9539);
  3485. var createIteratorProxy = __webpack_require__(9462);
  3486. var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);
  3487. var IS_PURE = __webpack_require__(6395);
  3488. var dropWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('drop', RangeError);
  3489. var IteratorProxy = createIteratorProxy(function () {
  3490. var iterator = this.iterator;
  3491. var next = this.next;
  3492. var result, done;
  3493. while (this.remaining) {
  3494. this.remaining--;
  3495. result = anObject(call(next, iterator));
  3496. done = this.done = !!result.done;
  3497. if (done) return;
  3498. }
  3499. result = anObject(call(next, iterator));
  3500. done = this.done = !!result.done;
  3501. if (!done) return result.value;
  3502. });
  3503. // `Iterator.prototype.drop` method
  3504. // https://tc39.es/ecma262/#sec-iterator.prototype.drop
  3505. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || dropWithoutClosingOnEarlyError }, {
  3506. drop: function drop(limit) {
  3507. anObject(this);
  3508. var remaining;
  3509. try {
  3510. remaining = toPositiveInteger(notANaN(+limit));
  3511. } catch (error) {
  3512. iteratorClose(this, 'throw', error);
  3513. }
  3514. if (dropWithoutClosingOnEarlyError) return call(dropWithoutClosingOnEarlyError, this, remaining);
  3515. return new IteratorProxy(getIteratorDirect(this), {
  3516. remaining: remaining
  3517. });
  3518. }
  3519. });
  3520. /***/ }),
  3521. /***/ 9429:
  3522. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3523. var globalThis = __webpack_require__(4576);
  3524. var IS_NODE = __webpack_require__(6193);
  3525. module.exports = function (name) {
  3526. if (IS_NODE) {
  3527. try {
  3528. return globalThis.process.getBuiltinModule(name);
  3529. } catch (error) { /* empty */ }
  3530. try {
  3531. // eslint-disable-next-line no-new-func -- safe
  3532. return Function('return require("' + name + '")')();
  3533. } catch (error) { /* empty */ }
  3534. }
  3535. };
  3536. /***/ }),
  3537. /***/ 9432:
  3538. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3539. var $ = __webpack_require__(6518);
  3540. var globalThis = __webpack_require__(4576);
  3541. var arrayFromConstructorAndList = __webpack_require__(5370);
  3542. var $fromBase64 = __webpack_require__(9143);
  3543. var Uint8Array = globalThis.Uint8Array;
  3544. // `Uint8Array.fromBase64` method
  3545. // https://github.com/tc39/proposal-arraybuffer-base64
  3546. if (Uint8Array) $({ target: 'Uint8Array', stat: true }, {
  3547. fromBase64: function fromBase64(string /* , options */) {
  3548. var result = $fromBase64(string, arguments.length > 1 ? arguments[1] : undefined, null, 0x1FFFFFFFFFFFFF);
  3549. return arrayFromConstructorAndList(Uint8Array, result.bytes);
  3550. }
  3551. });
  3552. /***/ }),
  3553. /***/ 9433:
  3554. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3555. var globalThis = __webpack_require__(4576);
  3556. // eslint-disable-next-line es/no-object-defineproperty -- safe
  3557. var defineProperty = Object.defineProperty;
  3558. module.exports = function (key, value) {
  3559. try {
  3560. defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
  3561. } catch (error) {
  3562. globalThis[key] = value;
  3563. } return value;
  3564. };
  3565. /***/ }),
  3566. /***/ 9462:
  3567. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3568. var call = __webpack_require__(9565);
  3569. var create = __webpack_require__(2360);
  3570. var createNonEnumerableProperty = __webpack_require__(6699);
  3571. var defineBuiltIns = __webpack_require__(6279);
  3572. var wellKnownSymbol = __webpack_require__(8227);
  3573. var InternalStateModule = __webpack_require__(1181);
  3574. var getMethod = __webpack_require__(5966);
  3575. var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);
  3576. var createIterResultObject = __webpack_require__(2529);
  3577. var iteratorClose = __webpack_require__(9539);
  3578. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  3579. var ITERATOR_HELPER = 'IteratorHelper';
  3580. var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
  3581. var setInternalState = InternalStateModule.set;
  3582. var createIteratorProxyPrototype = function (IS_ITERATOR) {
  3583. var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
  3584. return defineBuiltIns(create(IteratorPrototype), {
  3585. next: function next() {
  3586. var state = getInternalState(this);
  3587. // for simplification:
  3588. // for `%WrapForValidIteratorPrototype%.next` or with `state.returnHandlerResult` our `nextHandler` returns `IterResultObject`
  3589. // for `%IteratorHelperPrototype%.next` - just a value
  3590. if (IS_ITERATOR) return state.nextHandler();
  3591. if (state.done) return createIterResultObject(undefined, true);
  3592. try {
  3593. var result = state.nextHandler();
  3594. return state.returnHandlerResult ? result : createIterResultObject(result, state.done);
  3595. } catch (error) {
  3596. state.done = true;
  3597. throw error;
  3598. }
  3599. },
  3600. 'return': function () {
  3601. var state = getInternalState(this);
  3602. var iterator = state.iterator;
  3603. state.done = true;
  3604. if (IS_ITERATOR) {
  3605. var returnMethod = getMethod(iterator, 'return');
  3606. return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
  3607. }
  3608. if (state.inner) try {
  3609. iteratorClose(state.inner.iterator, 'normal');
  3610. } catch (error) {
  3611. return iteratorClose(iterator, 'throw', error);
  3612. }
  3613. if (iterator) iteratorClose(iterator, 'normal');
  3614. return createIterResultObject(undefined, true);
  3615. }
  3616. });
  3617. };
  3618. var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
  3619. var IteratorHelperPrototype = createIteratorProxyPrototype(false);
  3620. createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
  3621. module.exports = function (nextHandler, IS_ITERATOR, RETURN_HANDLER_RESULT) {
  3622. var IteratorProxy = function Iterator(record, state) {
  3623. if (state) {
  3624. state.iterator = record.iterator;
  3625. state.next = record.next;
  3626. } else state = record;
  3627. state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
  3628. state.returnHandlerResult = !!RETURN_HANDLER_RESULT;
  3629. state.nextHandler = nextHandler;
  3630. state.counter = 0;
  3631. state.done = false;
  3632. setInternalState(this, state);
  3633. };
  3634. IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
  3635. return IteratorProxy;
  3636. };
  3637. /***/ }),
  3638. /***/ 9504:
  3639. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3640. var NATIVE_BIND = __webpack_require__(616);
  3641. var FunctionPrototype = Function.prototype;
  3642. var call = FunctionPrototype.call;
  3643. // eslint-disable-next-line es/no-function-prototype-bind -- safe
  3644. var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
  3645. module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
  3646. return function () {
  3647. return call.apply(fn, arguments);
  3648. };
  3649. };
  3650. /***/ }),
  3651. /***/ 9519:
  3652. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3653. var globalThis = __webpack_require__(4576);
  3654. var userAgent = __webpack_require__(2839);
  3655. var process = globalThis.process;
  3656. var Deno = globalThis.Deno;
  3657. var versions = process && process.versions || Deno && Deno.version;
  3658. var v8 = versions && versions.v8;
  3659. var match, version;
  3660. if (v8) {
  3661. match = v8.split('.');
  3662. // in old Chrome, versions of V8 isn't V8 = Chrome / 10
  3663. // but their correct versions are not interesting for us
  3664. version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
  3665. }
  3666. // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
  3667. // so check `userAgent` even if `.v8` exists, but 0
  3668. if (!version && userAgent) {
  3669. match = userAgent.match(/Edge\/(\d+)/);
  3670. if (!match || match[1] >= 74) {
  3671. match = userAgent.match(/Chrome\/(\d+)/);
  3672. if (match) version = +match[1];
  3673. }
  3674. }
  3675. module.exports = version;
  3676. /***/ }),
  3677. /***/ 9539:
  3678. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3679. var call = __webpack_require__(9565);
  3680. var anObject = __webpack_require__(8551);
  3681. var getMethod = __webpack_require__(5966);
  3682. module.exports = function (iterator, kind, value) {
  3683. var innerResult, innerError;
  3684. anObject(iterator);
  3685. try {
  3686. innerResult = getMethod(iterator, 'return');
  3687. if (!innerResult) {
  3688. if (kind === 'throw') throw value;
  3689. return value;
  3690. }
  3691. innerResult = call(innerResult, iterator);
  3692. } catch (error) {
  3693. innerError = true;
  3694. innerResult = error;
  3695. }
  3696. if (kind === 'throw') throw value;
  3697. if (innerError) throw innerResult;
  3698. anObject(innerResult);
  3699. return value;
  3700. };
  3701. /***/ }),
  3702. /***/ 9565:
  3703. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3704. var NATIVE_BIND = __webpack_require__(616);
  3705. var call = Function.prototype.call;
  3706. // eslint-disable-next-line es/no-function-prototype-bind -- safe
  3707. module.exports = NATIVE_BIND ? call.bind(call) : function () {
  3708. return call.apply(call, arguments);
  3709. };
  3710. /***/ }),
  3711. /***/ 9590:
  3712. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3713. var toIntegerOrInfinity = __webpack_require__(1291);
  3714. var $RangeError = RangeError;
  3715. module.exports = function (it) {
  3716. var result = toIntegerOrInfinity(it);
  3717. if (result < 0) throw new $RangeError("The argument can't be less than 0");
  3718. return result;
  3719. };
  3720. /***/ }),
  3721. /***/ 9617:
  3722. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  3723. var toIndexedObject = __webpack_require__(5397);
  3724. var toAbsoluteIndex = __webpack_require__(5610);
  3725. var lengthOfArrayLike = __webpack_require__(6198);
  3726. // `Array.prototype.{ indexOf, includes }` methods implementation
  3727. var createMethod = function (IS_INCLUDES) {
  3728. return function ($this, el, fromIndex) {
  3729. var O = toIndexedObject($this);
  3730. var length = lengthOfArrayLike(O);
  3731. if (length === 0) return !IS_INCLUDES && -1;
  3732. var index = toAbsoluteIndex(fromIndex, length);
  3733. var value;
  3734. // Array#includes uses SameValueZero equality algorithm
  3735. // eslint-disable-next-line no-self-compare -- NaN check
  3736. if (IS_INCLUDES && el !== el) while (length > index) {
  3737. value = O[index++];
  3738. // eslint-disable-next-line no-self-compare -- NaN check
  3739. if (value !== value) return true;
  3740. // Array#indexOf ignores holes, Array#includes - not
  3741. } else for (;length > index; index++) {
  3742. if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
  3743. } return !IS_INCLUDES && -1;
  3744. };
  3745. };
  3746. module.exports = {
  3747. // `Array.prototype.includes` method
  3748. // https://tc39.es/ecma262/#sec-array.prototype.includes
  3749. includes: createMethod(true),
  3750. // `Array.prototype.indexOf` method
  3751. // https://tc39.es/ecma262/#sec-array.prototype.indexof
  3752. indexOf: createMethod(false)
  3753. };
  3754. /***/ }),
  3755. /***/ 9631:
  3756. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3757. var $ = __webpack_require__(6518);
  3758. var globalThis = __webpack_require__(4576);
  3759. var uncurryThis = __webpack_require__(9504);
  3760. var anObjectOrUndefined = __webpack_require__(3972);
  3761. var anUint8Array = __webpack_require__(4154);
  3762. var notDetached = __webpack_require__(5169);
  3763. var base64Map = __webpack_require__(2804);
  3764. var getAlphabetOption = __webpack_require__(944);
  3765. var base64Alphabet = base64Map.i2c;
  3766. var base64UrlAlphabet = base64Map.i2cUrl;
  3767. var charAt = uncurryThis(''.charAt);
  3768. // `Uint8Array.prototype.toBase64` method
  3769. // https://github.com/tc39/proposal-arraybuffer-base64
  3770. if (globalThis.Uint8Array) $({ target: 'Uint8Array', proto: true }, {
  3771. toBase64: function toBase64(/* options */) {
  3772. var array = anUint8Array(this);
  3773. var options = arguments.length ? anObjectOrUndefined(arguments[0]) : undefined;
  3774. var alphabet = getAlphabetOption(options) === 'base64' ? base64Alphabet : base64UrlAlphabet;
  3775. var omitPadding = !!options && !!options.omitPadding;
  3776. notDetached(this.buffer);
  3777. var result = '';
  3778. var i = 0;
  3779. var length = array.length;
  3780. var triplet;
  3781. var at = function (shift) {
  3782. return charAt(alphabet, (triplet >> (6 * shift)) & 63);
  3783. };
  3784. for (; i + 2 < length; i += 3) {
  3785. triplet = (array[i] << 16) + (array[i + 1] << 8) + array[i + 2];
  3786. result += at(3) + at(2) + at(1) + at(0);
  3787. }
  3788. if (i + 2 === length) {
  3789. triplet = (array[i] << 16) + (array[i + 1] << 8);
  3790. result += at(3) + at(2) + at(1) + (omitPadding ? '' : '=');
  3791. } else if (i + 1 === length) {
  3792. triplet = array[i] << 16;
  3793. result += at(3) + at(2) + (omitPadding ? '' : '==');
  3794. }
  3795. return result;
  3796. }
  3797. });
  3798. /***/ }),
  3799. /***/ 9797:
  3800. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3801. var $ = __webpack_require__(6518);
  3802. var globalThis = __webpack_require__(4576);
  3803. var aString = __webpack_require__(3463);
  3804. var anUint8Array = __webpack_require__(4154);
  3805. var notDetached = __webpack_require__(5169);
  3806. var $fromHex = __webpack_require__(2303);
  3807. // `Uint8Array.prototype.setFromHex` method
  3808. // https://github.com/tc39/proposal-arraybuffer-base64
  3809. if (globalThis.Uint8Array) $({ target: 'Uint8Array', proto: true }, {
  3810. setFromHex: function setFromHex(string) {
  3811. anUint8Array(this);
  3812. aString(string);
  3813. notDetached(this.buffer);
  3814. var read = $fromHex(string, this).read;
  3815. return { read: read, written: read / 2 };
  3816. }
  3817. });
  3818. /***/ })
  3819. /******/ });
  3820. /************************************************************************/
  3821. /******/ // The module cache
  3822. /******/ var __webpack_module_cache__ = {};
  3823. /******/
  3824. /******/ // The require function
  3825. /******/ function __webpack_require__(moduleId) {
  3826. /******/ // Check if module is in cache
  3827. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  3828. /******/ if (cachedModule !== undefined) {
  3829. /******/ return cachedModule.exports;
  3830. /******/ }
  3831. /******/ // Create a new module (and put it into the cache)
  3832. /******/ var module = __webpack_module_cache__[moduleId] = {
  3833. /******/ // no module.id needed
  3834. /******/ // no module.loaded needed
  3835. /******/ exports: {}
  3836. /******/ };
  3837. /******/
  3838. /******/ // Execute the module function
  3839. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  3840. /******/
  3841. /******/ // Return the exports of the module
  3842. /******/ return module.exports;
  3843. /******/ }
  3844. /******/
  3845. /************************************************************************/
  3846. var __webpack_exports__ = {};
  3847. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array.push.js
  3848. var es_array_push = __webpack_require__(4114);
  3849. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.detached.js
  3850. var es_array_buffer_detached = __webpack_require__(6573);
  3851. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer.js
  3852. var es_array_buffer_transfer = __webpack_require__(8100);
  3853. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer-to-fixed-length.js
  3854. var es_array_buffer_transfer_to_fixed_length = __webpack_require__(7936);
  3855. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.constructor.js
  3856. var es_iterator_constructor = __webpack_require__(8111);
  3857. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.reduce.js
  3858. var es_iterator_reduce = __webpack_require__(8237);
  3859. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.try.js
  3860. var es_promise_try = __webpack_require__(1689);
  3861. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.uint8-array.from-base64.js
  3862. var esnext_uint8_array_from_base64 = __webpack_require__(9432);
  3863. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.uint8-array.set-from-base64.js
  3864. var esnext_uint8_array_set_from_base64 = __webpack_require__(1549);
  3865. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.uint8-array.set-from-hex.js
  3866. var esnext_uint8_array_set_from_hex = __webpack_require__(9797);
  3867. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.uint8-array.to-base64.js
  3868. var esnext_uint8_array_to_base64 = __webpack_require__(9631);
  3869. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.uint8-array.to-hex.js
  3870. var esnext_uint8_array_to_hex = __webpack_require__(5623);
  3871. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom-exception.stack.js
  3872. var web_dom_exception_stack = __webpack_require__(4979);
  3873. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url.parse.js
  3874. var web_url_parse = __webpack_require__(5781);
  3875. ;// ./src/shared/util.js
  3876. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  3877. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  3878. const LINE_FACTOR = 1.35;
  3879. const LINE_DESCENT_FACTOR = 0.35;
  3880. const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
  3881. const RenderingIntentFlag = {
  3882. ANY: 0x01,
  3883. DISPLAY: 0x02,
  3884. PRINT: 0x04,
  3885. SAVE: 0x08,
  3886. ANNOTATIONS_FORMS: 0x10,
  3887. ANNOTATIONS_STORAGE: 0x20,
  3888. ANNOTATIONS_DISABLE: 0x40,
  3889. IS_EDITING: 0x80,
  3890. OPLIST: 0x100
  3891. };
  3892. const AnnotationMode = {
  3893. DISABLE: 0,
  3894. ENABLE: 1,
  3895. ENABLE_FORMS: 2,
  3896. ENABLE_STORAGE: 3
  3897. };
  3898. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  3899. const AnnotationEditorType = {
  3900. DISABLE: -1,
  3901. NONE: 0,
  3902. FREETEXT: 3,
  3903. HIGHLIGHT: 9,
  3904. STAMP: 13,
  3905. INK: 15,
  3906. SIGNATURE: 101
  3907. };
  3908. const AnnotationEditorParamsType = {
  3909. RESIZE: 1,
  3910. CREATE: 2,
  3911. FREETEXT_SIZE: 11,
  3912. FREETEXT_COLOR: 12,
  3913. FREETEXT_OPACITY: 13,
  3914. INK_COLOR: 21,
  3915. INK_THICKNESS: 22,
  3916. INK_OPACITY: 23,
  3917. HIGHLIGHT_COLOR: 31,
  3918. HIGHLIGHT_DEFAULT_COLOR: 32,
  3919. HIGHLIGHT_THICKNESS: 33,
  3920. HIGHLIGHT_FREE: 34,
  3921. HIGHLIGHT_SHOW_ALL: 35,
  3922. DRAW_STEP: 41
  3923. };
  3924. const PermissionFlag = {
  3925. PRINT: 0x04,
  3926. MODIFY_CONTENTS: 0x08,
  3927. COPY: 0x10,
  3928. MODIFY_ANNOTATIONS: 0x20,
  3929. FILL_INTERACTIVE_FORMS: 0x100,
  3930. COPY_FOR_ACCESSIBILITY: 0x200,
  3931. ASSEMBLE: 0x400,
  3932. PRINT_HIGH_QUALITY: 0x800
  3933. };
  3934. const TextRenderingMode = {
  3935. FILL: 0,
  3936. STROKE: 1,
  3937. FILL_STROKE: 2,
  3938. INVISIBLE: 3,
  3939. FILL_ADD_TO_PATH: 4,
  3940. STROKE_ADD_TO_PATH: 5,
  3941. FILL_STROKE_ADD_TO_PATH: 6,
  3942. ADD_TO_PATH: 7,
  3943. FILL_STROKE_MASK: 3,
  3944. ADD_TO_PATH_FLAG: 4
  3945. };
  3946. const util_ImageKind = {
  3947. GRAYSCALE_1BPP: 1,
  3948. RGB_24BPP: 2,
  3949. RGBA_32BPP: 3
  3950. };
  3951. const AnnotationType = {
  3952. TEXT: 1,
  3953. LINK: 2,
  3954. FREETEXT: 3,
  3955. LINE: 4,
  3956. SQUARE: 5,
  3957. CIRCLE: 6,
  3958. POLYGON: 7,
  3959. POLYLINE: 8,
  3960. HIGHLIGHT: 9,
  3961. UNDERLINE: 10,
  3962. SQUIGGLY: 11,
  3963. STRIKEOUT: 12,
  3964. STAMP: 13,
  3965. CARET: 14,
  3966. INK: 15,
  3967. POPUP: 16,
  3968. FILEATTACHMENT: 17,
  3969. SOUND: 18,
  3970. MOVIE: 19,
  3971. WIDGET: 20,
  3972. SCREEN: 21,
  3973. PRINTERMARK: 22,
  3974. TRAPNET: 23,
  3975. WATERMARK: 24,
  3976. THREED: 25,
  3977. REDACT: 26
  3978. };
  3979. const AnnotationReplyType = {
  3980. GROUP: "Group",
  3981. REPLY: "R"
  3982. };
  3983. const AnnotationFlag = {
  3984. INVISIBLE: 0x01,
  3985. HIDDEN: 0x02,
  3986. PRINT: 0x04,
  3987. NOZOOM: 0x08,
  3988. NOROTATE: 0x10,
  3989. NOVIEW: 0x20,
  3990. READONLY: 0x40,
  3991. LOCKED: 0x80,
  3992. TOGGLENOVIEW: 0x100,
  3993. LOCKEDCONTENTS: 0x200
  3994. };
  3995. const AnnotationFieldFlag = {
  3996. READONLY: 0x0000001,
  3997. REQUIRED: 0x0000002,
  3998. NOEXPORT: 0x0000004,
  3999. MULTILINE: 0x0001000,
  4000. PASSWORD: 0x0002000,
  4001. NOTOGGLETOOFF: 0x0004000,
  4002. RADIO: 0x0008000,
  4003. PUSHBUTTON: 0x0010000,
  4004. COMBO: 0x0020000,
  4005. EDIT: 0x0040000,
  4006. SORT: 0x0080000,
  4007. FILESELECT: 0x0100000,
  4008. MULTISELECT: 0x0200000,
  4009. DONOTSPELLCHECK: 0x0400000,
  4010. DONOTSCROLL: 0x0800000,
  4011. COMB: 0x1000000,
  4012. RICHTEXT: 0x2000000,
  4013. RADIOSINUNISON: 0x2000000,
  4014. COMMITONSELCHANGE: 0x4000000
  4015. };
  4016. const AnnotationBorderStyleType = {
  4017. SOLID: 1,
  4018. DASHED: 2,
  4019. BEVELED: 3,
  4020. INSET: 4,
  4021. UNDERLINE: 5
  4022. };
  4023. const AnnotationActionEventType = {
  4024. E: "Mouse Enter",
  4025. X: "Mouse Exit",
  4026. D: "Mouse Down",
  4027. U: "Mouse Up",
  4028. Fo: "Focus",
  4029. Bl: "Blur",
  4030. PO: "PageOpen",
  4031. PC: "PageClose",
  4032. PV: "PageVisible",
  4033. PI: "PageInvisible",
  4034. K: "Keystroke",
  4035. F: "Format",
  4036. V: "Validate",
  4037. C: "Calculate"
  4038. };
  4039. const DocumentActionEventType = {
  4040. WC: "WillClose",
  4041. WS: "WillSave",
  4042. DS: "DidSave",
  4043. WP: "WillPrint",
  4044. DP: "DidPrint"
  4045. };
  4046. const PageActionEventType = {
  4047. O: "PageOpen",
  4048. C: "PageClose"
  4049. };
  4050. const VerbosityLevel = {
  4051. ERRORS: 0,
  4052. WARNINGS: 1,
  4053. INFOS: 5
  4054. };
  4055. const OPS = {
  4056. dependency: 1,
  4057. setLineWidth: 2,
  4058. setLineCap: 3,
  4059. setLineJoin: 4,
  4060. setMiterLimit: 5,
  4061. setDash: 6,
  4062. setRenderingIntent: 7,
  4063. setFlatness: 8,
  4064. setGState: 9,
  4065. save: 10,
  4066. restore: 11,
  4067. transform: 12,
  4068. moveTo: 13,
  4069. lineTo: 14,
  4070. curveTo: 15,
  4071. curveTo2: 16,
  4072. curveTo3: 17,
  4073. closePath: 18,
  4074. rectangle: 19,
  4075. stroke: 20,
  4076. closeStroke: 21,
  4077. fill: 22,
  4078. eoFill: 23,
  4079. fillStroke: 24,
  4080. eoFillStroke: 25,
  4081. closeFillStroke: 26,
  4082. closeEOFillStroke: 27,
  4083. endPath: 28,
  4084. clip: 29,
  4085. eoClip: 30,
  4086. beginText: 31,
  4087. endText: 32,
  4088. setCharSpacing: 33,
  4089. setWordSpacing: 34,
  4090. setHScale: 35,
  4091. setLeading: 36,
  4092. setFont: 37,
  4093. setTextRenderingMode: 38,
  4094. setTextRise: 39,
  4095. moveText: 40,
  4096. setLeadingMoveText: 41,
  4097. setTextMatrix: 42,
  4098. nextLine: 43,
  4099. showText: 44,
  4100. showSpacedText: 45,
  4101. nextLineShowText: 46,
  4102. nextLineSetSpacingShowText: 47,
  4103. setCharWidth: 48,
  4104. setCharWidthAndBounds: 49,
  4105. setStrokeColorSpace: 50,
  4106. setFillColorSpace: 51,
  4107. setStrokeColor: 52,
  4108. setStrokeColorN: 53,
  4109. setFillColor: 54,
  4110. setFillColorN: 55,
  4111. setStrokeGray: 56,
  4112. setFillGray: 57,
  4113. setStrokeRGBColor: 58,
  4114. setFillRGBColor: 59,
  4115. setStrokeCMYKColor: 60,
  4116. setFillCMYKColor: 61,
  4117. shadingFill: 62,
  4118. beginInlineImage: 63,
  4119. beginImageData: 64,
  4120. endInlineImage: 65,
  4121. paintXObject: 66,
  4122. markPoint: 67,
  4123. markPointProps: 68,
  4124. beginMarkedContent: 69,
  4125. beginMarkedContentProps: 70,
  4126. endMarkedContent: 71,
  4127. beginCompat: 72,
  4128. endCompat: 73,
  4129. paintFormXObjectBegin: 74,
  4130. paintFormXObjectEnd: 75,
  4131. beginGroup: 76,
  4132. endGroup: 77,
  4133. beginAnnotation: 80,
  4134. endAnnotation: 81,
  4135. paintImageMaskXObject: 83,
  4136. paintImageMaskXObjectGroup: 84,
  4137. paintImageXObject: 85,
  4138. paintInlineImageXObject: 86,
  4139. paintInlineImageXObjectGroup: 87,
  4140. paintImageXObjectRepeat: 88,
  4141. paintImageMaskXObjectRepeat: 89,
  4142. paintSolidColorImageMask: 90,
  4143. constructPath: 91,
  4144. setStrokeTransparent: 92,
  4145. setFillTransparent: 93,
  4146. rawFillPath: 94
  4147. };
  4148. const DrawOPS = {
  4149. moveTo: 0,
  4150. lineTo: 1,
  4151. curveTo: 2,
  4152. closePath: 3
  4153. };
  4154. const PasswordResponses = {
  4155. NEED_PASSWORD: 1,
  4156. INCORRECT_PASSWORD: 2
  4157. };
  4158. let verbosity = VerbosityLevel.WARNINGS;
  4159. function setVerbosityLevel(level) {
  4160. if (Number.isInteger(level)) {
  4161. verbosity = level;
  4162. }
  4163. }
  4164. function getVerbosityLevel() {
  4165. return verbosity;
  4166. }
  4167. function info(msg) {
  4168. if (verbosity >= VerbosityLevel.INFOS) {
  4169. console.log(`Info: ${msg}`);
  4170. }
  4171. }
  4172. function warn(msg) {
  4173. if (verbosity >= VerbosityLevel.WARNINGS) {
  4174. console.log(`Warning: ${msg}`);
  4175. }
  4176. }
  4177. function unreachable(msg) {
  4178. throw new Error(msg);
  4179. }
  4180. function assert(cond, msg) {
  4181. if (!cond) {
  4182. unreachable(msg);
  4183. }
  4184. }
  4185. function _isValidProtocol(url) {
  4186. switch (url?.protocol) {
  4187. case "http:":
  4188. case "https:":
  4189. case "ftp:":
  4190. case "mailto:":
  4191. case "tel:":
  4192. return true;
  4193. default:
  4194. return false;
  4195. }
  4196. }
  4197. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  4198. if (!url) {
  4199. return null;
  4200. }
  4201. if (options && typeof url === "string") {
  4202. if (options.addDefaultProtocol && url.startsWith("www.")) {
  4203. const dots = url.match(/\./g);
  4204. if (dots?.length >= 2) {
  4205. url = `http://${url}`;
  4206. }
  4207. }
  4208. if (options.tryConvertEncoding) {
  4209. try {
  4210. url = stringToUTF8String(url);
  4211. } catch {}
  4212. }
  4213. }
  4214. const absoluteUrl = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
  4215. return _isValidProtocol(absoluteUrl) ? absoluteUrl : null;
  4216. }
  4217. function updateUrlHash(url, hash, allowRel = false) {
  4218. const res = URL.parse(url);
  4219. if (res) {
  4220. res.hash = hash;
  4221. return res.href;
  4222. }
  4223. if (allowRel && createValidAbsoluteUrl(url, "http://example.com")) {
  4224. return url.split("#", 1)[0] + `${hash ? `#${hash}` : ""}`;
  4225. }
  4226. return "";
  4227. }
  4228. function shadow(obj, prop, value, nonSerializable = false) {
  4229. Object.defineProperty(obj, prop, {
  4230. value,
  4231. enumerable: !nonSerializable,
  4232. configurable: true,
  4233. writable: false
  4234. });
  4235. return value;
  4236. }
  4237. const BaseException = function BaseExceptionClosure() {
  4238. function BaseException(message, name) {
  4239. this.message = message;
  4240. this.name = name;
  4241. }
  4242. BaseException.prototype = new Error();
  4243. BaseException.constructor = BaseException;
  4244. return BaseException;
  4245. }();
  4246. class PasswordException extends BaseException {
  4247. constructor(msg, code) {
  4248. super(msg, "PasswordException");
  4249. this.code = code;
  4250. }
  4251. }
  4252. class UnknownErrorException extends BaseException {
  4253. constructor(msg, details) {
  4254. super(msg, "UnknownErrorException");
  4255. this.details = details;
  4256. }
  4257. }
  4258. class InvalidPDFException extends BaseException {
  4259. constructor(msg) {
  4260. super(msg, "InvalidPDFException");
  4261. }
  4262. }
  4263. class ResponseException extends BaseException {
  4264. constructor(msg, status, missing) {
  4265. super(msg, "ResponseException");
  4266. this.status = status;
  4267. this.missing = missing;
  4268. }
  4269. }
  4270. class FormatError extends BaseException {
  4271. constructor(msg) {
  4272. super(msg, "FormatError");
  4273. }
  4274. }
  4275. class AbortException extends BaseException {
  4276. constructor(msg) {
  4277. super(msg, "AbortException");
  4278. }
  4279. }
  4280. function bytesToString(bytes) {
  4281. if (typeof bytes !== "object" || bytes?.length === undefined) {
  4282. unreachable("Invalid argument for bytesToString");
  4283. }
  4284. const length = bytes.length;
  4285. const MAX_ARGUMENT_COUNT = 8192;
  4286. if (length < MAX_ARGUMENT_COUNT) {
  4287. return String.fromCharCode.apply(null, bytes);
  4288. }
  4289. const strBuf = [];
  4290. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  4291. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  4292. const chunk = bytes.subarray(i, chunkEnd);
  4293. strBuf.push(String.fromCharCode.apply(null, chunk));
  4294. }
  4295. return strBuf.join("");
  4296. }
  4297. function stringToBytes(str) {
  4298. if (typeof str !== "string") {
  4299. unreachable("Invalid argument for stringToBytes");
  4300. }
  4301. const length = str.length;
  4302. const bytes = new Uint8Array(length);
  4303. for (let i = 0; i < length; ++i) {
  4304. bytes[i] = str.charCodeAt(i) & 0xff;
  4305. }
  4306. return bytes;
  4307. }
  4308. function string32(value) {
  4309. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  4310. }
  4311. function objectSize(obj) {
  4312. return Object.keys(obj).length;
  4313. }
  4314. function isLittleEndian() {
  4315. const buffer8 = new Uint8Array(4);
  4316. buffer8[0] = 1;
  4317. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  4318. return view32[0] === 1;
  4319. }
  4320. function isEvalSupported() {
  4321. try {
  4322. new Function("");
  4323. return true;
  4324. } catch {
  4325. return false;
  4326. }
  4327. }
  4328. class util_FeatureTest {
  4329. static get isLittleEndian() {
  4330. return shadow(this, "isLittleEndian", isLittleEndian());
  4331. }
  4332. static get isEvalSupported() {
  4333. return shadow(this, "isEvalSupported", isEvalSupported());
  4334. }
  4335. static get isOffscreenCanvasSupported() {
  4336. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  4337. }
  4338. static get isImageDecoderSupported() {
  4339. return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined");
  4340. }
  4341. static get platform() {
  4342. const {
  4343. platform,
  4344. userAgent
  4345. } = navigator;
  4346. return shadow(this, "platform", {
  4347. isAndroid: userAgent.includes("Android"),
  4348. isLinux: platform.includes("Linux"),
  4349. isMac: platform.includes("Mac"),
  4350. isWindows: platform.includes("Win"),
  4351. isFirefox: userAgent.includes("Firefox")
  4352. });
  4353. }
  4354. static get isCSSRoundSupported() {
  4355. return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
  4356. }
  4357. }
  4358. const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));
  4359. class Util {
  4360. static makeHexColor(r, g, b) {
  4361. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  4362. }
  4363. static scaleMinMax(transform, minMax) {
  4364. let temp;
  4365. if (transform[0]) {
  4366. if (transform[0] < 0) {
  4367. temp = minMax[0];
  4368. minMax[0] = minMax[2];
  4369. minMax[2] = temp;
  4370. }
  4371. minMax[0] *= transform[0];
  4372. minMax[2] *= transform[0];
  4373. if (transform[3] < 0) {
  4374. temp = minMax[1];
  4375. minMax[1] = minMax[3];
  4376. minMax[3] = temp;
  4377. }
  4378. minMax[1] *= transform[3];
  4379. minMax[3] *= transform[3];
  4380. } else {
  4381. temp = minMax[0];
  4382. minMax[0] = minMax[1];
  4383. minMax[1] = temp;
  4384. temp = minMax[2];
  4385. minMax[2] = minMax[3];
  4386. minMax[3] = temp;
  4387. if (transform[1] < 0) {
  4388. temp = minMax[1];
  4389. minMax[1] = minMax[3];
  4390. minMax[3] = temp;
  4391. }
  4392. minMax[1] *= transform[1];
  4393. minMax[3] *= transform[1];
  4394. if (transform[2] < 0) {
  4395. temp = minMax[0];
  4396. minMax[0] = minMax[2];
  4397. minMax[2] = temp;
  4398. }
  4399. minMax[0] *= transform[2];
  4400. minMax[2] *= transform[2];
  4401. }
  4402. minMax[0] += transform[4];
  4403. minMax[1] += transform[5];
  4404. minMax[2] += transform[4];
  4405. minMax[3] += transform[5];
  4406. }
  4407. static transform(m1, m2) {
  4408. return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
  4409. }
  4410. static applyTransform(p, m, pos = 0) {
  4411. const p0 = p[pos];
  4412. const p1 = p[pos + 1];
  4413. p[pos] = p0 * m[0] + p1 * m[2] + m[4];
  4414. p[pos + 1] = p0 * m[1] + p1 * m[3] + m[5];
  4415. }
  4416. static applyTransformToBezier(p, transform, pos = 0) {
  4417. const m0 = transform[0];
  4418. const m1 = transform[1];
  4419. const m2 = transform[2];
  4420. const m3 = transform[3];
  4421. const m4 = transform[4];
  4422. const m5 = transform[5];
  4423. for (let i = 0; i < 6; i += 2) {
  4424. const pI = p[pos + i];
  4425. const pI1 = p[pos + i + 1];
  4426. p[pos + i] = pI * m0 + pI1 * m2 + m4;
  4427. p[pos + i + 1] = pI * m1 + pI1 * m3 + m5;
  4428. }
  4429. }
  4430. static applyInverseTransform(p, m) {
  4431. const p0 = p[0];
  4432. const p1 = p[1];
  4433. const d = m[0] * m[3] - m[1] * m[2];
  4434. p[0] = (p0 * m[3] - p1 * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  4435. p[1] = (-p0 * m[1] + p1 * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  4436. }
  4437. static axialAlignedBoundingBox(rect, transform, output) {
  4438. const m0 = transform[0];
  4439. const m1 = transform[1];
  4440. const m2 = transform[2];
  4441. const m3 = transform[3];
  4442. const m4 = transform[4];
  4443. const m5 = transform[5];
  4444. const r0 = rect[0];
  4445. const r1 = rect[1];
  4446. const r2 = rect[2];
  4447. const r3 = rect[3];
  4448. let a0 = m0 * r0 + m4;
  4449. let a2 = a0;
  4450. let a1 = m0 * r2 + m4;
  4451. let a3 = a1;
  4452. let b0 = m3 * r1 + m5;
  4453. let b2 = b0;
  4454. let b1 = m3 * r3 + m5;
  4455. let b3 = b1;
  4456. if (m1 !== 0 || m2 !== 0) {
  4457. const m1r0 = m1 * r0;
  4458. const m1r2 = m1 * r2;
  4459. const m2r1 = m2 * r1;
  4460. const m2r3 = m2 * r3;
  4461. a0 += m2r1;
  4462. a3 += m2r1;
  4463. a1 += m2r3;
  4464. a2 += m2r3;
  4465. b0 += m1r0;
  4466. b3 += m1r0;
  4467. b1 += m1r2;
  4468. b2 += m1r2;
  4469. }
  4470. output[0] = Math.min(output[0], a0, a1, a2, a3);
  4471. output[1] = Math.min(output[1], b0, b1, b2, b3);
  4472. output[2] = Math.max(output[2], a0, a1, a2, a3);
  4473. output[3] = Math.max(output[3], b0, b1, b2, b3);
  4474. }
  4475. static inverseTransform(m) {
  4476. const d = m[0] * m[3] - m[1] * m[2];
  4477. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  4478. }
  4479. static singularValueDecompose2dScale(matrix, output) {
  4480. const m0 = matrix[0];
  4481. const m1 = matrix[1];
  4482. const m2 = matrix[2];
  4483. const m3 = matrix[3];
  4484. const a = m0 ** 2 + m1 ** 2;
  4485. const b = m0 * m2 + m1 * m3;
  4486. const c = m2 ** 2 + m3 ** 2;
  4487. const first = (a + c) / 2;
  4488. const second = Math.sqrt(first ** 2 - (a * c - b ** 2));
  4489. output[0] = Math.sqrt(first + second || 1);
  4490. output[1] = Math.sqrt(first - second || 1);
  4491. }
  4492. static normalizeRect(rect) {
  4493. const r = rect.slice(0);
  4494. if (rect[0] > rect[2]) {
  4495. r[0] = rect[2];
  4496. r[2] = rect[0];
  4497. }
  4498. if (rect[1] > rect[3]) {
  4499. r[1] = rect[3];
  4500. r[3] = rect[1];
  4501. }
  4502. return r;
  4503. }
  4504. static intersect(rect1, rect2) {
  4505. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  4506. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  4507. if (xLow > xHigh) {
  4508. return null;
  4509. }
  4510. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  4511. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  4512. if (yLow > yHigh) {
  4513. return null;
  4514. }
  4515. return [xLow, yLow, xHigh, yHigh];
  4516. }
  4517. static pointBoundingBox(x, y, minMax) {
  4518. minMax[0] = Math.min(minMax[0], x);
  4519. minMax[1] = Math.min(minMax[1], y);
  4520. minMax[2] = Math.max(minMax[2], x);
  4521. minMax[3] = Math.max(minMax[3], y);
  4522. }
  4523. static rectBoundingBox(x0, y0, x1, y1, minMax) {
  4524. minMax[0] = Math.min(minMax[0], x0, x1);
  4525. minMax[1] = Math.min(minMax[1], y0, y1);
  4526. minMax[2] = Math.max(minMax[2], x0, x1);
  4527. minMax[3] = Math.max(minMax[3], y0, y1);
  4528. }
  4529. static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {
  4530. if (t <= 0 || t >= 1) {
  4531. return;
  4532. }
  4533. const mt = 1 - t;
  4534. const tt = t * t;
  4535. const ttt = tt * t;
  4536. const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;
  4537. const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;
  4538. minMax[0] = Math.min(minMax[0], x);
  4539. minMax[1] = Math.min(minMax[1], y);
  4540. minMax[2] = Math.max(minMax[2], x);
  4541. minMax[3] = Math.max(minMax[3], y);
  4542. }
  4543. static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {
  4544. if (Math.abs(a) < 1e-12) {
  4545. if (Math.abs(b) >= 1e-12) {
  4546. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);
  4547. }
  4548. return;
  4549. }
  4550. const delta = b ** 2 - 4 * c * a;
  4551. if (delta < 0) {
  4552. return;
  4553. }
  4554. const sqrtDelta = Math.sqrt(delta);
  4555. const a2 = 2 * a;
  4556. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);
  4557. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);
  4558. }
  4559. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  4560. minMax[0] = Math.min(minMax[0], x0, x3);
  4561. minMax[1] = Math.min(minMax[1], y0, y3);
  4562. minMax[2] = Math.max(minMax[2], x0, x3);
  4563. minMax[3] = Math.max(minMax[3], y0, y3);
  4564. this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax);
  4565. this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax);
  4566. }
  4567. }
  4568. const PDFStringTranslateTable = (/* unused pure expression or super */ null && ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac]));
  4569. function stringToPDFString(str, keepEscapeSequence = false) {
  4570. if (str[0] >= "\xEF") {
  4571. let encoding;
  4572. if (str[0] === "\xFE" && str[1] === "\xFF") {
  4573. encoding = "utf-16be";
  4574. if (str.length % 2 === 1) {
  4575. str = str.slice(0, -1);
  4576. }
  4577. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  4578. encoding = "utf-16le";
  4579. if (str.length % 2 === 1) {
  4580. str = str.slice(0, -1);
  4581. }
  4582. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  4583. encoding = "utf-8";
  4584. }
  4585. if (encoding) {
  4586. try {
  4587. const decoder = new TextDecoder(encoding, {
  4588. fatal: true
  4589. });
  4590. const buffer = stringToBytes(str);
  4591. const decoded = decoder.decode(buffer);
  4592. if (keepEscapeSequence || !decoded.includes("\x1b")) {
  4593. return decoded;
  4594. }
  4595. return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, "");
  4596. } catch (ex) {
  4597. warn(`stringToPDFString: "${ex}".`);
  4598. }
  4599. }
  4600. }
  4601. const strBuf = [];
  4602. for (let i = 0, ii = str.length; i < ii; i++) {
  4603. const charCode = str.charCodeAt(i);
  4604. if (!keepEscapeSequence && charCode === 0x1b) {
  4605. while (++i < ii && str.charCodeAt(i) !== 0x1b) {}
  4606. continue;
  4607. }
  4608. const code = PDFStringTranslateTable[charCode];
  4609. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  4610. }
  4611. return strBuf.join("");
  4612. }
  4613. function stringToUTF8String(str) {
  4614. return decodeURIComponent(escape(str));
  4615. }
  4616. function utf8StringToString(str) {
  4617. return unescape(encodeURIComponent(str));
  4618. }
  4619. function isArrayEqual(arr1, arr2) {
  4620. if (arr1.length !== arr2.length) {
  4621. return false;
  4622. }
  4623. for (let i = 0, ii = arr1.length; i < ii; i++) {
  4624. if (arr1[i] !== arr2[i]) {
  4625. return false;
  4626. }
  4627. }
  4628. return true;
  4629. }
  4630. function getModificationDate(date = new Date()) {
  4631. const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
  4632. return buffer.join("");
  4633. }
  4634. let NormalizeRegex = null;
  4635. let NormalizationMap = null;
  4636. function normalizeUnicode(str) {
  4637. if (!NormalizeRegex) {
  4638. NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;
  4639. NormalizationMap = new Map([["ſt", "ſt"]]);
  4640. }
  4641. return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));
  4642. }
  4643. function getUuid() {
  4644. if (typeof crypto.randomUUID === "function") {
  4645. return crypto.randomUUID();
  4646. }
  4647. const buf = new Uint8Array(32);
  4648. crypto.getRandomValues(buf);
  4649. return bytesToString(buf);
  4650. }
  4651. const AnnotationPrefix = "pdfjs_internal_id_";
  4652. function _isValidExplicitDest(validRef, validName, dest) {
  4653. if (!Array.isArray(dest) || dest.length < 2) {
  4654. return false;
  4655. }
  4656. const [page, zoom, ...args] = dest;
  4657. if (!validRef(page) && !Number.isInteger(page)) {
  4658. return false;
  4659. }
  4660. if (!validName(zoom)) {
  4661. return false;
  4662. }
  4663. const argsLen = args.length;
  4664. let allowNull = true;
  4665. switch (zoom.name) {
  4666. case "XYZ":
  4667. if (argsLen < 2 || argsLen > 3) {
  4668. return false;
  4669. }
  4670. break;
  4671. case "Fit":
  4672. case "FitB":
  4673. return argsLen === 0;
  4674. case "FitH":
  4675. case "FitBH":
  4676. case "FitV":
  4677. case "FitBV":
  4678. if (argsLen > 1) {
  4679. return false;
  4680. }
  4681. break;
  4682. case "FitR":
  4683. if (argsLen !== 4) {
  4684. return false;
  4685. }
  4686. allowNull = false;
  4687. break;
  4688. default:
  4689. return false;
  4690. }
  4691. for (const arg of args) {
  4692. if (typeof arg === "number" || allowNull && arg === null) {
  4693. continue;
  4694. }
  4695. return false;
  4696. }
  4697. return true;
  4698. }
  4699. function MathClamp(v, min, max) {
  4700. return Math.min(Math.max(v, min), max);
  4701. }
  4702. function toHexUtil(arr) {
  4703. if (Uint8Array.prototype.toHex) {
  4704. return arr.toHex();
  4705. }
  4706. return Array.from(arr, num => hexNumbers[num]).join("");
  4707. }
  4708. function toBase64Util(arr) {
  4709. if (Uint8Array.prototype.toBase64) {
  4710. return arr.toBase64();
  4711. }
  4712. return btoa(bytesToString(arr));
  4713. }
  4714. function fromBase64Util(str) {
  4715. if (Uint8Array.fromBase64) {
  4716. return Uint8Array.fromBase64(str);
  4717. }
  4718. return stringToBytes(atob(str));
  4719. }
  4720. if (typeof Math.sumPrecise !== "function") {
  4721. Math.sumPrecise = function (numbers) {
  4722. return numbers.reduce((a, b) => a + b, 0);
  4723. };
  4724. }
  4725. if (typeof AbortSignal.any !== "function") {
  4726. AbortSignal.any = function (iterable) {
  4727. const ac = new AbortController();
  4728. const {
  4729. signal
  4730. } = ac;
  4731. for (const s of iterable) {
  4732. if (s.aborted) {
  4733. ac.abort(s.reason);
  4734. return signal;
  4735. }
  4736. }
  4737. for (const s of iterable) {
  4738. s.addEventListener("abort", () => {
  4739. ac.abort(s.reason);
  4740. }, {
  4741. signal
  4742. });
  4743. }
  4744. return signal;
  4745. };
  4746. }
  4747. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.map.js
  4748. var es_iterator_map = __webpack_require__(1701);
  4749. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.with-resolvers.js
  4750. var es_promise_with_resolvers = __webpack_require__(4628);
  4751. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.difference.v2.js
  4752. var es_set_difference_v2 = __webpack_require__(7642);
  4753. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.intersection.v2.js
  4754. var es_set_intersection_v2 = __webpack_require__(8004);
  4755. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-disjoint-from.v2.js
  4756. var es_set_is_disjoint_from_v2 = __webpack_require__(3853);
  4757. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-subset-of.v2.js
  4758. var es_set_is_subset_of_v2 = __webpack_require__(5876);
  4759. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-superset-of.v2.js
  4760. var es_set_is_superset_of_v2 = __webpack_require__(2475);
  4761. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.symmetric-difference.v2.js
  4762. var es_set_symmetric_difference_v2 = __webpack_require__(5024);
  4763. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.union.v2.js
  4764. var es_set_union_v2 = __webpack_require__(1698);
  4765. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.delete.js
  4766. var web_url_search_params_delete = __webpack_require__(4603);
  4767. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.has.js
  4768. var web_url_search_params_has = __webpack_require__(7566);
  4769. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.size.js
  4770. var web_url_search_params_size = __webpack_require__(8721);
  4771. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.drop.js
  4772. var es_iterator_drop = __webpack_require__(9314);
  4773. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.every.js
  4774. var es_iterator_every = __webpack_require__(1148);
  4775. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.some.js
  4776. var es_iterator_some = __webpack_require__(3579);
  4777. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.json.parse.js
  4778. var esnext_json_parse = __webpack_require__(8335);
  4779. ;// ./src/display/display_utils.js
  4780. const SVG_NS = "http://www.w3.org/2000/svg";
  4781. class PixelsPerInch {
  4782. static CSS = 96.0;
  4783. static PDF = 72.0;
  4784. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  4785. }
  4786. async function fetchData(url, type = "text") {
  4787. if (isValidFetchUrl(url, document.baseURI)) {
  4788. const response = await fetch(url);
  4789. if (!response.ok) {
  4790. throw new Error(response.statusText);
  4791. }
  4792. switch (type) {
  4793. case "arraybuffer":
  4794. return response.arrayBuffer();
  4795. case "blob":
  4796. return response.blob();
  4797. case "json":
  4798. return response.json();
  4799. }
  4800. return response.text();
  4801. }
  4802. return new Promise((resolve, reject) => {
  4803. const request = new XMLHttpRequest();
  4804. request.open("GET", url, true);
  4805. request.responseType = type;
  4806. request.onreadystatechange = () => {
  4807. if (request.readyState !== XMLHttpRequest.DONE) {
  4808. return;
  4809. }
  4810. if (request.status === 200 || request.status === 0) {
  4811. switch (type) {
  4812. case "arraybuffer":
  4813. case "blob":
  4814. case "json":
  4815. resolve(request.response);
  4816. return;
  4817. }
  4818. resolve(request.responseText);
  4819. return;
  4820. }
  4821. reject(new Error(request.statusText));
  4822. };
  4823. request.send(null);
  4824. });
  4825. }
  4826. class PageViewport {
  4827. constructor({
  4828. viewBox,
  4829. userUnit,
  4830. scale,
  4831. rotation,
  4832. offsetX = 0,
  4833. offsetY = 0,
  4834. dontFlip = false
  4835. }) {
  4836. this.viewBox = viewBox;
  4837. this.userUnit = userUnit;
  4838. this.scale = scale;
  4839. this.rotation = rotation;
  4840. this.offsetX = offsetX;
  4841. this.offsetY = offsetY;
  4842. scale *= userUnit;
  4843. const centerX = (viewBox[2] + viewBox[0]) / 2;
  4844. const centerY = (viewBox[3] + viewBox[1]) / 2;
  4845. let rotateA, rotateB, rotateC, rotateD;
  4846. rotation %= 360;
  4847. if (rotation < 0) {
  4848. rotation += 360;
  4849. }
  4850. switch (rotation) {
  4851. case 180:
  4852. rotateA = -1;
  4853. rotateB = 0;
  4854. rotateC = 0;
  4855. rotateD = 1;
  4856. break;
  4857. case 90:
  4858. rotateA = 0;
  4859. rotateB = 1;
  4860. rotateC = 1;
  4861. rotateD = 0;
  4862. break;
  4863. case 270:
  4864. rotateA = 0;
  4865. rotateB = -1;
  4866. rotateC = -1;
  4867. rotateD = 0;
  4868. break;
  4869. case 0:
  4870. rotateA = 1;
  4871. rotateB = 0;
  4872. rotateC = 0;
  4873. rotateD = -1;
  4874. break;
  4875. default:
  4876. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  4877. }
  4878. if (dontFlip) {
  4879. rotateC = -rotateC;
  4880. rotateD = -rotateD;
  4881. }
  4882. let offsetCanvasX, offsetCanvasY;
  4883. let width, height;
  4884. if (rotateA === 0) {
  4885. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  4886. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  4887. width = (viewBox[3] - viewBox[1]) * scale;
  4888. height = (viewBox[2] - viewBox[0]) * scale;
  4889. } else {
  4890. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  4891. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  4892. width = (viewBox[2] - viewBox[0]) * scale;
  4893. height = (viewBox[3] - viewBox[1]) * scale;
  4894. }
  4895. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  4896. this.width = width;
  4897. this.height = height;
  4898. }
  4899. get rawDims() {
  4900. const dims = this.viewBox;
  4901. return shadow(this, "rawDims", {
  4902. pageWidth: dims[2] - dims[0],
  4903. pageHeight: dims[3] - dims[1],
  4904. pageX: dims[0],
  4905. pageY: dims[1]
  4906. });
  4907. }
  4908. clone({
  4909. scale = this.scale,
  4910. rotation = this.rotation,
  4911. offsetX = this.offsetX,
  4912. offsetY = this.offsetY,
  4913. dontFlip = false
  4914. } = {}) {
  4915. return new PageViewport({
  4916. viewBox: this.viewBox.slice(),
  4917. userUnit: this.userUnit,
  4918. scale,
  4919. rotation,
  4920. offsetX,
  4921. offsetY,
  4922. dontFlip
  4923. });
  4924. }
  4925. convertToViewportPoint(x, y) {
  4926. const p = [x, y];
  4927. Util.applyTransform(p, this.transform);
  4928. return p;
  4929. }
  4930. convertToViewportRectangle(rect) {
  4931. const topLeft = [rect[0], rect[1]];
  4932. Util.applyTransform(topLeft, this.transform);
  4933. const bottomRight = [rect[2], rect[3]];
  4934. Util.applyTransform(bottomRight, this.transform);
  4935. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  4936. }
  4937. convertToPdfPoint(x, y) {
  4938. const p = [x, y];
  4939. Util.applyInverseTransform(p, this.transform);
  4940. return p;
  4941. }
  4942. }
  4943. class RenderingCancelledException extends BaseException {
  4944. constructor(msg, extraDelay = 0) {
  4945. super(msg, "RenderingCancelledException");
  4946. this.extraDelay = extraDelay;
  4947. }
  4948. }
  4949. function isDataScheme(url) {
  4950. const ii = url.length;
  4951. let i = 0;
  4952. while (i < ii && url[i].trim() === "") {
  4953. i++;
  4954. }
  4955. return url.substring(i, i + 5).toLowerCase() === "data:";
  4956. }
  4957. function isPdfFile(filename) {
  4958. return typeof filename === "string" && /\.pdf$/i.test(filename);
  4959. }
  4960. function getFilenameFromUrl(url) {
  4961. [url] = url.split(/[#?]/, 1);
  4962. return url.substring(url.lastIndexOf("/") + 1);
  4963. }
  4964. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  4965. if (typeof url !== "string") {
  4966. return defaultFilename;
  4967. }
  4968. if (isDataScheme(url)) {
  4969. warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  4970. return defaultFilename;
  4971. }
  4972. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  4973. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  4974. const splitURI = reURI.exec(url);
  4975. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  4976. if (suggestedFilename) {
  4977. suggestedFilename = suggestedFilename[0];
  4978. if (suggestedFilename.includes("%")) {
  4979. try {
  4980. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  4981. } catch {}
  4982. }
  4983. }
  4984. return suggestedFilename || defaultFilename;
  4985. }
  4986. class StatTimer {
  4987. started = Object.create(null);
  4988. times = [];
  4989. time(name) {
  4990. if (name in this.started) {
  4991. warn(`Timer is already running for ${name}`);
  4992. }
  4993. this.started[name] = Date.now();
  4994. }
  4995. timeEnd(name) {
  4996. if (!(name in this.started)) {
  4997. warn(`Timer has not been started for ${name}`);
  4998. }
  4999. this.times.push({
  5000. name,
  5001. start: this.started[name],
  5002. end: Date.now()
  5003. });
  5004. delete this.started[name];
  5005. }
  5006. toString() {
  5007. const outBuf = [];
  5008. let longest = 0;
  5009. for (const {
  5010. name
  5011. } of this.times) {
  5012. longest = Math.max(name.length, longest);
  5013. }
  5014. for (const {
  5015. name,
  5016. start,
  5017. end
  5018. } of this.times) {
  5019. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  5020. }
  5021. return outBuf.join("");
  5022. }
  5023. }
  5024. function isValidFetchUrl(url, baseUrl) {
  5025. const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
  5026. return res?.protocol === "http:" || res?.protocol === "https:";
  5027. }
  5028. function noContextMenu(e) {
  5029. e.preventDefault();
  5030. }
  5031. function stopEvent(e) {
  5032. e.preventDefault();
  5033. e.stopPropagation();
  5034. }
  5035. function deprecated(details) {
  5036. console.log("Deprecated API usage: " + details);
  5037. }
  5038. class PDFDateString {
  5039. static #regex;
  5040. static toDateObject(input) {
  5041. if (!input || typeof input !== "string") {
  5042. return null;
  5043. }
  5044. this.#regex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  5045. const matches = this.#regex.exec(input);
  5046. if (!matches) {
  5047. return null;
  5048. }
  5049. const year = parseInt(matches[1], 10);
  5050. let month = parseInt(matches[2], 10);
  5051. month = month >= 1 && month <= 12 ? month - 1 : 0;
  5052. let day = parseInt(matches[3], 10);
  5053. day = day >= 1 && day <= 31 ? day : 1;
  5054. let hour = parseInt(matches[4], 10);
  5055. hour = hour >= 0 && hour <= 23 ? hour : 0;
  5056. let minute = parseInt(matches[5], 10);
  5057. minute = minute >= 0 && minute <= 59 ? minute : 0;
  5058. let second = parseInt(matches[6], 10);
  5059. second = second >= 0 && second <= 59 ? second : 0;
  5060. const universalTimeRelation = matches[7] || "Z";
  5061. let offsetHour = parseInt(matches[8], 10);
  5062. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  5063. let offsetMinute = parseInt(matches[9], 10) || 0;
  5064. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  5065. if (universalTimeRelation === "-") {
  5066. hour += offsetHour;
  5067. minute += offsetMinute;
  5068. } else if (universalTimeRelation === "+") {
  5069. hour -= offsetHour;
  5070. minute -= offsetMinute;
  5071. }
  5072. return new Date(Date.UTC(year, month, day, hour, minute, second));
  5073. }
  5074. }
  5075. function getXfaPageViewport(xfaPage, {
  5076. scale = 1,
  5077. rotation = 0
  5078. }) {
  5079. const {
  5080. width,
  5081. height
  5082. } = xfaPage.attributes.style;
  5083. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  5084. return new PageViewport({
  5085. viewBox,
  5086. userUnit: 1,
  5087. scale,
  5088. rotation
  5089. });
  5090. }
  5091. function getRGB(color) {
  5092. if (color.startsWith("#")) {
  5093. const colorRGB = parseInt(color.slice(1), 16);
  5094. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  5095. }
  5096. if (color.startsWith("rgb(")) {
  5097. return color.slice(4, -1).split(",").map(x => parseInt(x));
  5098. }
  5099. if (color.startsWith("rgba(")) {
  5100. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  5101. }
  5102. warn(`Not a valid color format: "${color}"`);
  5103. return [0, 0, 0];
  5104. }
  5105. function getColorValues(colors) {
  5106. const span = document.createElement("span");
  5107. span.style.visibility = "hidden";
  5108. span.style.colorScheme = "only light";
  5109. document.body.append(span);
  5110. for (const name of colors.keys()) {
  5111. span.style.color = name;
  5112. const computedColor = window.getComputedStyle(span).color;
  5113. colors.set(name, getRGB(computedColor));
  5114. }
  5115. span.remove();
  5116. }
  5117. function getCurrentTransform(ctx) {
  5118. const {
  5119. a,
  5120. b,
  5121. c,
  5122. d,
  5123. e,
  5124. f
  5125. } = ctx.getTransform();
  5126. return [a, b, c, d, e, f];
  5127. }
  5128. function getCurrentTransformInverse(ctx) {
  5129. const {
  5130. a,
  5131. b,
  5132. c,
  5133. d,
  5134. e,
  5135. f
  5136. } = ctx.getTransform().invertSelf();
  5137. return [a, b, c, d, e, f];
  5138. }
  5139. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  5140. if (viewport instanceof PageViewport) {
  5141. const {
  5142. pageWidth,
  5143. pageHeight
  5144. } = viewport.rawDims;
  5145. const {
  5146. style
  5147. } = div;
  5148. const useRound = util_FeatureTest.isCSSRoundSupported;
  5149. const w = `var(--total-scale-factor) * ${pageWidth}px`,
  5150. h = `var(--total-scale-factor) * ${pageHeight}px`;
  5151. const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x))` : `calc(${w})`,
  5152. heightStr = useRound ? `round(down, ${h}, var(--scale-round-y))` : `calc(${h})`;
  5153. if (!mustFlip || viewport.rotation % 180 === 0) {
  5154. style.width = widthStr;
  5155. style.height = heightStr;
  5156. } else {
  5157. style.width = heightStr;
  5158. style.height = widthStr;
  5159. }
  5160. }
  5161. if (mustRotate) {
  5162. div.setAttribute("data-main-rotation", viewport.rotation);
  5163. }
  5164. }
  5165. class OutputScale {
  5166. constructor() {
  5167. const {
  5168. pixelRatio
  5169. } = OutputScale;
  5170. this.sx = pixelRatio;
  5171. this.sy = pixelRatio;
  5172. }
  5173. get scaled() {
  5174. return this.sx !== 1 || this.sy !== 1;
  5175. }
  5176. get symmetric() {
  5177. return this.sx === this.sy;
  5178. }
  5179. limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) {
  5180. let maxAreaScale = Infinity,
  5181. maxWidthScale = Infinity,
  5182. maxHeightScale = Infinity;
  5183. maxPixels = OutputScale.capPixels(maxPixels, capAreaFactor);
  5184. if (maxPixels > 0) {
  5185. maxAreaScale = Math.sqrt(maxPixels / (width * height));
  5186. }
  5187. if (maxDim !== -1) {
  5188. maxWidthScale = maxDim / width;
  5189. maxHeightScale = maxDim / height;
  5190. }
  5191. const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale);
  5192. if (this.sx > maxScale || this.sy > maxScale) {
  5193. this.sx = maxScale;
  5194. this.sy = maxScale;
  5195. return true;
  5196. }
  5197. return false;
  5198. }
  5199. static get pixelRatio() {
  5200. return globalThis.devicePixelRatio || 1;
  5201. }
  5202. static capPixels(maxPixels, capAreaFactor) {
  5203. if (capAreaFactor >= 0) {
  5204. const winPixels = Math.ceil(window.screen.availWidth * window.screen.availHeight * this.pixelRatio ** 2 * (1 + capAreaFactor / 100));
  5205. return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels;
  5206. }
  5207. return maxPixels;
  5208. }
  5209. }
  5210. const SupportedImageMimeTypes = ["image/apng", "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/webp", "image/x-icon"];
  5211. ;// ./src/display/editor/toolbar.js
  5212. class EditorToolbar {
  5213. #toolbar = null;
  5214. #colorPicker = null;
  5215. #editor;
  5216. #buttons = null;
  5217. #altText = null;
  5218. #signatureDescriptionButton = null;
  5219. static #l10nRemove = null;
  5220. constructor(editor) {
  5221. this.#editor = editor;
  5222. EditorToolbar.#l10nRemove ||= Object.freeze({
  5223. freetext: "pdfjs-editor-remove-freetext-button",
  5224. highlight: "pdfjs-editor-remove-highlight-button",
  5225. ink: "pdfjs-editor-remove-ink-button",
  5226. stamp: "pdfjs-editor-remove-stamp-button",
  5227. signature: "pdfjs-editor-remove-signature-button"
  5228. });
  5229. }
  5230. render() {
  5231. const editToolbar = this.#toolbar = document.createElement("div");
  5232. editToolbar.classList.add("editToolbar", "hidden");
  5233. editToolbar.setAttribute("role", "toolbar");
  5234. const signal = this.#editor._uiManager._signal;
  5235. editToolbar.addEventListener("contextmenu", noContextMenu, {
  5236. signal
  5237. });
  5238. editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, {
  5239. signal
  5240. });
  5241. const buttons = this.#buttons = document.createElement("div");
  5242. buttons.className = "buttons";
  5243. editToolbar.append(buttons);
  5244. const position = this.#editor.toolbarPosition;
  5245. if (position) {
  5246. const {
  5247. style
  5248. } = editToolbar;
  5249. const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
  5250. style.insetInlineEnd = `${100 * x}%`;
  5251. style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
  5252. }
  5253. this.#addDeleteButton();
  5254. return editToolbar;
  5255. }
  5256. get div() {
  5257. return this.#toolbar;
  5258. }
  5259. static #pointerDown(e) {
  5260. e.stopPropagation();
  5261. }
  5262. #focusIn(e) {
  5263. this.#editor._focusEventsAllowed = false;
  5264. stopEvent(e);
  5265. }
  5266. #focusOut(e) {
  5267. this.#editor._focusEventsAllowed = true;
  5268. stopEvent(e);
  5269. }
  5270. #addListenersToElement(element) {
  5271. const signal = this.#editor._uiManager._signal;
  5272. element.addEventListener("focusin", this.#focusIn.bind(this), {
  5273. capture: true,
  5274. signal
  5275. });
  5276. element.addEventListener("focusout", this.#focusOut.bind(this), {
  5277. capture: true,
  5278. signal
  5279. });
  5280. element.addEventListener("contextmenu", noContextMenu, {
  5281. signal
  5282. });
  5283. }
  5284. hide() {
  5285. this.#toolbar.classList.add("hidden");
  5286. this.#colorPicker?.hideDropdown();
  5287. }
  5288. show() {
  5289. this.#toolbar.classList.remove("hidden");
  5290. this.#altText?.shown();
  5291. }
  5292. #addDeleteButton() {
  5293. const {
  5294. editorType,
  5295. _uiManager
  5296. } = this.#editor;
  5297. const button = document.createElement("button");
  5298. button.className = "delete";
  5299. button.tabIndex = 0;
  5300. button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]);
  5301. this.#addListenersToElement(button);
  5302. button.addEventListener("click", e => {
  5303. _uiManager.delete();
  5304. }, {
  5305. signal: _uiManager._signal
  5306. });
  5307. this.#buttons.append(button);
  5308. }
  5309. get #divider() {
  5310. const divider = document.createElement("div");
  5311. divider.className = "divider";
  5312. return divider;
  5313. }
  5314. async addAltText(altText) {
  5315. const button = await altText.render();
  5316. this.#addListenersToElement(button);
  5317. this.#buttons.prepend(button, this.#divider);
  5318. this.#altText = altText;
  5319. }
  5320. addColorPicker(colorPicker) {
  5321. this.#colorPicker = colorPicker;
  5322. const button = colorPicker.renderButton();
  5323. this.#addListenersToElement(button);
  5324. this.#buttons.prepend(button, this.#divider);
  5325. }
  5326. async addEditSignatureButton(signatureManager) {
  5327. const button = this.#signatureDescriptionButton = await signatureManager.renderEditButton(this.#editor);
  5328. this.#addListenersToElement(button);
  5329. this.#buttons.prepend(button, this.#divider);
  5330. }
  5331. updateEditSignatureButton(description) {
  5332. if (this.#signatureDescriptionButton) {
  5333. this.#signatureDescriptionButton.title = description;
  5334. }
  5335. }
  5336. remove() {
  5337. this.#toolbar.remove();
  5338. this.#colorPicker?.destroy();
  5339. this.#colorPicker = null;
  5340. }
  5341. }
  5342. class HighlightToolbar {
  5343. #buttons = null;
  5344. #toolbar = null;
  5345. #uiManager;
  5346. constructor(uiManager) {
  5347. this.#uiManager = uiManager;
  5348. }
  5349. #render() {
  5350. const editToolbar = this.#toolbar = document.createElement("div");
  5351. editToolbar.className = "editToolbar";
  5352. editToolbar.setAttribute("role", "toolbar");
  5353. editToolbar.addEventListener("contextmenu", noContextMenu, {
  5354. signal: this.#uiManager._signal
  5355. });
  5356. const buttons = this.#buttons = document.createElement("div");
  5357. buttons.className = "buttons";
  5358. editToolbar.append(buttons);
  5359. this.#addHighlightButton();
  5360. return editToolbar;
  5361. }
  5362. #getLastPoint(boxes, isLTR) {
  5363. let lastY = 0;
  5364. let lastX = 0;
  5365. for (const box of boxes) {
  5366. const y = box.y + box.height;
  5367. if (y < lastY) {
  5368. continue;
  5369. }
  5370. const x = box.x + (isLTR ? box.width : 0);
  5371. if (y > lastY) {
  5372. lastX = x;
  5373. lastY = y;
  5374. continue;
  5375. }
  5376. if (isLTR) {
  5377. if (x > lastX) {
  5378. lastX = x;
  5379. }
  5380. } else if (x < lastX) {
  5381. lastX = x;
  5382. }
  5383. }
  5384. return [isLTR ? 1 - lastX : lastX, lastY];
  5385. }
  5386. show(parent, boxes, isLTR) {
  5387. const [x, y] = this.#getLastPoint(boxes, isLTR);
  5388. const {
  5389. style
  5390. } = this.#toolbar ||= this.#render();
  5391. parent.append(this.#toolbar);
  5392. style.insetInlineEnd = `${100 * x}%`;
  5393. style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;
  5394. }
  5395. hide() {
  5396. this.#toolbar.remove();
  5397. }
  5398. #addHighlightButton() {
  5399. const button = document.createElement("button");
  5400. button.className = "highlightButton";
  5401. button.tabIndex = 0;
  5402. button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`);
  5403. const span = document.createElement("span");
  5404. button.append(span);
  5405. span.className = "visuallyHidden";
  5406. span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label");
  5407. const signal = this.#uiManager._signal;
  5408. button.addEventListener("contextmenu", noContextMenu, {
  5409. signal
  5410. });
  5411. button.addEventListener("click", () => {
  5412. this.#uiManager.highlightSelection("floating_button");
  5413. }, {
  5414. signal
  5415. });
  5416. this.#buttons.append(button);
  5417. }
  5418. }
  5419. ;// ./src/display/editor/tools.js
  5420. function bindEvents(obj, element, names) {
  5421. for (const name of names) {
  5422. element.addEventListener(name, obj[name].bind(obj));
  5423. }
  5424. }
  5425. class IdManager {
  5426. #id = 0;
  5427. get id() {
  5428. return `${AnnotationEditorPrefix}${this.#id++}`;
  5429. }
  5430. }
  5431. class ImageManager {
  5432. #baseId = getUuid();
  5433. #id = 0;
  5434. #cache = null;
  5435. static get _isSVGFittingCanvas() {
  5436. const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;
  5437. const canvas = new OffscreenCanvas(1, 3);
  5438. const ctx = canvas.getContext("2d", {
  5439. willReadFrequently: true
  5440. });
  5441. const image = new Image();
  5442. image.src = svg;
  5443. const promise = image.decode().then(() => {
  5444. ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
  5445. return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
  5446. });
  5447. return shadow(this, "_isSVGFittingCanvas", promise);
  5448. }
  5449. async #get(key, rawData) {
  5450. this.#cache ||= new Map();
  5451. let data = this.#cache.get(key);
  5452. if (data === null) {
  5453. return null;
  5454. }
  5455. if (data?.bitmap) {
  5456. data.refCounter += 1;
  5457. return data;
  5458. }
  5459. try {
  5460. data ||= {
  5461. bitmap: null,
  5462. id: `image_${this.#baseId}_${this.#id++}`,
  5463. refCounter: 0,
  5464. isSvg: false
  5465. };
  5466. let image;
  5467. if (typeof rawData === "string") {
  5468. data.url = rawData;
  5469. image = await fetchData(rawData, "blob");
  5470. } else if (rawData instanceof File) {
  5471. image = data.file = rawData;
  5472. } else if (rawData instanceof Blob) {
  5473. image = rawData;
  5474. }
  5475. if (image.type === "image/svg+xml") {
  5476. const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;
  5477. const fileReader = new FileReader();
  5478. const imageElement = new Image();
  5479. const imagePromise = new Promise((resolve, reject) => {
  5480. imageElement.onload = () => {
  5481. data.bitmap = imageElement;
  5482. data.isSvg = true;
  5483. resolve();
  5484. };
  5485. fileReader.onload = async () => {
  5486. const url = data.svgUrl = fileReader.result;
  5487. imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;
  5488. };
  5489. imageElement.onerror = fileReader.onerror = reject;
  5490. });
  5491. fileReader.readAsDataURL(image);
  5492. await imagePromise;
  5493. } else {
  5494. data.bitmap = await createImageBitmap(image);
  5495. }
  5496. data.refCounter = 1;
  5497. } catch (e) {
  5498. warn(e);
  5499. data = null;
  5500. }
  5501. this.#cache.set(key, data);
  5502. if (data) {
  5503. this.#cache.set(data.id, data);
  5504. }
  5505. return data;
  5506. }
  5507. async getFromFile(file) {
  5508. const {
  5509. lastModified,
  5510. name,
  5511. size,
  5512. type
  5513. } = file;
  5514. return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
  5515. }
  5516. async getFromUrl(url) {
  5517. return this.#get(url, url);
  5518. }
  5519. async getFromBlob(id, blobPromise) {
  5520. const blob = await blobPromise;
  5521. return this.#get(id, blob);
  5522. }
  5523. async getFromId(id) {
  5524. this.#cache ||= new Map();
  5525. const data = this.#cache.get(id);
  5526. if (!data) {
  5527. return null;
  5528. }
  5529. if (data.bitmap) {
  5530. data.refCounter += 1;
  5531. return data;
  5532. }
  5533. if (data.file) {
  5534. return this.getFromFile(data.file);
  5535. }
  5536. if (data.blobPromise) {
  5537. const {
  5538. blobPromise
  5539. } = data;
  5540. delete data.blobPromise;
  5541. return this.getFromBlob(data.id, blobPromise);
  5542. }
  5543. return this.getFromUrl(data.url);
  5544. }
  5545. getFromCanvas(id, canvas) {
  5546. this.#cache ||= new Map();
  5547. let data = this.#cache.get(id);
  5548. if (data?.bitmap) {
  5549. data.refCounter += 1;
  5550. return data;
  5551. }
  5552. const offscreen = new OffscreenCanvas(canvas.width, canvas.height);
  5553. const ctx = offscreen.getContext("2d");
  5554. ctx.drawImage(canvas, 0, 0);
  5555. data = {
  5556. bitmap: offscreen.transferToImageBitmap(),
  5557. id: `image_${this.#baseId}_${this.#id++}`,
  5558. refCounter: 1,
  5559. isSvg: false
  5560. };
  5561. this.#cache.set(id, data);
  5562. this.#cache.set(data.id, data);
  5563. return data;
  5564. }
  5565. getSvgUrl(id) {
  5566. const data = this.#cache.get(id);
  5567. if (!data?.isSvg) {
  5568. return null;
  5569. }
  5570. return data.svgUrl;
  5571. }
  5572. deleteId(id) {
  5573. this.#cache ||= new Map();
  5574. const data = this.#cache.get(id);
  5575. if (!data) {
  5576. return;
  5577. }
  5578. data.refCounter -= 1;
  5579. if (data.refCounter !== 0) {
  5580. return;
  5581. }
  5582. const {
  5583. bitmap
  5584. } = data;
  5585. if (!data.url && !data.file) {
  5586. const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
  5587. const ctx = canvas.getContext("bitmaprenderer");
  5588. ctx.transferFromImageBitmap(bitmap);
  5589. data.blobPromise = canvas.convertToBlob();
  5590. }
  5591. bitmap.close?.();
  5592. data.bitmap = null;
  5593. }
  5594. isValidId(id) {
  5595. return id.startsWith(`image_${this.#baseId}_`);
  5596. }
  5597. }
  5598. class CommandManager {
  5599. #commands = [];
  5600. #locked = false;
  5601. #maxSize;
  5602. #position = -1;
  5603. constructor(maxSize = 128) {
  5604. this.#maxSize = maxSize;
  5605. }
  5606. add({
  5607. cmd,
  5608. undo,
  5609. post,
  5610. mustExec,
  5611. type = NaN,
  5612. overwriteIfSameType = false,
  5613. keepUndo = false
  5614. }) {
  5615. if (mustExec) {
  5616. cmd();
  5617. }
  5618. if (this.#locked) {
  5619. return;
  5620. }
  5621. const save = {
  5622. cmd,
  5623. undo,
  5624. post,
  5625. type
  5626. };
  5627. if (this.#position === -1) {
  5628. if (this.#commands.length > 0) {
  5629. this.#commands.length = 0;
  5630. }
  5631. this.#position = 0;
  5632. this.#commands.push(save);
  5633. return;
  5634. }
  5635. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  5636. if (keepUndo) {
  5637. save.undo = this.#commands[this.#position].undo;
  5638. }
  5639. this.#commands[this.#position] = save;
  5640. return;
  5641. }
  5642. const next = this.#position + 1;
  5643. if (next === this.#maxSize) {
  5644. this.#commands.splice(0, 1);
  5645. } else {
  5646. this.#position = next;
  5647. if (next < this.#commands.length) {
  5648. this.#commands.splice(next);
  5649. }
  5650. }
  5651. this.#commands.push(save);
  5652. }
  5653. undo() {
  5654. if (this.#position === -1) {
  5655. return;
  5656. }
  5657. this.#locked = true;
  5658. const {
  5659. undo,
  5660. post
  5661. } = this.#commands[this.#position];
  5662. undo();
  5663. post?.();
  5664. this.#locked = false;
  5665. this.#position -= 1;
  5666. }
  5667. redo() {
  5668. if (this.#position < this.#commands.length - 1) {
  5669. this.#position += 1;
  5670. this.#locked = true;
  5671. const {
  5672. cmd,
  5673. post
  5674. } = this.#commands[this.#position];
  5675. cmd();
  5676. post?.();
  5677. this.#locked = false;
  5678. }
  5679. }
  5680. hasSomethingToUndo() {
  5681. return this.#position !== -1;
  5682. }
  5683. hasSomethingToRedo() {
  5684. return this.#position < this.#commands.length - 1;
  5685. }
  5686. cleanType(type) {
  5687. if (this.#position === -1) {
  5688. return;
  5689. }
  5690. for (let i = this.#position; i >= 0; i--) {
  5691. if (this.#commands[i].type !== type) {
  5692. this.#commands.splice(i + 1, this.#position - i);
  5693. this.#position = i;
  5694. return;
  5695. }
  5696. }
  5697. this.#commands.length = 0;
  5698. this.#position = -1;
  5699. }
  5700. destroy() {
  5701. this.#commands = null;
  5702. }
  5703. }
  5704. class KeyboardManager {
  5705. constructor(callbacks) {
  5706. this.buffer = [];
  5707. this.callbacks = new Map();
  5708. this.allKeys = new Set();
  5709. const {
  5710. isMac
  5711. } = util_FeatureTest.platform;
  5712. for (const [keys, callback, options = {}] of callbacks) {
  5713. for (const key of keys) {
  5714. const isMacKey = key.startsWith("mac+");
  5715. if (isMac && isMacKey) {
  5716. this.callbacks.set(key.slice(4), {
  5717. callback,
  5718. options
  5719. });
  5720. this.allKeys.add(key.split("+").at(-1));
  5721. } else if (!isMac && !isMacKey) {
  5722. this.callbacks.set(key, {
  5723. callback,
  5724. options
  5725. });
  5726. this.allKeys.add(key.split("+").at(-1));
  5727. }
  5728. }
  5729. }
  5730. }
  5731. #serialize(event) {
  5732. if (event.altKey) {
  5733. this.buffer.push("alt");
  5734. }
  5735. if (event.ctrlKey) {
  5736. this.buffer.push("ctrl");
  5737. }
  5738. if (event.metaKey) {
  5739. this.buffer.push("meta");
  5740. }
  5741. if (event.shiftKey) {
  5742. this.buffer.push("shift");
  5743. }
  5744. this.buffer.push(event.key);
  5745. const str = this.buffer.join("+");
  5746. this.buffer.length = 0;
  5747. return str;
  5748. }
  5749. exec(self, event) {
  5750. if (!this.allKeys.has(event.key)) {
  5751. return;
  5752. }
  5753. const info = this.callbacks.get(this.#serialize(event));
  5754. if (!info) {
  5755. return;
  5756. }
  5757. const {
  5758. callback,
  5759. options: {
  5760. bubbles = false,
  5761. args = [],
  5762. checker = null
  5763. }
  5764. } = info;
  5765. if (checker && !checker(self, event)) {
  5766. return;
  5767. }
  5768. callback.bind(self, ...args, event)();
  5769. if (!bubbles) {
  5770. stopEvent(event);
  5771. }
  5772. }
  5773. }
  5774. class ColorManager {
  5775. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  5776. get _colors() {
  5777. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  5778. getColorValues(colors);
  5779. return shadow(this, "_colors", colors);
  5780. }
  5781. convert(color) {
  5782. const rgb = getRGB(color);
  5783. if (!window.matchMedia("(forced-colors: active)").matches) {
  5784. return rgb;
  5785. }
  5786. for (const [name, RGB] of this._colors) {
  5787. if (RGB.every((x, i) => x === rgb[i])) {
  5788. return ColorManager._colorsMapping.get(name);
  5789. }
  5790. }
  5791. return rgb;
  5792. }
  5793. getHexCode(name) {
  5794. const rgb = this._colors.get(name);
  5795. if (!rgb) {
  5796. return name;
  5797. }
  5798. return Util.makeHexColor(...rgb);
  5799. }
  5800. }
  5801. class AnnotationEditorUIManager {
  5802. #abortController = new AbortController();
  5803. #activeEditor = null;
  5804. #allEditors = new Map();
  5805. #allLayers = new Map();
  5806. #altTextManager = null;
  5807. #annotationStorage = null;
  5808. #changedExistingAnnotations = null;
  5809. #commandManager = new CommandManager();
  5810. #copyPasteAC = null;
  5811. #currentDrawingSession = null;
  5812. #currentPageIndex = 0;
  5813. #deletedAnnotationsElementIds = new Set();
  5814. #draggingEditors = null;
  5815. #editorTypes = null;
  5816. #editorsToRescale = new Set();
  5817. _editorUndoBar = null;
  5818. #enableHighlightFloatingButton = false;
  5819. #enableUpdatedAddImage = false;
  5820. #enableNewAltTextWhenAddingImage = false;
  5821. #filterFactory = null;
  5822. #focusMainContainerTimeoutId = null;
  5823. #focusManagerAC = null;
  5824. #highlightColors = null;
  5825. #highlightWhenShiftUp = false;
  5826. #highlightToolbar = null;
  5827. #idManager = new IdManager();
  5828. #isEnabled = false;
  5829. #isWaiting = false;
  5830. #keyboardManagerAC = null;
  5831. #lastActiveElement = null;
  5832. #mainHighlightColorPicker = null;
  5833. #missingCanvases = null;
  5834. #mlManager = null;
  5835. #mode = AnnotationEditorType.NONE;
  5836. #selectedEditors = new Set();
  5837. #selectedTextNode = null;
  5838. #signatureManager = null;
  5839. #pageColors = null;
  5840. #showAllStates = null;
  5841. #previousStates = {
  5842. isEditing: false,
  5843. isEmpty: true,
  5844. hasSomethingToUndo: false,
  5845. hasSomethingToRedo: false,
  5846. hasSelectedEditor: false,
  5847. hasSelectedText: false
  5848. };
  5849. #translation = [0, 0];
  5850. #translationTimeoutId = null;
  5851. #container = null;
  5852. #viewer = null;
  5853. #updateModeCapability = null;
  5854. static TRANSLATE_SMALL = 1;
  5855. static TRANSLATE_BIG = 10;
  5856. static get _keyboardManager() {
  5857. const proto = AnnotationEditorUIManager.prototype;
  5858. const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl();
  5859. const textInputChecker = (_self, {
  5860. target: el
  5861. }) => {
  5862. if (el instanceof HTMLInputElement) {
  5863. const {
  5864. type
  5865. } = el;
  5866. return type !== "text" && type !== "number";
  5867. }
  5868. return true;
  5869. };
  5870. const small = this.TRANSLATE_SMALL;
  5871. const big = this.TRANSLATE_BIG;
  5872. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
  5873. checker: textInputChecker
  5874. }], [["ctrl+z", "mac+meta+z"], proto.undo, {
  5875. checker: textInputChecker
  5876. }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
  5877. checker: textInputChecker
  5878. }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
  5879. checker: textInputChecker
  5880. }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
  5881. checker: (self, {
  5882. target: el
  5883. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled
  5884. }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
  5885. checker: (self, {
  5886. target: el
  5887. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement)
  5888. }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
  5889. args: [-small, 0],
  5890. checker: arrowChecker
  5891. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
  5892. args: [-big, 0],
  5893. checker: arrowChecker
  5894. }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
  5895. args: [small, 0],
  5896. checker: arrowChecker
  5897. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
  5898. args: [big, 0],
  5899. checker: arrowChecker
  5900. }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
  5901. args: [0, -small],
  5902. checker: arrowChecker
  5903. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
  5904. args: [0, -big],
  5905. checker: arrowChecker
  5906. }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
  5907. args: [0, small],
  5908. checker: arrowChecker
  5909. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
  5910. args: [0, big],
  5911. checker: arrowChecker
  5912. }]]));
  5913. }
  5914. constructor(container, viewer, altTextManager, signatureManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) {
  5915. const signal = this._signal = this.#abortController.signal;
  5916. this.#container = container;
  5917. this.#viewer = viewer;
  5918. this.#altTextManager = altTextManager;
  5919. this.#signatureManager = signatureManager;
  5920. this._eventBus = eventBus;
  5921. eventBus._on("editingaction", this.onEditingAction.bind(this), {
  5922. signal
  5923. });
  5924. eventBus._on("pagechanging", this.onPageChanging.bind(this), {
  5925. signal
  5926. });
  5927. eventBus._on("scalechanging", this.onScaleChanging.bind(this), {
  5928. signal
  5929. });
  5930. eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {
  5931. signal
  5932. });
  5933. eventBus._on("setpreference", this.onSetPreference.bind(this), {
  5934. signal
  5935. });
  5936. eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), {
  5937. signal
  5938. });
  5939. this.#addSelectionListener();
  5940. this.#addDragAndDropListeners();
  5941. this.#addKeyboardManager();
  5942. this.#annotationStorage = pdfDocument.annotationStorage;
  5943. this.#filterFactory = pdfDocument.filterFactory;
  5944. this.#pageColors = pageColors;
  5945. this.#highlightColors = highlightColors || null;
  5946. this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
  5947. this.#enableUpdatedAddImage = enableUpdatedAddImage;
  5948. this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;
  5949. this.#mlManager = mlManager || null;
  5950. this.viewParameters = {
  5951. realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
  5952. rotation: 0
  5953. };
  5954. this.isShiftKeyDown = false;
  5955. this._editorUndoBar = editorUndoBar || null;
  5956. this._supportsPinchToZoom = supportsPinchToZoom !== false;
  5957. }
  5958. destroy() {
  5959. this.#updateModeCapability?.resolve();
  5960. this.#updateModeCapability = null;
  5961. this.#abortController?.abort();
  5962. this.#abortController = null;
  5963. this._signal = null;
  5964. for (const layer of this.#allLayers.values()) {
  5965. layer.destroy();
  5966. }
  5967. this.#allLayers.clear();
  5968. this.#allEditors.clear();
  5969. this.#editorsToRescale.clear();
  5970. this.#missingCanvases?.clear();
  5971. this.#activeEditor = null;
  5972. this.#selectedEditors.clear();
  5973. this.#commandManager.destroy();
  5974. this.#altTextManager?.destroy();
  5975. this.#signatureManager?.destroy();
  5976. this.#highlightToolbar?.hide();
  5977. this.#highlightToolbar = null;
  5978. this.#mainHighlightColorPicker?.destroy();
  5979. this.#mainHighlightColorPicker = null;
  5980. if (this.#focusMainContainerTimeoutId) {
  5981. clearTimeout(this.#focusMainContainerTimeoutId);
  5982. this.#focusMainContainerTimeoutId = null;
  5983. }
  5984. if (this.#translationTimeoutId) {
  5985. clearTimeout(this.#translationTimeoutId);
  5986. this.#translationTimeoutId = null;
  5987. }
  5988. this._editorUndoBar?.destroy();
  5989. }
  5990. combinedSignal(ac) {
  5991. return AbortSignal.any([this._signal, ac.signal]);
  5992. }
  5993. get mlManager() {
  5994. return this.#mlManager;
  5995. }
  5996. get useNewAltTextFlow() {
  5997. return this.#enableUpdatedAddImage;
  5998. }
  5999. get useNewAltTextWhenAddingImage() {
  6000. return this.#enableNewAltTextWhenAddingImage;
  6001. }
  6002. get hcmFilter() {
  6003. return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
  6004. }
  6005. get direction() {
  6006. return shadow(this, "direction", getComputedStyle(this.#container).direction);
  6007. }
  6008. get highlightColors() {
  6009. return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null);
  6010. }
  6011. get highlightColorNames() {
  6012. return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null);
  6013. }
  6014. setCurrentDrawingSession(layer) {
  6015. if (layer) {
  6016. this.unselectAll();
  6017. this.disableUserSelect(true);
  6018. } else {
  6019. this.disableUserSelect(false);
  6020. }
  6021. this.#currentDrawingSession = layer;
  6022. }
  6023. setMainHighlightColorPicker(colorPicker) {
  6024. this.#mainHighlightColorPicker = colorPicker;
  6025. }
  6026. editAltText(editor, firstTime = false) {
  6027. this.#altTextManager?.editAltText(this, editor, firstTime);
  6028. }
  6029. getSignature(editor) {
  6030. this.#signatureManager?.getSignature({
  6031. uiManager: this,
  6032. editor
  6033. });
  6034. }
  6035. get signatureManager() {
  6036. return this.#signatureManager;
  6037. }
  6038. switchToMode(mode, callback) {
  6039. this._eventBus.on("annotationeditormodechanged", callback, {
  6040. once: true,
  6041. signal: this._signal
  6042. });
  6043. this._eventBus.dispatch("showannotationeditorui", {
  6044. source: this,
  6045. mode
  6046. });
  6047. }
  6048. setPreference(name, value) {
  6049. this._eventBus.dispatch("setpreference", {
  6050. source: this,
  6051. name,
  6052. value
  6053. });
  6054. }
  6055. onSetPreference({
  6056. name,
  6057. value
  6058. }) {
  6059. switch (name) {
  6060. case "enableNewAltTextWhenAddingImage":
  6061. this.#enableNewAltTextWhenAddingImage = value;
  6062. break;
  6063. }
  6064. }
  6065. onPageChanging({
  6066. pageNumber
  6067. }) {
  6068. this.#currentPageIndex = pageNumber - 1;
  6069. }
  6070. focusMainContainer() {
  6071. this.#container.focus();
  6072. }
  6073. findParent(x, y) {
  6074. for (const layer of this.#allLayers.values()) {
  6075. const {
  6076. x: layerX,
  6077. y: layerY,
  6078. width,
  6079. height
  6080. } = layer.div.getBoundingClientRect();
  6081. if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {
  6082. return layer;
  6083. }
  6084. }
  6085. return null;
  6086. }
  6087. disableUserSelect(value = false) {
  6088. this.#viewer.classList.toggle("noUserSelect", value);
  6089. }
  6090. addShouldRescale(editor) {
  6091. this.#editorsToRescale.add(editor);
  6092. }
  6093. removeShouldRescale(editor) {
  6094. this.#editorsToRescale.delete(editor);
  6095. }
  6096. onScaleChanging({
  6097. scale
  6098. }) {
  6099. this.commitOrRemove();
  6100. this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
  6101. for (const editor of this.#editorsToRescale) {
  6102. editor.onScaleChanging();
  6103. }
  6104. this.#currentDrawingSession?.onScaleChanging();
  6105. }
  6106. onRotationChanging({
  6107. pagesRotation
  6108. }) {
  6109. this.commitOrRemove();
  6110. this.viewParameters.rotation = pagesRotation;
  6111. }
  6112. #getAnchorElementForSelection({
  6113. anchorNode
  6114. }) {
  6115. return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
  6116. }
  6117. #getLayerForTextLayer(textLayer) {
  6118. const {
  6119. currentLayer
  6120. } = this;
  6121. if (currentLayer.hasTextLayer(textLayer)) {
  6122. return currentLayer;
  6123. }
  6124. for (const layer of this.#allLayers.values()) {
  6125. if (layer.hasTextLayer(textLayer)) {
  6126. return layer;
  6127. }
  6128. }
  6129. return null;
  6130. }
  6131. highlightSelection(methodOfCreation = "") {
  6132. const selection = document.getSelection();
  6133. if (!selection || selection.isCollapsed) {
  6134. return;
  6135. }
  6136. const {
  6137. anchorNode,
  6138. anchorOffset,
  6139. focusNode,
  6140. focusOffset
  6141. } = selection;
  6142. const text = selection.toString();
  6143. const anchorElement = this.#getAnchorElementForSelection(selection);
  6144. const textLayer = anchorElement.closest(".textLayer");
  6145. const boxes = this.getSelectionBoxes(textLayer);
  6146. if (!boxes) {
  6147. return;
  6148. }
  6149. selection.empty();
  6150. const layer = this.#getLayerForTextLayer(textLayer);
  6151. const isNoneMode = this.#mode === AnnotationEditorType.NONE;
  6152. const callback = () => {
  6153. layer?.createAndAddNewEditor({
  6154. x: 0,
  6155. y: 0
  6156. }, false, {
  6157. methodOfCreation,
  6158. boxes,
  6159. anchorNode,
  6160. anchorOffset,
  6161. focusNode,
  6162. focusOffset,
  6163. text
  6164. });
  6165. if (isNoneMode) {
  6166. this.showAllEditors("highlight", true, true);
  6167. }
  6168. };
  6169. if (isNoneMode) {
  6170. this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);
  6171. return;
  6172. }
  6173. callback();
  6174. }
  6175. #displayHighlightToolbar() {
  6176. const selection = document.getSelection();
  6177. if (!selection || selection.isCollapsed) {
  6178. return;
  6179. }
  6180. const anchorElement = this.#getAnchorElementForSelection(selection);
  6181. const textLayer = anchorElement.closest(".textLayer");
  6182. const boxes = this.getSelectionBoxes(textLayer);
  6183. if (!boxes) {
  6184. return;
  6185. }
  6186. this.#highlightToolbar ||= new HighlightToolbar(this);
  6187. this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr");
  6188. }
  6189. addToAnnotationStorage(editor) {
  6190. if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
  6191. this.#annotationStorage.setValue(editor.id, editor);
  6192. }
  6193. }
  6194. #selectionChange() {
  6195. const selection = document.getSelection();
  6196. if (!selection || selection.isCollapsed) {
  6197. if (this.#selectedTextNode) {
  6198. this.#highlightToolbar?.hide();
  6199. this.#selectedTextNode = null;
  6200. this.#dispatchUpdateStates({
  6201. hasSelectedText: false
  6202. });
  6203. }
  6204. return;
  6205. }
  6206. const {
  6207. anchorNode
  6208. } = selection;
  6209. if (anchorNode === this.#selectedTextNode) {
  6210. return;
  6211. }
  6212. const anchorElement = this.#getAnchorElementForSelection(selection);
  6213. const textLayer = anchorElement.closest(".textLayer");
  6214. if (!textLayer) {
  6215. if (this.#selectedTextNode) {
  6216. this.#highlightToolbar?.hide();
  6217. this.#selectedTextNode = null;
  6218. this.#dispatchUpdateStates({
  6219. hasSelectedText: false
  6220. });
  6221. }
  6222. return;
  6223. }
  6224. this.#highlightToolbar?.hide();
  6225. this.#selectedTextNode = anchorNode;
  6226. this.#dispatchUpdateStates({
  6227. hasSelectedText: true
  6228. });
  6229. if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
  6230. return;
  6231. }
  6232. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  6233. this.showAllEditors("highlight", true, true);
  6234. }
  6235. this.#highlightWhenShiftUp = this.isShiftKeyDown;
  6236. if (!this.isShiftKeyDown) {
  6237. const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;
  6238. activeLayer?.toggleDrawing();
  6239. const ac = new AbortController();
  6240. const signal = this.combinedSignal(ac);
  6241. const pointerup = e => {
  6242. if (e.type === "pointerup" && e.button !== 0) {
  6243. return;
  6244. }
  6245. ac.abort();
  6246. activeLayer?.toggleDrawing(true);
  6247. if (e.type === "pointerup") {
  6248. this.#onSelectEnd("main_toolbar");
  6249. }
  6250. };
  6251. window.addEventListener("pointerup", pointerup, {
  6252. signal
  6253. });
  6254. window.addEventListener("blur", pointerup, {
  6255. signal
  6256. });
  6257. }
  6258. }
  6259. #onSelectEnd(methodOfCreation = "") {
  6260. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  6261. this.highlightSelection(methodOfCreation);
  6262. } else if (this.#enableHighlightFloatingButton) {
  6263. this.#displayHighlightToolbar();
  6264. }
  6265. }
  6266. #addSelectionListener() {
  6267. document.addEventListener("selectionchange", this.#selectionChange.bind(this), {
  6268. signal: this._signal
  6269. });
  6270. }
  6271. #addFocusManager() {
  6272. if (this.#focusManagerAC) {
  6273. return;
  6274. }
  6275. this.#focusManagerAC = new AbortController();
  6276. const signal = this.combinedSignal(this.#focusManagerAC);
  6277. window.addEventListener("focus", this.focus.bind(this), {
  6278. signal
  6279. });
  6280. window.addEventListener("blur", this.blur.bind(this), {
  6281. signal
  6282. });
  6283. }
  6284. #removeFocusManager() {
  6285. this.#focusManagerAC?.abort();
  6286. this.#focusManagerAC = null;
  6287. }
  6288. blur() {
  6289. this.isShiftKeyDown = false;
  6290. if (this.#highlightWhenShiftUp) {
  6291. this.#highlightWhenShiftUp = false;
  6292. this.#onSelectEnd("main_toolbar");
  6293. }
  6294. if (!this.hasSelection) {
  6295. return;
  6296. }
  6297. const {
  6298. activeElement
  6299. } = document;
  6300. for (const editor of this.#selectedEditors) {
  6301. if (editor.div.contains(activeElement)) {
  6302. this.#lastActiveElement = [editor, activeElement];
  6303. editor._focusEventsAllowed = false;
  6304. break;
  6305. }
  6306. }
  6307. }
  6308. focus() {
  6309. if (!this.#lastActiveElement) {
  6310. return;
  6311. }
  6312. const [lastEditor, lastActiveElement] = this.#lastActiveElement;
  6313. this.#lastActiveElement = null;
  6314. lastActiveElement.addEventListener("focusin", () => {
  6315. lastEditor._focusEventsAllowed = true;
  6316. }, {
  6317. once: true,
  6318. signal: this._signal
  6319. });
  6320. lastActiveElement.focus();
  6321. }
  6322. #addKeyboardManager() {
  6323. if (this.#keyboardManagerAC) {
  6324. return;
  6325. }
  6326. this.#keyboardManagerAC = new AbortController();
  6327. const signal = this.combinedSignal(this.#keyboardManagerAC);
  6328. window.addEventListener("keydown", this.keydown.bind(this), {
  6329. signal
  6330. });
  6331. window.addEventListener("keyup", this.keyup.bind(this), {
  6332. signal
  6333. });
  6334. }
  6335. #removeKeyboardManager() {
  6336. this.#keyboardManagerAC?.abort();
  6337. this.#keyboardManagerAC = null;
  6338. }
  6339. #addCopyPasteListeners() {
  6340. if (this.#copyPasteAC) {
  6341. return;
  6342. }
  6343. this.#copyPasteAC = new AbortController();
  6344. const signal = this.combinedSignal(this.#copyPasteAC);
  6345. document.addEventListener("copy", this.copy.bind(this), {
  6346. signal
  6347. });
  6348. document.addEventListener("cut", this.cut.bind(this), {
  6349. signal
  6350. });
  6351. document.addEventListener("paste", this.paste.bind(this), {
  6352. signal
  6353. });
  6354. }
  6355. #removeCopyPasteListeners() {
  6356. this.#copyPasteAC?.abort();
  6357. this.#copyPasteAC = null;
  6358. }
  6359. #addDragAndDropListeners() {
  6360. const signal = this._signal;
  6361. document.addEventListener("dragover", this.dragOver.bind(this), {
  6362. signal
  6363. });
  6364. document.addEventListener("drop", this.drop.bind(this), {
  6365. signal
  6366. });
  6367. }
  6368. addEditListeners() {
  6369. this.#addKeyboardManager();
  6370. this.#addCopyPasteListeners();
  6371. }
  6372. removeEditListeners() {
  6373. this.#removeKeyboardManager();
  6374. this.#removeCopyPasteListeners();
  6375. }
  6376. dragOver(event) {
  6377. for (const {
  6378. type
  6379. } of event.dataTransfer.items) {
  6380. for (const editorType of this.#editorTypes) {
  6381. if (editorType.isHandlingMimeForPasting(type)) {
  6382. event.dataTransfer.dropEffect = "copy";
  6383. event.preventDefault();
  6384. return;
  6385. }
  6386. }
  6387. }
  6388. }
  6389. drop(event) {
  6390. for (const item of event.dataTransfer.items) {
  6391. for (const editorType of this.#editorTypes) {
  6392. if (editorType.isHandlingMimeForPasting(item.type)) {
  6393. editorType.paste(item, this.currentLayer);
  6394. event.preventDefault();
  6395. return;
  6396. }
  6397. }
  6398. }
  6399. }
  6400. copy(event) {
  6401. event.preventDefault();
  6402. this.#activeEditor?.commitOrRemove();
  6403. if (!this.hasSelection) {
  6404. return;
  6405. }
  6406. const editors = [];
  6407. for (const editor of this.#selectedEditors) {
  6408. const serialized = editor.serialize(true);
  6409. if (serialized) {
  6410. editors.push(serialized);
  6411. }
  6412. }
  6413. if (editors.length === 0) {
  6414. return;
  6415. }
  6416. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  6417. }
  6418. cut(event) {
  6419. this.copy(event);
  6420. this.delete();
  6421. }
  6422. async paste(event) {
  6423. event.preventDefault();
  6424. const {
  6425. clipboardData
  6426. } = event;
  6427. for (const item of clipboardData.items) {
  6428. for (const editorType of this.#editorTypes) {
  6429. if (editorType.isHandlingMimeForPasting(item.type)) {
  6430. editorType.paste(item, this.currentLayer);
  6431. return;
  6432. }
  6433. }
  6434. }
  6435. let data = clipboardData.getData("application/pdfjs");
  6436. if (!data) {
  6437. return;
  6438. }
  6439. try {
  6440. data = JSON.parse(data);
  6441. } catch (ex) {
  6442. warn(`paste: "${ex.message}".`);
  6443. return;
  6444. }
  6445. if (!Array.isArray(data)) {
  6446. return;
  6447. }
  6448. this.unselectAll();
  6449. const layer = this.currentLayer;
  6450. try {
  6451. const newEditors = [];
  6452. for (const editor of data) {
  6453. const deserializedEditor = await layer.deserialize(editor);
  6454. if (!deserializedEditor) {
  6455. return;
  6456. }
  6457. newEditors.push(deserializedEditor);
  6458. }
  6459. const cmd = () => {
  6460. for (const editor of newEditors) {
  6461. this.#addEditorToLayer(editor);
  6462. }
  6463. this.#selectEditors(newEditors);
  6464. };
  6465. const undo = () => {
  6466. for (const editor of newEditors) {
  6467. editor.remove();
  6468. }
  6469. };
  6470. this.addCommands({
  6471. cmd,
  6472. undo,
  6473. mustExec: true
  6474. });
  6475. } catch (ex) {
  6476. warn(`paste: "${ex.message}".`);
  6477. }
  6478. }
  6479. keydown(event) {
  6480. if (!this.isShiftKeyDown && event.key === "Shift") {
  6481. this.isShiftKeyDown = true;
  6482. }
  6483. if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
  6484. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  6485. }
  6486. }
  6487. keyup(event) {
  6488. if (this.isShiftKeyDown && event.key === "Shift") {
  6489. this.isShiftKeyDown = false;
  6490. if (this.#highlightWhenShiftUp) {
  6491. this.#highlightWhenShiftUp = false;
  6492. this.#onSelectEnd("main_toolbar");
  6493. }
  6494. }
  6495. }
  6496. onEditingAction({
  6497. name
  6498. }) {
  6499. switch (name) {
  6500. case "undo":
  6501. case "redo":
  6502. case "delete":
  6503. case "selectAll":
  6504. this[name]();
  6505. break;
  6506. case "highlightSelection":
  6507. this.highlightSelection("context_menu");
  6508. break;
  6509. }
  6510. }
  6511. #dispatchUpdateStates(details) {
  6512. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  6513. if (hasChanged) {
  6514. this._eventBus.dispatch("annotationeditorstateschanged", {
  6515. source: this,
  6516. details: Object.assign(this.#previousStates, details)
  6517. });
  6518. if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
  6519. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
  6520. }
  6521. }
  6522. }
  6523. #dispatchUpdateUI(details) {
  6524. this._eventBus.dispatch("annotationeditorparamschanged", {
  6525. source: this,
  6526. details
  6527. });
  6528. }
  6529. setEditingState(isEditing) {
  6530. if (isEditing) {
  6531. this.#addFocusManager();
  6532. this.#addCopyPasteListeners();
  6533. this.#dispatchUpdateStates({
  6534. isEditing: this.#mode !== AnnotationEditorType.NONE,
  6535. isEmpty: this.#isEmpty(),
  6536. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  6537. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  6538. hasSelectedEditor: false
  6539. });
  6540. } else {
  6541. this.#removeFocusManager();
  6542. this.#removeCopyPasteListeners();
  6543. this.#dispatchUpdateStates({
  6544. isEditing: false
  6545. });
  6546. this.disableUserSelect(false);
  6547. }
  6548. }
  6549. registerEditorTypes(types) {
  6550. if (this.#editorTypes) {
  6551. return;
  6552. }
  6553. this.#editorTypes = types;
  6554. for (const editorType of this.#editorTypes) {
  6555. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  6556. }
  6557. }
  6558. getId() {
  6559. return this.#idManager.id;
  6560. }
  6561. get currentLayer() {
  6562. return this.#allLayers.get(this.#currentPageIndex);
  6563. }
  6564. getLayer(pageIndex) {
  6565. return this.#allLayers.get(pageIndex);
  6566. }
  6567. get currentPageIndex() {
  6568. return this.#currentPageIndex;
  6569. }
  6570. addLayer(layer) {
  6571. this.#allLayers.set(layer.pageIndex, layer);
  6572. if (this.#isEnabled) {
  6573. layer.enable();
  6574. } else {
  6575. layer.disable();
  6576. }
  6577. }
  6578. removeLayer(layer) {
  6579. this.#allLayers.delete(layer.pageIndex);
  6580. }
  6581. async updateMode(mode, editId = null, isFromKeyboard = false) {
  6582. if (this.#mode === mode) {
  6583. return;
  6584. }
  6585. if (this.#updateModeCapability) {
  6586. await this.#updateModeCapability.promise;
  6587. if (!this.#updateModeCapability) {
  6588. return;
  6589. }
  6590. }
  6591. this.#updateModeCapability = Promise.withResolvers();
  6592. this.#currentDrawingSession?.commitOrRemove();
  6593. this.#mode = mode;
  6594. if (mode === AnnotationEditorType.NONE) {
  6595. this.setEditingState(false);
  6596. this.#disableAll();
  6597. this._editorUndoBar?.hide();
  6598. this.#updateModeCapability.resolve();
  6599. return;
  6600. }
  6601. if (mode === AnnotationEditorType.SIGNATURE) {
  6602. await this.#signatureManager?.loadSignatures();
  6603. }
  6604. this.setEditingState(true);
  6605. await this.#enableAll();
  6606. this.unselectAll();
  6607. for (const layer of this.#allLayers.values()) {
  6608. layer.updateMode(mode);
  6609. }
  6610. if (!editId) {
  6611. if (isFromKeyboard) {
  6612. this.addNewEditorFromKeyboard();
  6613. }
  6614. this.#updateModeCapability.resolve();
  6615. return;
  6616. }
  6617. for (const editor of this.#allEditors.values()) {
  6618. if (editor.annotationElementId === editId || editor.id === editId) {
  6619. this.setSelected(editor);
  6620. editor.enterInEditMode();
  6621. } else {
  6622. editor.unselect();
  6623. }
  6624. }
  6625. this.#updateModeCapability.resolve();
  6626. }
  6627. addNewEditorFromKeyboard() {
  6628. if (this.currentLayer.canCreateNewEmptyEditor()) {
  6629. this.currentLayer.addNewEditor();
  6630. }
  6631. }
  6632. updateToolbar(options) {
  6633. if (options.mode === this.#mode) {
  6634. return;
  6635. }
  6636. this._eventBus.dispatch("switchannotationeditormode", {
  6637. source: this,
  6638. ...options
  6639. });
  6640. }
  6641. updateParams(type, value) {
  6642. if (!this.#editorTypes) {
  6643. return;
  6644. }
  6645. switch (type) {
  6646. case AnnotationEditorParamsType.CREATE:
  6647. this.currentLayer.addNewEditor(value);
  6648. return;
  6649. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  6650. this.#mainHighlightColorPicker?.updateColor(value);
  6651. break;
  6652. case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
  6653. this._eventBus.dispatch("reporttelemetry", {
  6654. source: this,
  6655. details: {
  6656. type: "editing",
  6657. data: {
  6658. type: "highlight",
  6659. action: "toggle_visibility"
  6660. }
  6661. }
  6662. });
  6663. (this.#showAllStates ||= new Map()).set(type, value);
  6664. this.showAllEditors("highlight", value);
  6665. break;
  6666. }
  6667. for (const editor of this.#selectedEditors) {
  6668. editor.updateParams(type, value);
  6669. }
  6670. for (const editorType of this.#editorTypes) {
  6671. editorType.updateDefaultParams(type, value);
  6672. }
  6673. }
  6674. showAllEditors(type, visible, updateButton = false) {
  6675. for (const editor of this.#allEditors.values()) {
  6676. if (editor.editorType === type) {
  6677. editor.show(visible);
  6678. }
  6679. }
  6680. const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
  6681. if (state !== visible) {
  6682. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
  6683. }
  6684. }
  6685. enableWaiting(mustWait = false) {
  6686. if (this.#isWaiting === mustWait) {
  6687. return;
  6688. }
  6689. this.#isWaiting = mustWait;
  6690. for (const layer of this.#allLayers.values()) {
  6691. if (mustWait) {
  6692. layer.disableClick();
  6693. } else {
  6694. layer.enableClick();
  6695. }
  6696. layer.div.classList.toggle("waiting", mustWait);
  6697. }
  6698. }
  6699. async #enableAll() {
  6700. if (!this.#isEnabled) {
  6701. this.#isEnabled = true;
  6702. const promises = [];
  6703. for (const layer of this.#allLayers.values()) {
  6704. promises.push(layer.enable());
  6705. }
  6706. await Promise.all(promises);
  6707. for (const editor of this.#allEditors.values()) {
  6708. editor.enable();
  6709. }
  6710. }
  6711. }
  6712. #disableAll() {
  6713. this.unselectAll();
  6714. if (this.#isEnabled) {
  6715. this.#isEnabled = false;
  6716. for (const layer of this.#allLayers.values()) {
  6717. layer.disable();
  6718. }
  6719. for (const editor of this.#allEditors.values()) {
  6720. editor.disable();
  6721. }
  6722. }
  6723. }
  6724. getEditors(pageIndex) {
  6725. const editors = [];
  6726. for (const editor of this.#allEditors.values()) {
  6727. if (editor.pageIndex === pageIndex) {
  6728. editors.push(editor);
  6729. }
  6730. }
  6731. return editors;
  6732. }
  6733. getEditor(id) {
  6734. return this.#allEditors.get(id);
  6735. }
  6736. addEditor(editor) {
  6737. this.#allEditors.set(editor.id, editor);
  6738. }
  6739. removeEditor(editor) {
  6740. if (editor.div.contains(document.activeElement)) {
  6741. if (this.#focusMainContainerTimeoutId) {
  6742. clearTimeout(this.#focusMainContainerTimeoutId);
  6743. }
  6744. this.#focusMainContainerTimeoutId = setTimeout(() => {
  6745. this.focusMainContainer();
  6746. this.#focusMainContainerTimeoutId = null;
  6747. }, 0);
  6748. }
  6749. this.#allEditors.delete(editor.id);
  6750. if (editor.annotationElementId) {
  6751. this.#missingCanvases?.delete(editor.annotationElementId);
  6752. }
  6753. this.unselect(editor);
  6754. if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
  6755. this.#annotationStorage?.remove(editor.id);
  6756. }
  6757. }
  6758. addDeletedAnnotationElement(editor) {
  6759. this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
  6760. this.addChangedExistingAnnotation(editor);
  6761. editor.deleted = true;
  6762. }
  6763. isDeletedAnnotationElement(annotationElementId) {
  6764. return this.#deletedAnnotationsElementIds.has(annotationElementId);
  6765. }
  6766. removeDeletedAnnotationElement(editor) {
  6767. this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
  6768. this.removeChangedExistingAnnotation(editor);
  6769. editor.deleted = false;
  6770. }
  6771. #addEditorToLayer(editor) {
  6772. const layer = this.#allLayers.get(editor.pageIndex);
  6773. if (layer) {
  6774. layer.addOrRebuild(editor);
  6775. } else {
  6776. this.addEditor(editor);
  6777. this.addToAnnotationStorage(editor);
  6778. }
  6779. }
  6780. setActiveEditor(editor) {
  6781. if (this.#activeEditor === editor) {
  6782. return;
  6783. }
  6784. this.#activeEditor = editor;
  6785. if (editor) {
  6786. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6787. }
  6788. }
  6789. get #lastSelectedEditor() {
  6790. let ed = null;
  6791. for (ed of this.#selectedEditors) {}
  6792. return ed;
  6793. }
  6794. updateUI(editor) {
  6795. if (this.#lastSelectedEditor === editor) {
  6796. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6797. }
  6798. }
  6799. updateUIForDefaultProperties(editorType) {
  6800. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  6801. }
  6802. toggleSelected(editor) {
  6803. if (this.#selectedEditors.has(editor)) {
  6804. this.#selectedEditors.delete(editor);
  6805. editor.unselect();
  6806. this.#dispatchUpdateStates({
  6807. hasSelectedEditor: this.hasSelection
  6808. });
  6809. return;
  6810. }
  6811. this.#selectedEditors.add(editor);
  6812. editor.select();
  6813. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6814. this.#dispatchUpdateStates({
  6815. hasSelectedEditor: true
  6816. });
  6817. }
  6818. setSelected(editor) {
  6819. this.#currentDrawingSession?.commitOrRemove();
  6820. for (const ed of this.#selectedEditors) {
  6821. if (ed !== editor) {
  6822. ed.unselect();
  6823. }
  6824. }
  6825. this.#selectedEditors.clear();
  6826. this.#selectedEditors.add(editor);
  6827. editor.select();
  6828. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6829. this.#dispatchUpdateStates({
  6830. hasSelectedEditor: true
  6831. });
  6832. }
  6833. isSelected(editor) {
  6834. return this.#selectedEditors.has(editor);
  6835. }
  6836. get firstSelectedEditor() {
  6837. return this.#selectedEditors.values().next().value;
  6838. }
  6839. unselect(editor) {
  6840. editor.unselect();
  6841. this.#selectedEditors.delete(editor);
  6842. this.#dispatchUpdateStates({
  6843. hasSelectedEditor: this.hasSelection
  6844. });
  6845. }
  6846. get hasSelection() {
  6847. return this.#selectedEditors.size !== 0;
  6848. }
  6849. get isEnterHandled() {
  6850. return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
  6851. }
  6852. undo() {
  6853. this.#commandManager.undo();
  6854. this.#dispatchUpdateStates({
  6855. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  6856. hasSomethingToRedo: true,
  6857. isEmpty: this.#isEmpty()
  6858. });
  6859. this._editorUndoBar?.hide();
  6860. }
  6861. redo() {
  6862. this.#commandManager.redo();
  6863. this.#dispatchUpdateStates({
  6864. hasSomethingToUndo: true,
  6865. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  6866. isEmpty: this.#isEmpty()
  6867. });
  6868. }
  6869. addCommands(params) {
  6870. this.#commandManager.add(params);
  6871. this.#dispatchUpdateStates({
  6872. hasSomethingToUndo: true,
  6873. hasSomethingToRedo: false,
  6874. isEmpty: this.#isEmpty()
  6875. });
  6876. }
  6877. cleanUndoStack(type) {
  6878. this.#commandManager.cleanType(type);
  6879. }
  6880. #isEmpty() {
  6881. if (this.#allEditors.size === 0) {
  6882. return true;
  6883. }
  6884. if (this.#allEditors.size === 1) {
  6885. for (const editor of this.#allEditors.values()) {
  6886. return editor.isEmpty();
  6887. }
  6888. }
  6889. return false;
  6890. }
  6891. delete() {
  6892. this.commitOrRemove();
  6893. const drawingEditor = this.currentLayer?.endDrawingSession(true);
  6894. if (!this.hasSelection && !drawingEditor) {
  6895. return;
  6896. }
  6897. const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors];
  6898. const cmd = () => {
  6899. this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length);
  6900. for (const editor of editors) {
  6901. editor.remove();
  6902. }
  6903. };
  6904. const undo = () => {
  6905. for (const editor of editors) {
  6906. this.#addEditorToLayer(editor);
  6907. }
  6908. };
  6909. this.addCommands({
  6910. cmd,
  6911. undo,
  6912. mustExec: true
  6913. });
  6914. }
  6915. commitOrRemove() {
  6916. this.#activeEditor?.commitOrRemove();
  6917. }
  6918. hasSomethingToControl() {
  6919. return this.#activeEditor || this.hasSelection;
  6920. }
  6921. #selectEditors(editors) {
  6922. for (const editor of this.#selectedEditors) {
  6923. editor.unselect();
  6924. }
  6925. this.#selectedEditors.clear();
  6926. for (const editor of editors) {
  6927. if (editor.isEmpty()) {
  6928. continue;
  6929. }
  6930. this.#selectedEditors.add(editor);
  6931. editor.select();
  6932. }
  6933. this.#dispatchUpdateStates({
  6934. hasSelectedEditor: this.hasSelection
  6935. });
  6936. }
  6937. selectAll() {
  6938. for (const editor of this.#selectedEditors) {
  6939. editor.commit();
  6940. }
  6941. this.#selectEditors(this.#allEditors.values());
  6942. }
  6943. unselectAll() {
  6944. if (this.#activeEditor) {
  6945. this.#activeEditor.commitOrRemove();
  6946. if (this.#mode !== AnnotationEditorType.NONE) {
  6947. return;
  6948. }
  6949. }
  6950. if (this.#currentDrawingSession?.commitOrRemove()) {
  6951. return;
  6952. }
  6953. if (!this.hasSelection) {
  6954. return;
  6955. }
  6956. for (const editor of this.#selectedEditors) {
  6957. editor.unselect();
  6958. }
  6959. this.#selectedEditors.clear();
  6960. this.#dispatchUpdateStates({
  6961. hasSelectedEditor: false
  6962. });
  6963. }
  6964. translateSelectedEditors(x, y, noCommit = false) {
  6965. if (!noCommit) {
  6966. this.commitOrRemove();
  6967. }
  6968. if (!this.hasSelection) {
  6969. return;
  6970. }
  6971. this.#translation[0] += x;
  6972. this.#translation[1] += y;
  6973. const [totalX, totalY] = this.#translation;
  6974. const editors = [...this.#selectedEditors];
  6975. const TIME_TO_WAIT = 1000;
  6976. if (this.#translationTimeoutId) {
  6977. clearTimeout(this.#translationTimeoutId);
  6978. }
  6979. this.#translationTimeoutId = setTimeout(() => {
  6980. this.#translationTimeoutId = null;
  6981. this.#translation[0] = this.#translation[1] = 0;
  6982. this.addCommands({
  6983. cmd: () => {
  6984. for (const editor of editors) {
  6985. if (this.#allEditors.has(editor.id)) {
  6986. editor.translateInPage(totalX, totalY);
  6987. editor.translationDone();
  6988. }
  6989. }
  6990. },
  6991. undo: () => {
  6992. for (const editor of editors) {
  6993. if (this.#allEditors.has(editor.id)) {
  6994. editor.translateInPage(-totalX, -totalY);
  6995. editor.translationDone();
  6996. }
  6997. }
  6998. },
  6999. mustExec: false
  7000. });
  7001. }, TIME_TO_WAIT);
  7002. for (const editor of editors) {
  7003. editor.translateInPage(x, y);
  7004. editor.translationDone();
  7005. }
  7006. }
  7007. setUpDragSession() {
  7008. if (!this.hasSelection) {
  7009. return;
  7010. }
  7011. this.disableUserSelect(true);
  7012. this.#draggingEditors = new Map();
  7013. for (const editor of this.#selectedEditors) {
  7014. this.#draggingEditors.set(editor, {
  7015. savedX: editor.x,
  7016. savedY: editor.y,
  7017. savedPageIndex: editor.pageIndex,
  7018. newX: 0,
  7019. newY: 0,
  7020. newPageIndex: -1
  7021. });
  7022. }
  7023. }
  7024. endDragSession() {
  7025. if (!this.#draggingEditors) {
  7026. return false;
  7027. }
  7028. this.disableUserSelect(false);
  7029. const map = this.#draggingEditors;
  7030. this.#draggingEditors = null;
  7031. let mustBeAddedInUndoStack = false;
  7032. for (const [{
  7033. x,
  7034. y,
  7035. pageIndex
  7036. }, value] of map) {
  7037. value.newX = x;
  7038. value.newY = y;
  7039. value.newPageIndex = pageIndex;
  7040. mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex;
  7041. }
  7042. if (!mustBeAddedInUndoStack) {
  7043. return false;
  7044. }
  7045. const move = (editor, x, y, pageIndex) => {
  7046. if (this.#allEditors.has(editor.id)) {
  7047. const parent = this.#allLayers.get(pageIndex);
  7048. if (parent) {
  7049. editor._setParentAndPosition(parent, x, y);
  7050. } else {
  7051. editor.pageIndex = pageIndex;
  7052. editor.x = x;
  7053. editor.y = y;
  7054. }
  7055. }
  7056. };
  7057. this.addCommands({
  7058. cmd: () => {
  7059. for (const [editor, {
  7060. newX,
  7061. newY,
  7062. newPageIndex
  7063. }] of map) {
  7064. move(editor, newX, newY, newPageIndex);
  7065. }
  7066. },
  7067. undo: () => {
  7068. for (const [editor, {
  7069. savedX,
  7070. savedY,
  7071. savedPageIndex
  7072. }] of map) {
  7073. move(editor, savedX, savedY, savedPageIndex);
  7074. }
  7075. },
  7076. mustExec: true
  7077. });
  7078. return true;
  7079. }
  7080. dragSelectedEditors(tx, ty) {
  7081. if (!this.#draggingEditors) {
  7082. return;
  7083. }
  7084. for (const editor of this.#draggingEditors.keys()) {
  7085. editor.drag(tx, ty);
  7086. }
  7087. }
  7088. rebuild(editor) {
  7089. if (editor.parent === null) {
  7090. const parent = this.getLayer(editor.pageIndex);
  7091. if (parent) {
  7092. parent.changeParent(editor);
  7093. parent.addOrRebuild(editor);
  7094. } else {
  7095. this.addEditor(editor);
  7096. this.addToAnnotationStorage(editor);
  7097. editor.rebuild();
  7098. }
  7099. } else {
  7100. editor.parent.addOrRebuild(editor);
  7101. }
  7102. }
  7103. get isEditorHandlingKeyboard() {
  7104. return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
  7105. }
  7106. isActive(editor) {
  7107. return this.#activeEditor === editor;
  7108. }
  7109. getActive() {
  7110. return this.#activeEditor;
  7111. }
  7112. getMode() {
  7113. return this.#mode;
  7114. }
  7115. get imageManager() {
  7116. return shadow(this, "imageManager", new ImageManager());
  7117. }
  7118. getSelectionBoxes(textLayer) {
  7119. if (!textLayer) {
  7120. return null;
  7121. }
  7122. const selection = document.getSelection();
  7123. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  7124. if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) {
  7125. return null;
  7126. }
  7127. }
  7128. const {
  7129. x: layerX,
  7130. y: layerY,
  7131. width: parentWidth,
  7132. height: parentHeight
  7133. } = textLayer.getBoundingClientRect();
  7134. let rotator;
  7135. switch (textLayer.getAttribute("data-main-rotation")) {
  7136. case "90":
  7137. rotator = (x, y, w, h) => ({
  7138. x: (y - layerY) / parentHeight,
  7139. y: 1 - (x + w - layerX) / parentWidth,
  7140. width: h / parentHeight,
  7141. height: w / parentWidth
  7142. });
  7143. break;
  7144. case "180":
  7145. rotator = (x, y, w, h) => ({
  7146. x: 1 - (x + w - layerX) / parentWidth,
  7147. y: 1 - (y + h - layerY) / parentHeight,
  7148. width: w / parentWidth,
  7149. height: h / parentHeight
  7150. });
  7151. break;
  7152. case "270":
  7153. rotator = (x, y, w, h) => ({
  7154. x: 1 - (y + h - layerY) / parentHeight,
  7155. y: (x - layerX) / parentWidth,
  7156. width: h / parentHeight,
  7157. height: w / parentWidth
  7158. });
  7159. break;
  7160. default:
  7161. rotator = (x, y, w, h) => ({
  7162. x: (x - layerX) / parentWidth,
  7163. y: (y - layerY) / parentHeight,
  7164. width: w / parentWidth,
  7165. height: h / parentHeight
  7166. });
  7167. break;
  7168. }
  7169. const boxes = [];
  7170. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  7171. const range = selection.getRangeAt(i);
  7172. if (range.collapsed) {
  7173. continue;
  7174. }
  7175. for (const {
  7176. x,
  7177. y,
  7178. width,
  7179. height
  7180. } of range.getClientRects()) {
  7181. if (width === 0 || height === 0) {
  7182. continue;
  7183. }
  7184. boxes.push(rotator(x, y, width, height));
  7185. }
  7186. }
  7187. return boxes.length === 0 ? null : boxes;
  7188. }
  7189. addChangedExistingAnnotation({
  7190. annotationElementId,
  7191. id
  7192. }) {
  7193. (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id);
  7194. }
  7195. removeChangedExistingAnnotation({
  7196. annotationElementId
  7197. }) {
  7198. this.#changedExistingAnnotations?.delete(annotationElementId);
  7199. }
  7200. renderAnnotationElement(annotation) {
  7201. const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
  7202. if (!editorId) {
  7203. return;
  7204. }
  7205. const editor = this.#annotationStorage.getRawValue(editorId);
  7206. if (!editor) {
  7207. return;
  7208. }
  7209. if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
  7210. return;
  7211. }
  7212. editor.renderAnnotationElement(annotation);
  7213. }
  7214. setMissingCanvas(annotationId, annotationElementId, canvas) {
  7215. const editor = this.#missingCanvases?.get(annotationId);
  7216. if (!editor) {
  7217. return;
  7218. }
  7219. editor.setCanvas(annotationElementId, canvas);
  7220. this.#missingCanvases.delete(annotationId);
  7221. }
  7222. addMissingCanvas(annotationId, editor) {
  7223. (this.#missingCanvases ||= new Map()).set(annotationId, editor);
  7224. }
  7225. }
  7226. ;// ./src/display/editor/alt_text.js
  7227. class AltText {
  7228. #altText = null;
  7229. #altTextDecorative = false;
  7230. #altTextButton = null;
  7231. #altTextButtonLabel = null;
  7232. #altTextTooltip = null;
  7233. #altTextTooltipTimeout = null;
  7234. #altTextWasFromKeyBoard = false;
  7235. #badge = null;
  7236. #editor = null;
  7237. #guessedText = null;
  7238. #textWithDisclaimer = null;
  7239. #useNewAltTextFlow = false;
  7240. static #l10nNewButton = null;
  7241. static _l10n = null;
  7242. constructor(editor) {
  7243. this.#editor = editor;
  7244. this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;
  7245. AltText.#l10nNewButton ||= Object.freeze({
  7246. added: "pdfjs-editor-new-alt-text-added-button",
  7247. "added-label": "pdfjs-editor-new-alt-text-added-button-label",
  7248. missing: "pdfjs-editor-new-alt-text-missing-button",
  7249. "missing-label": "pdfjs-editor-new-alt-text-missing-button-label",
  7250. review: "pdfjs-editor-new-alt-text-to-review-button",
  7251. "review-label": "pdfjs-editor-new-alt-text-to-review-button-label"
  7252. });
  7253. }
  7254. static initialize(l10n) {
  7255. AltText._l10n ??= l10n;
  7256. }
  7257. async render() {
  7258. const altText = this.#altTextButton = document.createElement("button");
  7259. altText.className = "altText";
  7260. altText.tabIndex = "0";
  7261. const label = this.#altTextButtonLabel = document.createElement("span");
  7262. altText.append(label);
  7263. if (this.#useNewAltTextFlow) {
  7264. altText.classList.add("new");
  7265. altText.setAttribute("data-l10n-id", AltText.#l10nNewButton.missing);
  7266. label.setAttribute("data-l10n-id", AltText.#l10nNewButton["missing-label"]);
  7267. } else {
  7268. altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button");
  7269. label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label");
  7270. }
  7271. const signal = this.#editor._uiManager._signal;
  7272. altText.addEventListener("contextmenu", noContextMenu, {
  7273. signal
  7274. });
  7275. altText.addEventListener("pointerdown", event => event.stopPropagation(), {
  7276. signal
  7277. });
  7278. const onClick = event => {
  7279. event.preventDefault();
  7280. this.#editor._uiManager.editAltText(this.#editor);
  7281. if (this.#useNewAltTextFlow) {
  7282. this.#editor._reportTelemetry({
  7283. action: "pdfjs.image.alt_text.image_status_label_clicked",
  7284. data: {
  7285. label: this.#label
  7286. }
  7287. });
  7288. }
  7289. };
  7290. altText.addEventListener("click", onClick, {
  7291. capture: true,
  7292. signal
  7293. });
  7294. altText.addEventListener("keydown", event => {
  7295. if (event.target === altText && event.key === "Enter") {
  7296. this.#altTextWasFromKeyBoard = true;
  7297. onClick(event);
  7298. }
  7299. }, {
  7300. signal
  7301. });
  7302. await this.#setState();
  7303. return altText;
  7304. }
  7305. get #label() {
  7306. return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";
  7307. }
  7308. finish() {
  7309. if (!this.#altTextButton) {
  7310. return;
  7311. }
  7312. this.#altTextButton.focus({
  7313. focusVisible: this.#altTextWasFromKeyBoard
  7314. });
  7315. this.#altTextWasFromKeyBoard = false;
  7316. }
  7317. isEmpty() {
  7318. if (this.#useNewAltTextFlow) {
  7319. return this.#altText === null;
  7320. }
  7321. return !this.#altText && !this.#altTextDecorative;
  7322. }
  7323. hasData() {
  7324. if (this.#useNewAltTextFlow) {
  7325. return this.#altText !== null || !!this.#guessedText;
  7326. }
  7327. return this.isEmpty();
  7328. }
  7329. get guessedText() {
  7330. return this.#guessedText;
  7331. }
  7332. async setGuessedText(guessedText) {
  7333. if (this.#altText !== null) {
  7334. return;
  7335. }
  7336. this.#guessedText = guessedText;
  7337. this.#textWithDisclaimer = await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", {
  7338. generatedAltText: guessedText
  7339. });
  7340. this.#setState();
  7341. }
  7342. toggleAltTextBadge(visibility = false) {
  7343. if (!this.#useNewAltTextFlow || this.#altText) {
  7344. this.#badge?.remove();
  7345. this.#badge = null;
  7346. return;
  7347. }
  7348. if (!this.#badge) {
  7349. const badge = this.#badge = document.createElement("div");
  7350. badge.className = "noAltTextBadge";
  7351. this.#editor.div.append(badge);
  7352. }
  7353. this.#badge.classList.toggle("hidden", !visibility);
  7354. }
  7355. serialize(isForCopying) {
  7356. let altText = this.#altText;
  7357. if (!isForCopying && this.#guessedText === altText) {
  7358. altText = this.#textWithDisclaimer;
  7359. }
  7360. return {
  7361. altText,
  7362. decorative: this.#altTextDecorative,
  7363. guessedText: this.#guessedText,
  7364. textWithDisclaimer: this.#textWithDisclaimer
  7365. };
  7366. }
  7367. get data() {
  7368. return {
  7369. altText: this.#altText,
  7370. decorative: this.#altTextDecorative
  7371. };
  7372. }
  7373. set data({
  7374. altText,
  7375. decorative,
  7376. guessedText,
  7377. textWithDisclaimer,
  7378. cancel = false
  7379. }) {
  7380. if (guessedText) {
  7381. this.#guessedText = guessedText;
  7382. this.#textWithDisclaimer = textWithDisclaimer;
  7383. }
  7384. if (this.#altText === altText && this.#altTextDecorative === decorative) {
  7385. return;
  7386. }
  7387. if (!cancel) {
  7388. this.#altText = altText;
  7389. this.#altTextDecorative = decorative;
  7390. }
  7391. this.#setState();
  7392. }
  7393. toggle(enabled = false) {
  7394. if (!this.#altTextButton) {
  7395. return;
  7396. }
  7397. if (!enabled && this.#altTextTooltipTimeout) {
  7398. clearTimeout(this.#altTextTooltipTimeout);
  7399. this.#altTextTooltipTimeout = null;
  7400. }
  7401. this.#altTextButton.disabled = !enabled;
  7402. }
  7403. shown() {
  7404. this.#editor._reportTelemetry({
  7405. action: "pdfjs.image.alt_text.image_status_label_displayed",
  7406. data: {
  7407. label: this.#label
  7408. }
  7409. });
  7410. }
  7411. destroy() {
  7412. this.#altTextButton?.remove();
  7413. this.#altTextButton = null;
  7414. this.#altTextButtonLabel = null;
  7415. this.#altTextTooltip = null;
  7416. this.#badge?.remove();
  7417. this.#badge = null;
  7418. }
  7419. async #setState() {
  7420. const button = this.#altTextButton;
  7421. if (!button) {
  7422. return;
  7423. }
  7424. if (this.#useNewAltTextFlow) {
  7425. button.classList.toggle("done", !!this.#altText);
  7426. button.setAttribute("data-l10n-id", AltText.#l10nNewButton[this.#label]);
  7427. this.#altTextButtonLabel?.setAttribute("data-l10n-id", AltText.#l10nNewButton[`${this.#label}-label`]);
  7428. if (!this.#altText) {
  7429. this.#altTextTooltip?.remove();
  7430. return;
  7431. }
  7432. } else {
  7433. if (!this.#altText && !this.#altTextDecorative) {
  7434. button.classList.remove("done");
  7435. this.#altTextTooltip?.remove();
  7436. return;
  7437. }
  7438. button.classList.add("done");
  7439. button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button");
  7440. }
  7441. let tooltip = this.#altTextTooltip;
  7442. if (!tooltip) {
  7443. this.#altTextTooltip = tooltip = document.createElement("span");
  7444. tooltip.className = "tooltip";
  7445. tooltip.setAttribute("role", "tooltip");
  7446. tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
  7447. const DELAY_TO_SHOW_TOOLTIP = 100;
  7448. const signal = this.#editor._uiManager._signal;
  7449. signal.addEventListener("abort", () => {
  7450. clearTimeout(this.#altTextTooltipTimeout);
  7451. this.#altTextTooltipTimeout = null;
  7452. }, {
  7453. once: true
  7454. });
  7455. button.addEventListener("mouseenter", () => {
  7456. this.#altTextTooltipTimeout = setTimeout(() => {
  7457. this.#altTextTooltipTimeout = null;
  7458. this.#altTextTooltip.classList.add("show");
  7459. this.#editor._reportTelemetry({
  7460. action: "alt_text_tooltip"
  7461. });
  7462. }, DELAY_TO_SHOW_TOOLTIP);
  7463. }, {
  7464. signal
  7465. });
  7466. button.addEventListener("mouseleave", () => {
  7467. if (this.#altTextTooltipTimeout) {
  7468. clearTimeout(this.#altTextTooltipTimeout);
  7469. this.#altTextTooltipTimeout = null;
  7470. }
  7471. this.#altTextTooltip?.classList.remove("show");
  7472. }, {
  7473. signal
  7474. });
  7475. }
  7476. if (this.#altTextDecorative) {
  7477. tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip");
  7478. } else {
  7479. tooltip.removeAttribute("data-l10n-id");
  7480. tooltip.textContent = this.#altText;
  7481. }
  7482. if (!tooltip.parentNode) {
  7483. button.append(tooltip);
  7484. }
  7485. const element = this.#editor.getElementForAltText();
  7486. element?.setAttribute("aria-describedby", tooltip.id);
  7487. }
  7488. }
  7489. ;// ./src/display/touch_manager.js
  7490. class TouchManager {
  7491. #container;
  7492. #isPinching = false;
  7493. #isPinchingStopped = null;
  7494. #isPinchingDisabled;
  7495. #onPinchStart;
  7496. #onPinching;
  7497. #onPinchEnd;
  7498. #pointerDownAC = null;
  7499. #signal;
  7500. #touchInfo = null;
  7501. #touchManagerAC;
  7502. #touchMoveAC = null;
  7503. constructor({
  7504. container,
  7505. isPinchingDisabled = null,
  7506. isPinchingStopped = null,
  7507. onPinchStart = null,
  7508. onPinching = null,
  7509. onPinchEnd = null,
  7510. signal
  7511. }) {
  7512. this.#container = container;
  7513. this.#isPinchingStopped = isPinchingStopped;
  7514. this.#isPinchingDisabled = isPinchingDisabled;
  7515. this.#onPinchStart = onPinchStart;
  7516. this.#onPinching = onPinching;
  7517. this.#onPinchEnd = onPinchEnd;
  7518. this.#touchManagerAC = new AbortController();
  7519. this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]);
  7520. container.addEventListener("touchstart", this.#onTouchStart.bind(this), {
  7521. passive: false,
  7522. signal: this.#signal
  7523. });
  7524. }
  7525. get MIN_TOUCH_DISTANCE_TO_PINCH() {
  7526. return 35 / OutputScale.pixelRatio;
  7527. }
  7528. #onTouchStart(evt) {
  7529. if (this.#isPinchingDisabled?.()) {
  7530. return;
  7531. }
  7532. if (evt.touches.length === 1) {
  7533. if (this.#pointerDownAC) {
  7534. return;
  7535. }
  7536. const pointerDownAC = this.#pointerDownAC = new AbortController();
  7537. const signal = AbortSignal.any([this.#signal, pointerDownAC.signal]);
  7538. const container = this.#container;
  7539. const opts = {
  7540. capture: true,
  7541. signal,
  7542. passive: false
  7543. };
  7544. const cancelPointerDown = e => {
  7545. if (e.pointerType === "touch") {
  7546. this.#pointerDownAC?.abort();
  7547. this.#pointerDownAC = null;
  7548. }
  7549. };
  7550. container.addEventListener("pointerdown", e => {
  7551. if (e.pointerType === "touch") {
  7552. stopEvent(e);
  7553. cancelPointerDown(e);
  7554. }
  7555. }, opts);
  7556. container.addEventListener("pointerup", cancelPointerDown, opts);
  7557. container.addEventListener("pointercancel", cancelPointerDown, opts);
  7558. return;
  7559. }
  7560. if (!this.#touchMoveAC) {
  7561. this.#touchMoveAC = new AbortController();
  7562. const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]);
  7563. const container = this.#container;
  7564. const opt = {
  7565. signal,
  7566. capture: false,
  7567. passive: false
  7568. };
  7569. container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt);
  7570. const onTouchEnd = this.#onTouchEnd.bind(this);
  7571. container.addEventListener("touchend", onTouchEnd, opt);
  7572. container.addEventListener("touchcancel", onTouchEnd, opt);
  7573. opt.capture = true;
  7574. container.addEventListener("pointerdown", stopEvent, opt);
  7575. container.addEventListener("pointermove", stopEvent, opt);
  7576. container.addEventListener("pointercancel", stopEvent, opt);
  7577. container.addEventListener("pointerup", stopEvent, opt);
  7578. this.#onPinchStart?.();
  7579. }
  7580. stopEvent(evt);
  7581. if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) {
  7582. this.#touchInfo = null;
  7583. return;
  7584. }
  7585. let [touch0, touch1] = evt.touches;
  7586. if (touch0.identifier > touch1.identifier) {
  7587. [touch0, touch1] = [touch1, touch0];
  7588. }
  7589. this.#touchInfo = {
  7590. touch0X: touch0.screenX,
  7591. touch0Y: touch0.screenY,
  7592. touch1X: touch1.screenX,
  7593. touch1Y: touch1.screenY
  7594. };
  7595. }
  7596. #onTouchMove(evt) {
  7597. if (!this.#touchInfo || evt.touches.length !== 2) {
  7598. return;
  7599. }
  7600. stopEvent(evt);
  7601. let [touch0, touch1] = evt.touches;
  7602. if (touch0.identifier > touch1.identifier) {
  7603. [touch0, touch1] = [touch1, touch0];
  7604. }
  7605. const {
  7606. screenX: screen0X,
  7607. screenY: screen0Y
  7608. } = touch0;
  7609. const {
  7610. screenX: screen1X,
  7611. screenY: screen1Y
  7612. } = touch1;
  7613. const touchInfo = this.#touchInfo;
  7614. const {
  7615. touch0X: pTouch0X,
  7616. touch0Y: pTouch0Y,
  7617. touch1X: pTouch1X,
  7618. touch1Y: pTouch1Y
  7619. } = touchInfo;
  7620. const prevGapX = pTouch1X - pTouch0X;
  7621. const prevGapY = pTouch1Y - pTouch0Y;
  7622. const currGapX = screen1X - screen0X;
  7623. const currGapY = screen1Y - screen0Y;
  7624. const distance = Math.hypot(currGapX, currGapY) || 1;
  7625. const pDistance = Math.hypot(prevGapX, prevGapY) || 1;
  7626. if (!this.#isPinching && Math.abs(pDistance - distance) <= TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) {
  7627. return;
  7628. }
  7629. touchInfo.touch0X = screen0X;
  7630. touchInfo.touch0Y = screen0Y;
  7631. touchInfo.touch1X = screen1X;
  7632. touchInfo.touch1Y = screen1Y;
  7633. if (!this.#isPinching) {
  7634. this.#isPinching = true;
  7635. return;
  7636. }
  7637. const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2];
  7638. this.#onPinching?.(origin, pDistance, distance);
  7639. }
  7640. #onTouchEnd(evt) {
  7641. if (evt.touches.length >= 2) {
  7642. return;
  7643. }
  7644. if (this.#touchMoveAC) {
  7645. this.#touchMoveAC.abort();
  7646. this.#touchMoveAC = null;
  7647. this.#onPinchEnd?.();
  7648. }
  7649. if (!this.#touchInfo) {
  7650. return;
  7651. }
  7652. stopEvent(evt);
  7653. this.#touchInfo = null;
  7654. this.#isPinching = false;
  7655. }
  7656. destroy() {
  7657. this.#touchManagerAC?.abort();
  7658. this.#touchManagerAC = null;
  7659. this.#pointerDownAC?.abort();
  7660. this.#pointerDownAC = null;
  7661. }
  7662. }
  7663. ;// ./src/display/editor/editor.js
  7664. class AnnotationEditor {
  7665. #accessibilityData = null;
  7666. #allResizerDivs = null;
  7667. #altText = null;
  7668. #disabled = false;
  7669. #dragPointerId = null;
  7670. #dragPointerType = "";
  7671. #keepAspectRatio = false;
  7672. #resizersDiv = null;
  7673. #lastPointerCoords = null;
  7674. #savedDimensions = null;
  7675. #focusAC = null;
  7676. #focusedResizerName = "";
  7677. #hasBeenClicked = false;
  7678. #initialRect = null;
  7679. #isEditing = false;
  7680. #isInEditMode = false;
  7681. #isResizerEnabledForKeyboard = false;
  7682. #moveInDOMTimeout = null;
  7683. #prevDragX = 0;
  7684. #prevDragY = 0;
  7685. #telemetryTimeouts = null;
  7686. #touchManager = null;
  7687. isSelected = false;
  7688. _isCopy = false;
  7689. _editToolbar = null;
  7690. _initialOptions = Object.create(null);
  7691. _initialData = null;
  7692. _isVisible = true;
  7693. _uiManager = null;
  7694. _focusEventsAllowed = true;
  7695. static _l10n = null;
  7696. static _l10nResizer = null;
  7697. #isDraggable = false;
  7698. #zIndex = AnnotationEditor._zIndex++;
  7699. static _borderLineWidth = -1;
  7700. static _colorManager = new ColorManager();
  7701. static _zIndex = 1;
  7702. static _telemetryTimeout = 1000;
  7703. static get _resizerKeyboardManager() {
  7704. const resize = AnnotationEditor.prototype._resizeWithKeyboard;
  7705. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  7706. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  7707. return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
  7708. args: [-small, 0]
  7709. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
  7710. args: [-big, 0]
  7711. }], [["ArrowRight", "mac+ArrowRight"], resize, {
  7712. args: [small, 0]
  7713. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
  7714. args: [big, 0]
  7715. }], [["ArrowUp", "mac+ArrowUp"], resize, {
  7716. args: [0, -small]
  7717. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
  7718. args: [0, -big]
  7719. }], [["ArrowDown", "mac+ArrowDown"], resize, {
  7720. args: [0, small]
  7721. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
  7722. args: [0, big]
  7723. }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]]));
  7724. }
  7725. constructor(parameters) {
  7726. this.parent = parameters.parent;
  7727. this.id = parameters.id;
  7728. this.width = this.height = null;
  7729. this.pageIndex = parameters.parent.pageIndex;
  7730. this.name = parameters.name;
  7731. this.div = null;
  7732. this._uiManager = parameters.uiManager;
  7733. this.annotationElementId = null;
  7734. this._willKeepAspectRatio = false;
  7735. this._initialOptions.isCentered = parameters.isCentered;
  7736. this._structTreeParentId = null;
  7737. const {
  7738. rotation,
  7739. rawDims: {
  7740. pageWidth,
  7741. pageHeight,
  7742. pageX,
  7743. pageY
  7744. }
  7745. } = this.parent.viewport;
  7746. this.rotation = rotation;
  7747. this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
  7748. this.pageDimensions = [pageWidth, pageHeight];
  7749. this.pageTranslation = [pageX, pageY];
  7750. const [width, height] = this.parentDimensions;
  7751. this.x = parameters.x / width;
  7752. this.y = parameters.y / height;
  7753. this.isAttachedToDOM = false;
  7754. this.deleted = false;
  7755. }
  7756. get editorType() {
  7757. return Object.getPrototypeOf(this).constructor._type;
  7758. }
  7759. static get isDrawer() {
  7760. return false;
  7761. }
  7762. static get _defaultLineColor() {
  7763. return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  7764. }
  7765. static deleteAnnotationElement(editor) {
  7766. const fakeEditor = new FakeEditor({
  7767. id: editor.parent.getNextId(),
  7768. parent: editor.parent,
  7769. uiManager: editor._uiManager
  7770. });
  7771. fakeEditor.annotationElementId = editor.annotationElementId;
  7772. fakeEditor.deleted = true;
  7773. fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
  7774. }
  7775. static initialize(l10n, _uiManager) {
  7776. AnnotationEditor._l10n ??= l10n;
  7777. AnnotationEditor._l10nResizer ||= Object.freeze({
  7778. topLeft: "pdfjs-editor-resizer-top-left",
  7779. topMiddle: "pdfjs-editor-resizer-top-middle",
  7780. topRight: "pdfjs-editor-resizer-top-right",
  7781. middleRight: "pdfjs-editor-resizer-middle-right",
  7782. bottomRight: "pdfjs-editor-resizer-bottom-right",
  7783. bottomMiddle: "pdfjs-editor-resizer-bottom-middle",
  7784. bottomLeft: "pdfjs-editor-resizer-bottom-left",
  7785. middleLeft: "pdfjs-editor-resizer-middle-left"
  7786. });
  7787. if (AnnotationEditor._borderLineWidth !== -1) {
  7788. return;
  7789. }
  7790. const style = getComputedStyle(document.documentElement);
  7791. AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
  7792. }
  7793. static updateDefaultParams(_type, _value) {}
  7794. static get defaultPropertiesToUpdate() {
  7795. return [];
  7796. }
  7797. static isHandlingMimeForPasting(mime) {
  7798. return false;
  7799. }
  7800. static paste(item, parent) {
  7801. unreachable("Not implemented");
  7802. }
  7803. get propertiesToUpdate() {
  7804. return [];
  7805. }
  7806. get _isDraggable() {
  7807. return this.#isDraggable;
  7808. }
  7809. set _isDraggable(value) {
  7810. this.#isDraggable = value;
  7811. this.div?.classList.toggle("draggable", value);
  7812. }
  7813. get isEnterHandled() {
  7814. return true;
  7815. }
  7816. center() {
  7817. const [pageWidth, pageHeight] = this.pageDimensions;
  7818. switch (this.parentRotation) {
  7819. case 90:
  7820. this.x -= this.height * pageHeight / (pageWidth * 2);
  7821. this.y += this.width * pageWidth / (pageHeight * 2);
  7822. break;
  7823. case 180:
  7824. this.x += this.width / 2;
  7825. this.y += this.height / 2;
  7826. break;
  7827. case 270:
  7828. this.x += this.height * pageHeight / (pageWidth * 2);
  7829. this.y -= this.width * pageWidth / (pageHeight * 2);
  7830. break;
  7831. default:
  7832. this.x -= this.width / 2;
  7833. this.y -= this.height / 2;
  7834. break;
  7835. }
  7836. this.fixAndSetPosition();
  7837. }
  7838. addCommands(params) {
  7839. this._uiManager.addCommands(params);
  7840. }
  7841. get currentLayer() {
  7842. return this._uiManager.currentLayer;
  7843. }
  7844. setInBackground() {
  7845. this.div.style.zIndex = 0;
  7846. }
  7847. setInForeground() {
  7848. this.div.style.zIndex = this.#zIndex;
  7849. }
  7850. setParent(parent) {
  7851. if (parent !== null) {
  7852. this.pageIndex = parent.pageIndex;
  7853. this.pageDimensions = parent.pageDimensions;
  7854. } else {
  7855. this.#stopResizing();
  7856. }
  7857. this.parent = parent;
  7858. }
  7859. focusin(event) {
  7860. if (!this._focusEventsAllowed) {
  7861. return;
  7862. }
  7863. if (!this.#hasBeenClicked) {
  7864. this.parent.setSelected(this);
  7865. } else {
  7866. this.#hasBeenClicked = false;
  7867. }
  7868. }
  7869. focusout(event) {
  7870. if (!this._focusEventsAllowed) {
  7871. return;
  7872. }
  7873. if (!this.isAttachedToDOM) {
  7874. return;
  7875. }
  7876. const target = event.relatedTarget;
  7877. if (target?.closest(`#${this.id}`)) {
  7878. return;
  7879. }
  7880. event.preventDefault();
  7881. if (!this.parent?.isMultipleSelection) {
  7882. this.commitOrRemove();
  7883. }
  7884. }
  7885. commitOrRemove() {
  7886. if (this.isEmpty()) {
  7887. this.remove();
  7888. } else {
  7889. this.commit();
  7890. }
  7891. }
  7892. commit() {
  7893. this.addToAnnotationStorage();
  7894. }
  7895. addToAnnotationStorage() {
  7896. this._uiManager.addToAnnotationStorage(this);
  7897. }
  7898. setAt(x, y, tx, ty) {
  7899. const [width, height] = this.parentDimensions;
  7900. [tx, ty] = this.screenToPageTranslation(tx, ty);
  7901. this.x = (x + tx) / width;
  7902. this.y = (y + ty) / height;
  7903. this.fixAndSetPosition();
  7904. }
  7905. _moveAfterPaste(baseX, baseY) {
  7906. const [parentWidth, parentHeight] = this.parentDimensions;
  7907. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  7908. this._onTranslated();
  7909. }
  7910. #translate([width, height], x, y) {
  7911. [x, y] = this.screenToPageTranslation(x, y);
  7912. this.x += x / width;
  7913. this.y += y / height;
  7914. this._onTranslating(this.x, this.y);
  7915. this.fixAndSetPosition();
  7916. }
  7917. translate(x, y) {
  7918. this.#translate(this.parentDimensions, x, y);
  7919. }
  7920. translateInPage(x, y) {
  7921. this.#initialRect ||= [this.x, this.y, this.width, this.height];
  7922. this.#translate(this.pageDimensions, x, y);
  7923. this.div.scrollIntoView({
  7924. block: "nearest"
  7925. });
  7926. }
  7927. translationDone() {
  7928. this._onTranslated(this.x, this.y);
  7929. }
  7930. drag(tx, ty) {
  7931. this.#initialRect ||= [this.x, this.y, this.width, this.height];
  7932. const {
  7933. div,
  7934. parentDimensions: [parentWidth, parentHeight]
  7935. } = this;
  7936. this.x += tx / parentWidth;
  7937. this.y += ty / parentHeight;
  7938. if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
  7939. const {
  7940. x,
  7941. y
  7942. } = this.div.getBoundingClientRect();
  7943. if (this.parent.findNewParent(this, x, y)) {
  7944. this.x -= Math.floor(this.x);
  7945. this.y -= Math.floor(this.y);
  7946. }
  7947. }
  7948. let {
  7949. x,
  7950. y
  7951. } = this;
  7952. const [bx, by] = this.getBaseTranslation();
  7953. x += bx;
  7954. y += by;
  7955. const {
  7956. style
  7957. } = div;
  7958. style.left = `${(100 * x).toFixed(2)}%`;
  7959. style.top = `${(100 * y).toFixed(2)}%`;
  7960. this._onTranslating(x, y);
  7961. div.scrollIntoView({
  7962. block: "nearest"
  7963. });
  7964. }
  7965. _onTranslating(x, y) {}
  7966. _onTranslated(x, y) {}
  7967. get _hasBeenMoved() {
  7968. return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y);
  7969. }
  7970. get _hasBeenResized() {
  7971. return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height);
  7972. }
  7973. getBaseTranslation() {
  7974. const [parentWidth, parentHeight] = this.parentDimensions;
  7975. const {
  7976. _borderLineWidth
  7977. } = AnnotationEditor;
  7978. const x = _borderLineWidth / parentWidth;
  7979. const y = _borderLineWidth / parentHeight;
  7980. switch (this.rotation) {
  7981. case 90:
  7982. return [-x, y];
  7983. case 180:
  7984. return [x, y];
  7985. case 270:
  7986. return [x, -y];
  7987. default:
  7988. return [-x, -y];
  7989. }
  7990. }
  7991. get _mustFixPosition() {
  7992. return true;
  7993. }
  7994. fixAndSetPosition(rotation = this.rotation) {
  7995. const {
  7996. div: {
  7997. style
  7998. },
  7999. pageDimensions: [pageWidth, pageHeight]
  8000. } = this;
  8001. let {
  8002. x,
  8003. y,
  8004. width,
  8005. height
  8006. } = this;
  8007. width *= pageWidth;
  8008. height *= pageHeight;
  8009. x *= pageWidth;
  8010. y *= pageHeight;
  8011. if (this._mustFixPosition) {
  8012. switch (rotation) {
  8013. case 0:
  8014. x = MathClamp(x, 0, pageWidth - width);
  8015. y = MathClamp(y, 0, pageHeight - height);
  8016. break;
  8017. case 90:
  8018. x = MathClamp(x, 0, pageWidth - height);
  8019. y = MathClamp(y, width, pageHeight);
  8020. break;
  8021. case 180:
  8022. x = MathClamp(x, width, pageWidth);
  8023. y = MathClamp(y, height, pageHeight);
  8024. break;
  8025. case 270:
  8026. x = MathClamp(x, height, pageWidth);
  8027. y = MathClamp(y, 0, pageHeight - width);
  8028. break;
  8029. }
  8030. }
  8031. this.x = x /= pageWidth;
  8032. this.y = y /= pageHeight;
  8033. const [bx, by] = this.getBaseTranslation();
  8034. x += bx;
  8035. y += by;
  8036. style.left = `${(100 * x).toFixed(2)}%`;
  8037. style.top = `${(100 * y).toFixed(2)}%`;
  8038. this.moveInDOM();
  8039. }
  8040. static #rotatePoint(x, y, angle) {
  8041. switch (angle) {
  8042. case 90:
  8043. return [y, -x];
  8044. case 180:
  8045. return [-x, -y];
  8046. case 270:
  8047. return [-y, x];
  8048. default:
  8049. return [x, y];
  8050. }
  8051. }
  8052. screenToPageTranslation(x, y) {
  8053. return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);
  8054. }
  8055. pageTranslationToScreen(x, y) {
  8056. return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);
  8057. }
  8058. #getRotationMatrix(rotation) {
  8059. switch (rotation) {
  8060. case 90:
  8061. {
  8062. const [pageWidth, pageHeight] = this.pageDimensions;
  8063. return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
  8064. }
  8065. case 180:
  8066. return [-1, 0, 0, -1];
  8067. case 270:
  8068. {
  8069. const [pageWidth, pageHeight] = this.pageDimensions;
  8070. return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
  8071. }
  8072. default:
  8073. return [1, 0, 0, 1];
  8074. }
  8075. }
  8076. get parentScale() {
  8077. return this._uiManager.viewParameters.realScale;
  8078. }
  8079. get parentRotation() {
  8080. return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
  8081. }
  8082. get parentDimensions() {
  8083. const {
  8084. parentScale,
  8085. pageDimensions: [pageWidth, pageHeight]
  8086. } = this;
  8087. return [pageWidth * parentScale, pageHeight * parentScale];
  8088. }
  8089. setDims(width, height) {
  8090. const [parentWidth, parentHeight] = this.parentDimensions;
  8091. const {
  8092. style
  8093. } = this.div;
  8094. style.width = `${(100 * width / parentWidth).toFixed(2)}%`;
  8095. if (!this.#keepAspectRatio) {
  8096. style.height = `${(100 * height / parentHeight).toFixed(2)}%`;
  8097. }
  8098. }
  8099. fixDims() {
  8100. const {
  8101. style
  8102. } = this.div;
  8103. const {
  8104. height,
  8105. width
  8106. } = style;
  8107. const widthPercent = width.endsWith("%");
  8108. const heightPercent = !this.#keepAspectRatio && height.endsWith("%");
  8109. if (widthPercent && heightPercent) {
  8110. return;
  8111. }
  8112. const [parentWidth, parentHeight] = this.parentDimensions;
  8113. if (!widthPercent) {
  8114. style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`;
  8115. }
  8116. if (!this.#keepAspectRatio && !heightPercent) {
  8117. style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`;
  8118. }
  8119. }
  8120. getInitialTranslation() {
  8121. return [0, 0];
  8122. }
  8123. #createResizers() {
  8124. if (this.#resizersDiv) {
  8125. return;
  8126. }
  8127. this.#resizersDiv = document.createElement("div");
  8128. this.#resizersDiv.classList.add("resizers");
  8129. const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
  8130. const signal = this._uiManager._signal;
  8131. for (const name of classes) {
  8132. const div = document.createElement("div");
  8133. this.#resizersDiv.append(div);
  8134. div.classList.add("resizer", name);
  8135. div.setAttribute("data-resizer-name", name);
  8136. div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {
  8137. signal
  8138. });
  8139. div.addEventListener("contextmenu", noContextMenu, {
  8140. signal
  8141. });
  8142. div.tabIndex = -1;
  8143. }
  8144. this.div.prepend(this.#resizersDiv);
  8145. }
  8146. #resizerPointerdown(name, event) {
  8147. event.preventDefault();
  8148. const {
  8149. isMac
  8150. } = util_FeatureTest.platform;
  8151. if (event.button !== 0 || event.ctrlKey && isMac) {
  8152. return;
  8153. }
  8154. this.#altText?.toggle(false);
  8155. const savedDraggable = this._isDraggable;
  8156. this._isDraggable = false;
  8157. this.#lastPointerCoords = [event.screenX, event.screenY];
  8158. const ac = new AbortController();
  8159. const signal = this._uiManager.combinedSignal(ac);
  8160. this.parent.togglePointerEvents(false);
  8161. window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {
  8162. passive: true,
  8163. capture: true,
  8164. signal
  8165. });
  8166. window.addEventListener("touchmove", stopEvent, {
  8167. passive: false,
  8168. signal
  8169. });
  8170. window.addEventListener("contextmenu", noContextMenu, {
  8171. signal
  8172. });
  8173. this.#savedDimensions = {
  8174. savedX: this.x,
  8175. savedY: this.y,
  8176. savedWidth: this.width,
  8177. savedHeight: this.height
  8178. };
  8179. const savedParentCursor = this.parent.div.style.cursor;
  8180. const savedCursor = this.div.style.cursor;
  8181. this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
  8182. const pointerUpCallback = () => {
  8183. ac.abort();
  8184. this.parent.togglePointerEvents(true);
  8185. this.#altText?.toggle(true);
  8186. this._isDraggable = savedDraggable;
  8187. this.parent.div.style.cursor = savedParentCursor;
  8188. this.div.style.cursor = savedCursor;
  8189. this.#addResizeToUndoStack();
  8190. };
  8191. window.addEventListener("pointerup", pointerUpCallback, {
  8192. signal
  8193. });
  8194. window.addEventListener("blur", pointerUpCallback, {
  8195. signal
  8196. });
  8197. }
  8198. #resize(x, y, width, height) {
  8199. this.width = width;
  8200. this.height = height;
  8201. this.x = x;
  8202. this.y = y;
  8203. const [parentWidth, parentHeight] = this.parentDimensions;
  8204. this.setDims(parentWidth * width, parentHeight * height);
  8205. this.fixAndSetPosition();
  8206. this._onResized();
  8207. }
  8208. _onResized() {}
  8209. #addResizeToUndoStack() {
  8210. if (!this.#savedDimensions) {
  8211. return;
  8212. }
  8213. const {
  8214. savedX,
  8215. savedY,
  8216. savedWidth,
  8217. savedHeight
  8218. } = this.#savedDimensions;
  8219. this.#savedDimensions = null;
  8220. const newX = this.x;
  8221. const newY = this.y;
  8222. const newWidth = this.width;
  8223. const newHeight = this.height;
  8224. if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
  8225. return;
  8226. }
  8227. this.addCommands({
  8228. cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight),
  8229. undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight),
  8230. mustExec: true
  8231. });
  8232. }
  8233. static _round(x) {
  8234. return Math.round(x * 10000) / 10000;
  8235. }
  8236. #resizerPointermove(name, event) {
  8237. const [parentWidth, parentHeight] = this.parentDimensions;
  8238. const savedX = this.x;
  8239. const savedY = this.y;
  8240. const savedWidth = this.width;
  8241. const savedHeight = this.height;
  8242. const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
  8243. const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
  8244. const rotationMatrix = this.#getRotationMatrix(this.rotation);
  8245. const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
  8246. const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
  8247. const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];
  8248. let getPoint;
  8249. let getOpposite;
  8250. let isDiagonal = false;
  8251. let isHorizontal = false;
  8252. switch (name) {
  8253. case "topLeft":
  8254. isDiagonal = true;
  8255. getPoint = (w, h) => [0, 0];
  8256. getOpposite = (w, h) => [w, h];
  8257. break;
  8258. case "topMiddle":
  8259. getPoint = (w, h) => [w / 2, 0];
  8260. getOpposite = (w, h) => [w / 2, h];
  8261. break;
  8262. case "topRight":
  8263. isDiagonal = true;
  8264. getPoint = (w, h) => [w, 0];
  8265. getOpposite = (w, h) => [0, h];
  8266. break;
  8267. case "middleRight":
  8268. isHorizontal = true;
  8269. getPoint = (w, h) => [w, h / 2];
  8270. getOpposite = (w, h) => [0, h / 2];
  8271. break;
  8272. case "bottomRight":
  8273. isDiagonal = true;
  8274. getPoint = (w, h) => [w, h];
  8275. getOpposite = (w, h) => [0, 0];
  8276. break;
  8277. case "bottomMiddle":
  8278. getPoint = (w, h) => [w / 2, h];
  8279. getOpposite = (w, h) => [w / 2, 0];
  8280. break;
  8281. case "bottomLeft":
  8282. isDiagonal = true;
  8283. getPoint = (w, h) => [0, h];
  8284. getOpposite = (w, h) => [w, 0];
  8285. break;
  8286. case "middleLeft":
  8287. isHorizontal = true;
  8288. getPoint = (w, h) => [0, h / 2];
  8289. getOpposite = (w, h) => [w, h / 2];
  8290. break;
  8291. }
  8292. const point = getPoint(savedWidth, savedHeight);
  8293. const oppositePoint = getOpposite(savedWidth, savedHeight);
  8294. let transfOppositePoint = transf(...oppositePoint);
  8295. const oppositeX = AnnotationEditor._round(savedX + transfOppositePoint[0]);
  8296. const oppositeY = AnnotationEditor._round(savedY + transfOppositePoint[1]);
  8297. let ratioX = 1;
  8298. let ratioY = 1;
  8299. let deltaX, deltaY;
  8300. if (!event.fromKeyboard) {
  8301. const {
  8302. screenX,
  8303. screenY
  8304. } = event;
  8305. const [lastScreenX, lastScreenY] = this.#lastPointerCoords;
  8306. [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY);
  8307. this.#lastPointerCoords[0] = screenX;
  8308. this.#lastPointerCoords[1] = screenY;
  8309. } else {
  8310. ({
  8311. deltaX,
  8312. deltaY
  8313. } = event);
  8314. }
  8315. [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
  8316. if (isDiagonal) {
  8317. const oldDiag = Math.hypot(savedWidth, savedHeight);
  8318. ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
  8319. } else if (isHorizontal) {
  8320. ratioX = MathClamp(Math.abs(oppositePoint[0] - point[0] - deltaX), minWidth, 1) / savedWidth;
  8321. } else {
  8322. ratioY = MathClamp(Math.abs(oppositePoint[1] - point[1] - deltaY), minHeight, 1) / savedHeight;
  8323. }
  8324. const newWidth = AnnotationEditor._round(savedWidth * ratioX);
  8325. const newHeight = AnnotationEditor._round(savedHeight * ratioY);
  8326. transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
  8327. const newX = oppositeX - transfOppositePoint[0];
  8328. const newY = oppositeY - transfOppositePoint[1];
  8329. this.#initialRect ||= [this.x, this.y, this.width, this.height];
  8330. this.width = newWidth;
  8331. this.height = newHeight;
  8332. this.x = newX;
  8333. this.y = newY;
  8334. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  8335. this.fixAndSetPosition();
  8336. this._onResizing();
  8337. }
  8338. _onResizing() {}
  8339. altTextFinish() {
  8340. this.#altText?.finish();
  8341. }
  8342. async addEditToolbar() {
  8343. if (this._editToolbar || this.#isInEditMode) {
  8344. return this._editToolbar;
  8345. }
  8346. this._editToolbar = new EditorToolbar(this);
  8347. this.div.append(this._editToolbar.render());
  8348. if (this.#altText) {
  8349. await this._editToolbar.addAltText(this.#altText);
  8350. }
  8351. return this._editToolbar;
  8352. }
  8353. removeEditToolbar() {
  8354. if (!this._editToolbar) {
  8355. return;
  8356. }
  8357. this._editToolbar.remove();
  8358. this._editToolbar = null;
  8359. this.#altText?.destroy();
  8360. }
  8361. addContainer(container) {
  8362. const editToolbarDiv = this._editToolbar?.div;
  8363. if (editToolbarDiv) {
  8364. editToolbarDiv.before(container);
  8365. } else {
  8366. this.div.append(container);
  8367. }
  8368. }
  8369. getClientDimensions() {
  8370. return this.div.getBoundingClientRect();
  8371. }
  8372. async addAltTextButton() {
  8373. if (this.#altText) {
  8374. return;
  8375. }
  8376. AltText.initialize(AnnotationEditor._l10n);
  8377. this.#altText = new AltText(this);
  8378. if (this.#accessibilityData) {
  8379. this.#altText.data = this.#accessibilityData;
  8380. this.#accessibilityData = null;
  8381. }
  8382. await this.addEditToolbar();
  8383. }
  8384. get altTextData() {
  8385. return this.#altText?.data;
  8386. }
  8387. set altTextData(data) {
  8388. if (!this.#altText) {
  8389. return;
  8390. }
  8391. this.#altText.data = data;
  8392. }
  8393. get guessedAltText() {
  8394. return this.#altText?.guessedText;
  8395. }
  8396. async setGuessedAltText(text) {
  8397. await this.#altText?.setGuessedText(text);
  8398. }
  8399. serializeAltText(isForCopying) {
  8400. return this.#altText?.serialize(isForCopying);
  8401. }
  8402. hasAltText() {
  8403. return !!this.#altText && !this.#altText.isEmpty();
  8404. }
  8405. hasAltTextData() {
  8406. return this.#altText?.hasData() ?? false;
  8407. }
  8408. render() {
  8409. const div = this.div = document.createElement("div");
  8410. div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  8411. div.className = this.name;
  8412. div.setAttribute("id", this.id);
  8413. div.tabIndex = this.#disabled ? -1 : 0;
  8414. div.setAttribute("role", "application");
  8415. if (this.defaultL10nId) {
  8416. div.setAttribute("data-l10n-id", this.defaultL10nId);
  8417. }
  8418. if (!this._isVisible) {
  8419. div.classList.add("hidden");
  8420. }
  8421. this.setInForeground();
  8422. this.#addFocusListeners();
  8423. const [parentWidth, parentHeight] = this.parentDimensions;
  8424. if (this.parentRotation % 180 !== 0) {
  8425. div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
  8426. div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
  8427. }
  8428. const [tx, ty] = this.getInitialTranslation();
  8429. this.translate(tx, ty);
  8430. bindEvents(this, div, ["keydown", "pointerdown", "dblclick"]);
  8431. if (this.isResizable && this._uiManager._supportsPinchToZoom) {
  8432. this.#touchManager ||= new TouchManager({
  8433. container: div,
  8434. isPinchingDisabled: () => !this.isSelected,
  8435. onPinchStart: this.#touchPinchStartCallback.bind(this),
  8436. onPinching: this.#touchPinchCallback.bind(this),
  8437. onPinchEnd: this.#touchPinchEndCallback.bind(this),
  8438. signal: this._uiManager._signal
  8439. });
  8440. }
  8441. this._uiManager._editorUndoBar?.hide();
  8442. return div;
  8443. }
  8444. #touchPinchStartCallback() {
  8445. this.#savedDimensions = {
  8446. savedX: this.x,
  8447. savedY: this.y,
  8448. savedWidth: this.width,
  8449. savedHeight: this.height
  8450. };
  8451. this.#altText?.toggle(false);
  8452. this.parent.togglePointerEvents(false);
  8453. }
  8454. #touchPinchCallback(_origin, prevDistance, distance) {
  8455. const slowDownFactor = 0.7;
  8456. let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor;
  8457. if (factor === 1) {
  8458. return;
  8459. }
  8460. const rotationMatrix = this.#getRotationMatrix(this.rotation);
  8461. const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
  8462. const [parentWidth, parentHeight] = this.parentDimensions;
  8463. const savedX = this.x;
  8464. const savedY = this.y;
  8465. const savedWidth = this.width;
  8466. const savedHeight = this.height;
  8467. const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
  8468. const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
  8469. factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
  8470. const newWidth = AnnotationEditor._round(savedWidth * factor);
  8471. const newHeight = AnnotationEditor._round(savedHeight * factor);
  8472. if (newWidth === savedWidth && newHeight === savedHeight) {
  8473. return;
  8474. }
  8475. this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight];
  8476. const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2);
  8477. const centerX = AnnotationEditor._round(savedX + transfCenterPoint[0]);
  8478. const centerY = AnnotationEditor._round(savedY + transfCenterPoint[1]);
  8479. const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2);
  8480. this.x = centerX - newTransfCenterPoint[0];
  8481. this.y = centerY - newTransfCenterPoint[1];
  8482. this.width = newWidth;
  8483. this.height = newHeight;
  8484. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  8485. this.fixAndSetPosition();
  8486. this._onResizing();
  8487. }
  8488. #touchPinchEndCallback() {
  8489. this.#altText?.toggle(true);
  8490. this.parent.togglePointerEvents(true);
  8491. this.#addResizeToUndoStack();
  8492. }
  8493. pointerdown(event) {
  8494. const {
  8495. isMac
  8496. } = util_FeatureTest.platform;
  8497. if (event.button !== 0 || event.ctrlKey && isMac) {
  8498. event.preventDefault();
  8499. return;
  8500. }
  8501. this.#hasBeenClicked = true;
  8502. if (this._isDraggable) {
  8503. this.#setUpDragSession(event);
  8504. return;
  8505. }
  8506. this.#selectOnPointerEvent(event);
  8507. }
  8508. #selectOnPointerEvent(event) {
  8509. const {
  8510. isMac
  8511. } = util_FeatureTest.platform;
  8512. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  8513. this.parent.toggleSelected(this);
  8514. } else {
  8515. this.parent.setSelected(this);
  8516. }
  8517. }
  8518. #setUpDragSession(event) {
  8519. const {
  8520. isSelected
  8521. } = this;
  8522. this._uiManager.setUpDragSession();
  8523. let hasDraggingStarted = false;
  8524. const ac = new AbortController();
  8525. const signal = this._uiManager.combinedSignal(ac);
  8526. const opts = {
  8527. capture: true,
  8528. passive: false,
  8529. signal
  8530. };
  8531. const cancelDrag = e => {
  8532. ac.abort();
  8533. this.#dragPointerId = null;
  8534. this.#hasBeenClicked = false;
  8535. if (!this._uiManager.endDragSession()) {
  8536. this.#selectOnPointerEvent(e);
  8537. }
  8538. if (hasDraggingStarted) {
  8539. this._onStopDragging();
  8540. }
  8541. };
  8542. if (isSelected) {
  8543. this.#prevDragX = event.clientX;
  8544. this.#prevDragY = event.clientY;
  8545. this.#dragPointerId = event.pointerId;
  8546. this.#dragPointerType = event.pointerType;
  8547. window.addEventListener("pointermove", e => {
  8548. if (!hasDraggingStarted) {
  8549. hasDraggingStarted = true;
  8550. this._onStartDragging();
  8551. }
  8552. const {
  8553. clientX: x,
  8554. clientY: y,
  8555. pointerId
  8556. } = e;
  8557. if (pointerId !== this.#dragPointerId) {
  8558. stopEvent(e);
  8559. return;
  8560. }
  8561. const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY);
  8562. this.#prevDragX = x;
  8563. this.#prevDragY = y;
  8564. this._uiManager.dragSelectedEditors(tx, ty);
  8565. }, opts);
  8566. window.addEventListener("touchmove", stopEvent, opts);
  8567. window.addEventListener("pointerdown", e => {
  8568. if (e.pointerType === this.#dragPointerType) {
  8569. if (this.#touchManager || e.isPrimary) {
  8570. cancelDrag(e);
  8571. }
  8572. }
  8573. stopEvent(e);
  8574. }, opts);
  8575. }
  8576. const pointerUpCallback = e => {
  8577. if (!this.#dragPointerId || this.#dragPointerId === e.pointerId) {
  8578. cancelDrag(e);
  8579. return;
  8580. }
  8581. stopEvent(e);
  8582. };
  8583. window.addEventListener("pointerup", pointerUpCallback, {
  8584. signal
  8585. });
  8586. window.addEventListener("blur", pointerUpCallback, {
  8587. signal
  8588. });
  8589. }
  8590. _onStartDragging() {}
  8591. _onStopDragging() {}
  8592. moveInDOM() {
  8593. if (this.#moveInDOMTimeout) {
  8594. clearTimeout(this.#moveInDOMTimeout);
  8595. }
  8596. this.#moveInDOMTimeout = setTimeout(() => {
  8597. this.#moveInDOMTimeout = null;
  8598. this.parent?.moveEditorInDOM(this);
  8599. }, 0);
  8600. }
  8601. _setParentAndPosition(parent, x, y) {
  8602. parent.changeParent(this);
  8603. this.x = x;
  8604. this.y = y;
  8605. this.fixAndSetPosition();
  8606. this._onTranslated();
  8607. }
  8608. getRect(tx, ty, rotation = this.rotation) {
  8609. const scale = this.parentScale;
  8610. const [pageWidth, pageHeight] = this.pageDimensions;
  8611. const [pageX, pageY] = this.pageTranslation;
  8612. const shiftX = tx / scale;
  8613. const shiftY = ty / scale;
  8614. const x = this.x * pageWidth;
  8615. const y = this.y * pageHeight;
  8616. const width = this.width * pageWidth;
  8617. const height = this.height * pageHeight;
  8618. switch (rotation) {
  8619. case 0:
  8620. return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
  8621. case 90:
  8622. return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
  8623. case 180:
  8624. return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
  8625. case 270:
  8626. return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
  8627. default:
  8628. throw new Error("Invalid rotation");
  8629. }
  8630. }
  8631. getRectInCurrentCoords(rect, pageHeight) {
  8632. const [x1, y1, x2, y2] = rect;
  8633. const width = x2 - x1;
  8634. const height = y2 - y1;
  8635. switch (this.rotation) {
  8636. case 0:
  8637. return [x1, pageHeight - y2, width, height];
  8638. case 90:
  8639. return [x1, pageHeight - y1, height, width];
  8640. case 180:
  8641. return [x2, pageHeight - y1, width, height];
  8642. case 270:
  8643. return [x2, pageHeight - y2, height, width];
  8644. default:
  8645. throw new Error("Invalid rotation");
  8646. }
  8647. }
  8648. onceAdded(focus) {}
  8649. isEmpty() {
  8650. return false;
  8651. }
  8652. enableEditMode() {
  8653. if (this.isInEditMode()) {
  8654. return false;
  8655. }
  8656. this.parent.setEditingState(false);
  8657. this.#isInEditMode = true;
  8658. return true;
  8659. }
  8660. disableEditMode() {
  8661. if (!this.isInEditMode()) {
  8662. return false;
  8663. }
  8664. this.parent.setEditingState(true);
  8665. this.#isInEditMode = false;
  8666. return true;
  8667. }
  8668. isInEditMode() {
  8669. return this.#isInEditMode;
  8670. }
  8671. shouldGetKeyboardEvents() {
  8672. return this.#isResizerEnabledForKeyboard;
  8673. }
  8674. needsToBeRebuilt() {
  8675. return this.div && !this.isAttachedToDOM;
  8676. }
  8677. get isOnScreen() {
  8678. const {
  8679. top,
  8680. left,
  8681. bottom,
  8682. right
  8683. } = this.getClientDimensions();
  8684. const {
  8685. innerHeight,
  8686. innerWidth
  8687. } = window;
  8688. return left < innerWidth && right > 0 && top < innerHeight && bottom > 0;
  8689. }
  8690. #addFocusListeners() {
  8691. if (this.#focusAC || !this.div) {
  8692. return;
  8693. }
  8694. this.#focusAC = new AbortController();
  8695. const signal = this._uiManager.combinedSignal(this.#focusAC);
  8696. this.div.addEventListener("focusin", this.focusin.bind(this), {
  8697. signal
  8698. });
  8699. this.div.addEventListener("focusout", this.focusout.bind(this), {
  8700. signal
  8701. });
  8702. }
  8703. rebuild() {
  8704. this.#addFocusListeners();
  8705. }
  8706. rotate(_angle) {}
  8707. resize() {}
  8708. serializeDeleted() {
  8709. return {
  8710. id: this.annotationElementId,
  8711. deleted: true,
  8712. pageIndex: this.pageIndex,
  8713. popupRef: this._initialData?.popupRef || ""
  8714. };
  8715. }
  8716. serialize(isForCopying = false, context = null) {
  8717. unreachable("An editor must be serializable");
  8718. }
  8719. static async deserialize(data, parent, uiManager) {
  8720. const editor = new this.prototype.constructor({
  8721. parent,
  8722. id: parent.getNextId(),
  8723. uiManager
  8724. });
  8725. editor.rotation = data.rotation;
  8726. editor.#accessibilityData = data.accessibilityData;
  8727. editor._isCopy = data.isCopy || false;
  8728. const [pageWidth, pageHeight] = editor.pageDimensions;
  8729. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  8730. editor.x = x / pageWidth;
  8731. editor.y = y / pageHeight;
  8732. editor.width = width / pageWidth;
  8733. editor.height = height / pageHeight;
  8734. return editor;
  8735. }
  8736. get hasBeenModified() {
  8737. return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
  8738. }
  8739. remove() {
  8740. this.#focusAC?.abort();
  8741. this.#focusAC = null;
  8742. if (!this.isEmpty()) {
  8743. this.commit();
  8744. }
  8745. if (this.parent) {
  8746. this.parent.remove(this);
  8747. } else {
  8748. this._uiManager.removeEditor(this);
  8749. }
  8750. if (this.#moveInDOMTimeout) {
  8751. clearTimeout(this.#moveInDOMTimeout);
  8752. this.#moveInDOMTimeout = null;
  8753. }
  8754. this.#stopResizing();
  8755. this.removeEditToolbar();
  8756. if (this.#telemetryTimeouts) {
  8757. for (const timeout of this.#telemetryTimeouts.values()) {
  8758. clearTimeout(timeout);
  8759. }
  8760. this.#telemetryTimeouts = null;
  8761. }
  8762. this.parent = null;
  8763. this.#touchManager?.destroy();
  8764. this.#touchManager = null;
  8765. }
  8766. get isResizable() {
  8767. return false;
  8768. }
  8769. makeResizable() {
  8770. if (this.isResizable) {
  8771. this.#createResizers();
  8772. this.#resizersDiv.classList.remove("hidden");
  8773. }
  8774. }
  8775. get toolbarPosition() {
  8776. return null;
  8777. }
  8778. keydown(event) {
  8779. if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
  8780. return;
  8781. }
  8782. this._uiManager.setSelected(this);
  8783. this.#savedDimensions = {
  8784. savedX: this.x,
  8785. savedY: this.y,
  8786. savedWidth: this.width,
  8787. savedHeight: this.height
  8788. };
  8789. const children = this.#resizersDiv.children;
  8790. if (!this.#allResizerDivs) {
  8791. this.#allResizerDivs = Array.from(children);
  8792. const boundResizerKeydown = this.#resizerKeydown.bind(this);
  8793. const boundResizerBlur = this.#resizerBlur.bind(this);
  8794. const signal = this._uiManager._signal;
  8795. for (const div of this.#allResizerDivs) {
  8796. const name = div.getAttribute("data-resizer-name");
  8797. div.setAttribute("role", "spinbutton");
  8798. div.addEventListener("keydown", boundResizerKeydown, {
  8799. signal
  8800. });
  8801. div.addEventListener("blur", boundResizerBlur, {
  8802. signal
  8803. });
  8804. div.addEventListener("focus", this.#resizerFocus.bind(this, name), {
  8805. signal
  8806. });
  8807. div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  8808. }
  8809. }
  8810. const first = this.#allResizerDivs[0];
  8811. let firstPosition = 0;
  8812. for (const div of children) {
  8813. if (div === first) {
  8814. break;
  8815. }
  8816. firstPosition++;
  8817. }
  8818. const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
  8819. if (nextFirstPosition !== firstPosition) {
  8820. if (nextFirstPosition < firstPosition) {
  8821. for (let i = 0; i < firstPosition - nextFirstPosition; i++) {
  8822. this.#resizersDiv.append(this.#resizersDiv.firstChild);
  8823. }
  8824. } else if (nextFirstPosition > firstPosition) {
  8825. for (let i = 0; i < nextFirstPosition - firstPosition; i++) {
  8826. this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
  8827. }
  8828. }
  8829. let i = 0;
  8830. for (const child of children) {
  8831. const div = this.#allResizerDivs[i++];
  8832. const name = div.getAttribute("data-resizer-name");
  8833. child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  8834. }
  8835. }
  8836. this.#setResizerTabIndex(0);
  8837. this.#isResizerEnabledForKeyboard = true;
  8838. this.#resizersDiv.firstChild.focus({
  8839. focusVisible: true
  8840. });
  8841. event.preventDefault();
  8842. event.stopImmediatePropagation();
  8843. }
  8844. #resizerKeydown(event) {
  8845. AnnotationEditor._resizerKeyboardManager.exec(this, event);
  8846. }
  8847. #resizerBlur(event) {
  8848. if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
  8849. this.#stopResizing();
  8850. }
  8851. }
  8852. #resizerFocus(name) {
  8853. this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
  8854. }
  8855. #setResizerTabIndex(value) {
  8856. if (!this.#allResizerDivs) {
  8857. return;
  8858. }
  8859. for (const div of this.#allResizerDivs) {
  8860. div.tabIndex = value;
  8861. }
  8862. }
  8863. _resizeWithKeyboard(x, y) {
  8864. if (!this.#isResizerEnabledForKeyboard) {
  8865. return;
  8866. }
  8867. this.#resizerPointermove(this.#focusedResizerName, {
  8868. deltaX: x,
  8869. deltaY: y,
  8870. fromKeyboard: true
  8871. });
  8872. }
  8873. #stopResizing() {
  8874. this.#isResizerEnabledForKeyboard = false;
  8875. this.#setResizerTabIndex(-1);
  8876. this.#addResizeToUndoStack();
  8877. }
  8878. _stopResizingWithKeyboard() {
  8879. this.#stopResizing();
  8880. this.div.focus();
  8881. }
  8882. select() {
  8883. if (this.isSelected && this._editToolbar) {
  8884. return;
  8885. }
  8886. this.isSelected = true;
  8887. this.makeResizable();
  8888. this.div?.classList.add("selectedEditor");
  8889. if (!this._editToolbar) {
  8890. this.addEditToolbar().then(() => {
  8891. if (this.div?.classList.contains("selectedEditor")) {
  8892. this._editToolbar?.show();
  8893. }
  8894. });
  8895. return;
  8896. }
  8897. this._editToolbar?.show();
  8898. this.#altText?.toggleAltTextBadge(false);
  8899. }
  8900. unselect() {
  8901. if (!this.isSelected) {
  8902. return;
  8903. }
  8904. this.isSelected = false;
  8905. this.#resizersDiv?.classList.add("hidden");
  8906. this.div?.classList.remove("selectedEditor");
  8907. if (this.div?.contains(document.activeElement)) {
  8908. this._uiManager.currentLayer.div.focus({
  8909. preventScroll: true
  8910. });
  8911. }
  8912. this._editToolbar?.hide();
  8913. this.#altText?.toggleAltTextBadge(true);
  8914. }
  8915. updateParams(type, value) {}
  8916. disableEditing() {}
  8917. enableEditing() {}
  8918. get canChangeContent() {
  8919. return false;
  8920. }
  8921. enterInEditMode() {
  8922. if (!this.canChangeContent) {
  8923. return;
  8924. }
  8925. this.enableEditMode();
  8926. this.div.focus();
  8927. }
  8928. dblclick(event) {
  8929. this.enterInEditMode();
  8930. this.parent.updateToolbar({
  8931. mode: this.constructor._editorType,
  8932. editId: this.id
  8933. });
  8934. }
  8935. getElementForAltText() {
  8936. return this.div;
  8937. }
  8938. get contentDiv() {
  8939. return this.div;
  8940. }
  8941. get isEditing() {
  8942. return this.#isEditing;
  8943. }
  8944. set isEditing(value) {
  8945. this.#isEditing = value;
  8946. if (!this.parent) {
  8947. return;
  8948. }
  8949. if (value) {
  8950. this.parent.setSelected(this);
  8951. this.parent.setActiveEditor(this);
  8952. } else {
  8953. this.parent.setActiveEditor(null);
  8954. }
  8955. }
  8956. setAspectRatio(width, height) {
  8957. this.#keepAspectRatio = true;
  8958. const aspectRatio = width / height;
  8959. const {
  8960. style
  8961. } = this.div;
  8962. style.aspectRatio = aspectRatio;
  8963. style.height = "auto";
  8964. }
  8965. static get MIN_SIZE() {
  8966. return 16;
  8967. }
  8968. static canCreateNewEmptyEditor() {
  8969. return true;
  8970. }
  8971. get telemetryInitialData() {
  8972. return {
  8973. action: "added"
  8974. };
  8975. }
  8976. get telemetryFinalData() {
  8977. return null;
  8978. }
  8979. _reportTelemetry(data, mustWait = false) {
  8980. if (mustWait) {
  8981. this.#telemetryTimeouts ||= new Map();
  8982. const {
  8983. action
  8984. } = data;
  8985. let timeout = this.#telemetryTimeouts.get(action);
  8986. if (timeout) {
  8987. clearTimeout(timeout);
  8988. }
  8989. timeout = setTimeout(() => {
  8990. this._reportTelemetry(data);
  8991. this.#telemetryTimeouts.delete(action);
  8992. if (this.#telemetryTimeouts.size === 0) {
  8993. this.#telemetryTimeouts = null;
  8994. }
  8995. }, AnnotationEditor._telemetryTimeout);
  8996. this.#telemetryTimeouts.set(action, timeout);
  8997. return;
  8998. }
  8999. data.type ||= this.editorType;
  9000. this._uiManager._eventBus.dispatch("reporttelemetry", {
  9001. source: this,
  9002. details: {
  9003. type: "editing",
  9004. data
  9005. }
  9006. });
  9007. }
  9008. show(visible = this._isVisible) {
  9009. this.div.classList.toggle("hidden", !visible);
  9010. this._isVisible = visible;
  9011. }
  9012. enable() {
  9013. if (this.div) {
  9014. this.div.tabIndex = 0;
  9015. }
  9016. this.#disabled = false;
  9017. }
  9018. disable() {
  9019. if (this.div) {
  9020. this.div.tabIndex = -1;
  9021. }
  9022. this.#disabled = true;
  9023. }
  9024. renderAnnotationElement(annotation) {
  9025. let content = annotation.container.querySelector(".annotationContent");
  9026. if (!content) {
  9027. content = document.createElement("div");
  9028. content.classList.add("annotationContent", this.editorType);
  9029. annotation.container.prepend(content);
  9030. } else if (content.nodeName === "CANVAS") {
  9031. const canvas = content;
  9032. content = document.createElement("div");
  9033. content.classList.add("annotationContent", this.editorType);
  9034. canvas.before(content);
  9035. }
  9036. return content;
  9037. }
  9038. resetAnnotationElement(annotation) {
  9039. const {
  9040. firstChild
  9041. } = annotation.container;
  9042. if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
  9043. firstChild.remove();
  9044. }
  9045. }
  9046. }
  9047. class FakeEditor extends AnnotationEditor {
  9048. constructor(params) {
  9049. super(params);
  9050. this.annotationElementId = params.annotationElementId;
  9051. this.deleted = true;
  9052. }
  9053. serialize() {
  9054. return this.serializeDeleted();
  9055. }
  9056. }
  9057. ;// ./src/shared/murmurhash3.js
  9058. const SEED = 0xc3d2e1f0;
  9059. const MASK_HIGH = 0xffff0000;
  9060. const MASK_LOW = 0xffff;
  9061. class MurmurHash3_64 {
  9062. constructor(seed) {
  9063. this.h1 = seed ? seed & 0xffffffff : SEED;
  9064. this.h2 = seed ? seed & 0xffffffff : SEED;
  9065. }
  9066. update(input) {
  9067. let data, length;
  9068. if (typeof input === "string") {
  9069. data = new Uint8Array(input.length * 2);
  9070. length = 0;
  9071. for (let i = 0, ii = input.length; i < ii; i++) {
  9072. const code = input.charCodeAt(i);
  9073. if (code <= 0xff) {
  9074. data[length++] = code;
  9075. } else {
  9076. data[length++] = code >>> 8;
  9077. data[length++] = code & 0xff;
  9078. }
  9079. }
  9080. } else if (ArrayBuffer.isView(input)) {
  9081. data = input.slice();
  9082. length = data.byteLength;
  9083. } else {
  9084. throw new Error("Invalid data format, must be a string or TypedArray.");
  9085. }
  9086. const blockCounts = length >> 2;
  9087. const tailLength = length - blockCounts * 4;
  9088. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  9089. let k1 = 0,
  9090. k2 = 0;
  9091. let h1 = this.h1,
  9092. h2 = this.h2;
  9093. const C1 = 0xcc9e2d51,
  9094. C2 = 0x1b873593;
  9095. const C1_LOW = C1 & MASK_LOW,
  9096. C2_LOW = C2 & MASK_LOW;
  9097. for (let i = 0; i < blockCounts; i++) {
  9098. if (i & 1) {
  9099. k1 = dataUint32[i];
  9100. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  9101. k1 = k1 << 15 | k1 >>> 17;
  9102. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  9103. h1 ^= k1;
  9104. h1 = h1 << 13 | h1 >>> 19;
  9105. h1 = h1 * 5 + 0xe6546b64;
  9106. } else {
  9107. k2 = dataUint32[i];
  9108. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  9109. k2 = k2 << 15 | k2 >>> 17;
  9110. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  9111. h2 ^= k2;
  9112. h2 = h2 << 13 | h2 >>> 19;
  9113. h2 = h2 * 5 + 0xe6546b64;
  9114. }
  9115. }
  9116. k1 = 0;
  9117. switch (tailLength) {
  9118. case 3:
  9119. k1 ^= data[blockCounts * 4 + 2] << 16;
  9120. case 2:
  9121. k1 ^= data[blockCounts * 4 + 1] << 8;
  9122. case 1:
  9123. k1 ^= data[blockCounts * 4];
  9124. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  9125. k1 = k1 << 15 | k1 >>> 17;
  9126. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  9127. if (blockCounts & 1) {
  9128. h1 ^= k1;
  9129. } else {
  9130. h2 ^= k1;
  9131. }
  9132. }
  9133. this.h1 = h1;
  9134. this.h2 = h2;
  9135. }
  9136. hexdigest() {
  9137. let h1 = this.h1,
  9138. h2 = this.h2;
  9139. h1 ^= h2 >>> 1;
  9140. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  9141. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  9142. h1 ^= h2 >>> 1;
  9143. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  9144. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  9145. h1 ^= h2 >>> 1;
  9146. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  9147. }
  9148. }
  9149. ;// ./src/display/annotation_storage.js
  9150. const SerializableEmpty = Object.freeze({
  9151. map: null,
  9152. hash: "",
  9153. transfer: undefined
  9154. });
  9155. class AnnotationStorage {
  9156. #modified = false;
  9157. #modifiedIds = null;
  9158. #storage = new Map();
  9159. constructor() {
  9160. this.onSetModified = null;
  9161. this.onResetModified = null;
  9162. this.onAnnotationEditor = null;
  9163. }
  9164. getValue(key, defaultValue) {
  9165. const value = this.#storage.get(key);
  9166. if (value === undefined) {
  9167. return defaultValue;
  9168. }
  9169. return Object.assign(defaultValue, value);
  9170. }
  9171. getRawValue(key) {
  9172. return this.#storage.get(key);
  9173. }
  9174. remove(key) {
  9175. this.#storage.delete(key);
  9176. if (this.#storage.size === 0) {
  9177. this.resetModified();
  9178. }
  9179. if (typeof this.onAnnotationEditor === "function") {
  9180. for (const value of this.#storage.values()) {
  9181. if (value instanceof AnnotationEditor) {
  9182. return;
  9183. }
  9184. }
  9185. this.onAnnotationEditor(null);
  9186. }
  9187. }
  9188. setValue(key, value) {
  9189. const obj = this.#storage.get(key);
  9190. let modified = false;
  9191. if (obj !== undefined) {
  9192. for (const [entry, val] of Object.entries(value)) {
  9193. if (obj[entry] !== val) {
  9194. modified = true;
  9195. obj[entry] = val;
  9196. }
  9197. }
  9198. } else {
  9199. modified = true;
  9200. this.#storage.set(key, value);
  9201. }
  9202. if (modified) {
  9203. this.#setModified();
  9204. }
  9205. if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  9206. this.onAnnotationEditor(value.constructor._type);
  9207. }
  9208. }
  9209. has(key) {
  9210. return this.#storage.has(key);
  9211. }
  9212. get size() {
  9213. return this.#storage.size;
  9214. }
  9215. #setModified() {
  9216. if (!this.#modified) {
  9217. this.#modified = true;
  9218. if (typeof this.onSetModified === "function") {
  9219. this.onSetModified();
  9220. }
  9221. }
  9222. }
  9223. resetModified() {
  9224. if (this.#modified) {
  9225. this.#modified = false;
  9226. if (typeof this.onResetModified === "function") {
  9227. this.onResetModified();
  9228. }
  9229. }
  9230. }
  9231. get print() {
  9232. return new PrintAnnotationStorage(this);
  9233. }
  9234. get serializable() {
  9235. if (this.#storage.size === 0) {
  9236. return SerializableEmpty;
  9237. }
  9238. const map = new Map(),
  9239. hash = new MurmurHash3_64(),
  9240. transfer = [];
  9241. const context = Object.create(null);
  9242. let hasBitmap = false;
  9243. for (const [key, val] of this.#storage) {
  9244. const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;
  9245. if (serialized) {
  9246. map.set(key, serialized);
  9247. hash.update(`${key}:${JSON.stringify(serialized)}`);
  9248. hasBitmap ||= !!serialized.bitmap;
  9249. }
  9250. }
  9251. if (hasBitmap) {
  9252. for (const value of map.values()) {
  9253. if (value.bitmap) {
  9254. transfer.push(value.bitmap);
  9255. }
  9256. }
  9257. }
  9258. return map.size > 0 ? {
  9259. map,
  9260. hash: hash.hexdigest(),
  9261. transfer
  9262. } : SerializableEmpty;
  9263. }
  9264. get editorStats() {
  9265. let stats = null;
  9266. const typeToEditor = new Map();
  9267. for (const value of this.#storage.values()) {
  9268. if (!(value instanceof AnnotationEditor)) {
  9269. continue;
  9270. }
  9271. const editorStats = value.telemetryFinalData;
  9272. if (!editorStats) {
  9273. continue;
  9274. }
  9275. const {
  9276. type
  9277. } = editorStats;
  9278. if (!typeToEditor.has(type)) {
  9279. typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
  9280. }
  9281. stats ||= Object.create(null);
  9282. const map = stats[type] ||= new Map();
  9283. for (const [key, val] of Object.entries(editorStats)) {
  9284. if (key === "type") {
  9285. continue;
  9286. }
  9287. let counters = map.get(key);
  9288. if (!counters) {
  9289. counters = new Map();
  9290. map.set(key, counters);
  9291. }
  9292. const count = counters.get(val) ?? 0;
  9293. counters.set(val, count + 1);
  9294. }
  9295. }
  9296. for (const [type, editor] of typeToEditor) {
  9297. stats[type] = editor.computeTelemetryFinalData(stats[type]);
  9298. }
  9299. return stats;
  9300. }
  9301. resetModifiedIds() {
  9302. this.#modifiedIds = null;
  9303. }
  9304. get modifiedIds() {
  9305. if (this.#modifiedIds) {
  9306. return this.#modifiedIds;
  9307. }
  9308. const ids = [];
  9309. for (const value of this.#storage.values()) {
  9310. if (!(value instanceof AnnotationEditor) || !value.annotationElementId || !value.serialize()) {
  9311. continue;
  9312. }
  9313. ids.push(value.annotationElementId);
  9314. }
  9315. return this.#modifiedIds = {
  9316. ids: new Set(ids),
  9317. hash: ids.join(",")
  9318. };
  9319. }
  9320. [Symbol.iterator]() {
  9321. return this.#storage.entries();
  9322. }
  9323. }
  9324. class PrintAnnotationStorage extends AnnotationStorage {
  9325. #serializable;
  9326. constructor(parent) {
  9327. super();
  9328. const {
  9329. map,
  9330. hash,
  9331. transfer
  9332. } = parent.serializable;
  9333. const clone = structuredClone(map, transfer ? {
  9334. transfer
  9335. } : null);
  9336. this.#serializable = {
  9337. map: clone,
  9338. hash,
  9339. transfer
  9340. };
  9341. }
  9342. get print() {
  9343. unreachable("Should not call PrintAnnotationStorage.print");
  9344. }
  9345. get serializable() {
  9346. return this.#serializable;
  9347. }
  9348. get modifiedIds() {
  9349. return shadow(this, "modifiedIds", {
  9350. ids: new Set(),
  9351. hash: ""
  9352. });
  9353. }
  9354. }
  9355. ;// ./src/display/font_loader.js
  9356. class FontLoader {
  9357. #systemFonts = new Set();
  9358. constructor({
  9359. ownerDocument = globalThis.document,
  9360. styleElement = null
  9361. }) {
  9362. this._document = ownerDocument;
  9363. this.nativeFontFaces = new Set();
  9364. this.styleElement = null;
  9365. this.loadingRequests = [];
  9366. this.loadTestFontId = 0;
  9367. }
  9368. addNativeFontFace(nativeFontFace) {
  9369. this.nativeFontFaces.add(nativeFontFace);
  9370. this._document.fonts.add(nativeFontFace);
  9371. }
  9372. removeNativeFontFace(nativeFontFace) {
  9373. this.nativeFontFaces.delete(nativeFontFace);
  9374. this._document.fonts.delete(nativeFontFace);
  9375. }
  9376. insertRule(rule) {
  9377. if (!this.styleElement) {
  9378. this.styleElement = this._document.createElement("style");
  9379. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  9380. }
  9381. const styleSheet = this.styleElement.sheet;
  9382. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  9383. }
  9384. clear() {
  9385. for (const nativeFontFace of this.nativeFontFaces) {
  9386. this._document.fonts.delete(nativeFontFace);
  9387. }
  9388. this.nativeFontFaces.clear();
  9389. this.#systemFonts.clear();
  9390. if (this.styleElement) {
  9391. this.styleElement.remove();
  9392. this.styleElement = null;
  9393. }
  9394. }
  9395. async loadSystemFont({
  9396. systemFontInfo: info,
  9397. disableFontFace,
  9398. _inspectFont
  9399. }) {
  9400. if (!info || this.#systemFonts.has(info.loadedName)) {
  9401. return;
  9402. }
  9403. assert(!disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
  9404. if (this.isFontLoadingAPISupported) {
  9405. const {
  9406. loadedName,
  9407. src,
  9408. style
  9409. } = info;
  9410. const fontFace = new FontFace(loadedName, src, style);
  9411. this.addNativeFontFace(fontFace);
  9412. try {
  9413. await fontFace.load();
  9414. this.#systemFonts.add(loadedName);
  9415. _inspectFont?.(info);
  9416. } catch {
  9417. warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);
  9418. this.removeNativeFontFace(fontFace);
  9419. }
  9420. return;
  9421. }
  9422. unreachable("Not implemented: loadSystemFont without the Font Loading API.");
  9423. }
  9424. async bind(font) {
  9425. if (font.attached || font.missingFile && !font.systemFontInfo) {
  9426. return;
  9427. }
  9428. font.attached = true;
  9429. if (font.systemFontInfo) {
  9430. await this.loadSystemFont(font);
  9431. return;
  9432. }
  9433. if (this.isFontLoadingAPISupported) {
  9434. const nativeFontFace = font.createNativeFontFace();
  9435. if (nativeFontFace) {
  9436. this.addNativeFontFace(nativeFontFace);
  9437. try {
  9438. await nativeFontFace.loaded;
  9439. } catch (ex) {
  9440. warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  9441. font.disableFontFace = true;
  9442. throw ex;
  9443. }
  9444. }
  9445. return;
  9446. }
  9447. const rule = font.createFontFaceRule();
  9448. if (rule) {
  9449. this.insertRule(rule);
  9450. if (this.isSyncFontLoadingSupported) {
  9451. return;
  9452. }
  9453. await new Promise(resolve => {
  9454. const request = this._queueLoadingCallback(resolve);
  9455. this._prepareFontLoadEvent(font, request);
  9456. });
  9457. }
  9458. }
  9459. get isFontLoadingAPISupported() {
  9460. const hasFonts = !!this._document?.fonts;
  9461. return shadow(this, "isFontLoadingAPISupported", hasFonts);
  9462. }
  9463. get isSyncFontLoadingSupported() {
  9464. return shadow(this, "isSyncFontLoadingSupported", isNodeJS || util_FeatureTest.platform.isFirefox);
  9465. }
  9466. _queueLoadingCallback(callback) {
  9467. function completeRequest() {
  9468. assert(!request.done, "completeRequest() cannot be called twice.");
  9469. request.done = true;
  9470. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  9471. const otherRequest = loadingRequests.shift();
  9472. setTimeout(otherRequest.callback, 0);
  9473. }
  9474. }
  9475. const {
  9476. loadingRequests
  9477. } = this;
  9478. const request = {
  9479. done: false,
  9480. complete: completeRequest,
  9481. callback
  9482. };
  9483. loadingRequests.push(request);
  9484. return request;
  9485. }
  9486. get _loadTestFont() {
  9487. const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
  9488. return shadow(this, "_loadTestFont", testFont);
  9489. }
  9490. _prepareFontLoadEvent(font, request) {
  9491. function int32(data, offset) {
  9492. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  9493. }
  9494. function spliceString(s, offset, remove, insert) {
  9495. const chunk1 = s.substring(0, offset);
  9496. const chunk2 = s.substring(offset + remove);
  9497. return chunk1 + insert + chunk2;
  9498. }
  9499. let i, ii;
  9500. const canvas = this._document.createElement("canvas");
  9501. canvas.width = 1;
  9502. canvas.height = 1;
  9503. const ctx = canvas.getContext("2d");
  9504. let called = 0;
  9505. function isFontReady(name, callback) {
  9506. if (++called > 30) {
  9507. warn("Load test font never loaded.");
  9508. callback();
  9509. return;
  9510. }
  9511. ctx.font = "30px " + name;
  9512. ctx.fillText(".", 0, 20);
  9513. const imageData = ctx.getImageData(0, 0, 1, 1);
  9514. if (imageData.data[3] > 0) {
  9515. callback();
  9516. return;
  9517. }
  9518. setTimeout(isFontReady.bind(null, name, callback));
  9519. }
  9520. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  9521. let data = this._loadTestFont;
  9522. const COMMENT_OFFSET = 976;
  9523. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  9524. const CFF_CHECKSUM_OFFSET = 16;
  9525. const XXXX_VALUE = 0x58585858;
  9526. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  9527. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  9528. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  9529. }
  9530. if (i < loadTestFontId.length) {
  9531. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  9532. }
  9533. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  9534. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  9535. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  9536. this.insertRule(rule);
  9537. const div = this._document.createElement("div");
  9538. div.style.visibility = "hidden";
  9539. div.style.width = div.style.height = "10px";
  9540. div.style.position = "absolute";
  9541. div.style.top = div.style.left = "0px";
  9542. for (const name of [font.loadedName, loadTestFontId]) {
  9543. const span = this._document.createElement("span");
  9544. span.textContent = "Hi";
  9545. span.style.fontFamily = name;
  9546. div.append(span);
  9547. }
  9548. this._document.body.append(div);
  9549. isFontReady(loadTestFontId, () => {
  9550. div.remove();
  9551. request.complete();
  9552. });
  9553. }
  9554. }
  9555. class FontFaceObject {
  9556. constructor(translatedData, inspectFont = null) {
  9557. this.compiledGlyphs = Object.create(null);
  9558. for (const i in translatedData) {
  9559. this[i] = translatedData[i];
  9560. }
  9561. this._inspectFont = inspectFont;
  9562. }
  9563. createNativeFontFace() {
  9564. if (!this.data || this.disableFontFace) {
  9565. return null;
  9566. }
  9567. let nativeFontFace;
  9568. if (!this.cssFontInfo) {
  9569. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  9570. } else {
  9571. const css = {
  9572. weight: this.cssFontInfo.fontWeight
  9573. };
  9574. if (this.cssFontInfo.italicAngle) {
  9575. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  9576. }
  9577. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  9578. }
  9579. this._inspectFont?.(this);
  9580. return nativeFontFace;
  9581. }
  9582. createFontFaceRule() {
  9583. if (!this.data || this.disableFontFace) {
  9584. return null;
  9585. }
  9586. const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;
  9587. let rule;
  9588. if (!this.cssFontInfo) {
  9589. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  9590. } else {
  9591. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  9592. if (this.cssFontInfo.italicAngle) {
  9593. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  9594. }
  9595. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  9596. }
  9597. this._inspectFont?.(this, url);
  9598. return rule;
  9599. }
  9600. getPathGenerator(objs, character) {
  9601. if (this.compiledGlyphs[character] !== undefined) {
  9602. return this.compiledGlyphs[character];
  9603. }
  9604. const objId = this.loadedName + "_path_" + character;
  9605. let cmds;
  9606. try {
  9607. cmds = objs.get(objId);
  9608. } catch (ex) {
  9609. warn(`getPathGenerator - ignoring character: "${ex}".`);
  9610. }
  9611. const path = new Path2D(cmds || "");
  9612. if (!this.fontExtraProperties) {
  9613. objs.delete(objId);
  9614. }
  9615. return this.compiledGlyphs[character] = path;
  9616. }
  9617. }
  9618. ;// ./src/display/api_utils.js
  9619. function getUrlProp(val) {
  9620. if (val instanceof URL) {
  9621. return val.href;
  9622. }
  9623. if (typeof val === "string") {
  9624. if (isNodeJS) {
  9625. return val;
  9626. }
  9627. const url = URL.parse(val, window.location);
  9628. if (url) {
  9629. return url.href;
  9630. }
  9631. }
  9632. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  9633. }
  9634. function getDataProp(val) {
  9635. if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
  9636. throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
  9637. }
  9638. if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
  9639. return val;
  9640. }
  9641. if (typeof val === "string") {
  9642. return stringToBytes(val);
  9643. }
  9644. if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) {
  9645. return new Uint8Array(val);
  9646. }
  9647. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  9648. }
  9649. function getFactoryUrlProp(val) {
  9650. if (typeof val !== "string") {
  9651. return null;
  9652. }
  9653. if (val.endsWith("/")) {
  9654. return val;
  9655. }
  9656. throw new Error(`Invalid factory url: "${val}" must include trailing slash.`);
  9657. }
  9658. const isRefProxy = v => typeof v === "object" && Number.isInteger(v?.num) && v.num >= 0 && Number.isInteger(v?.gen) && v.gen >= 0;
  9659. const isNameProxy = v => typeof v === "object" && typeof v?.name === "string";
  9660. const isValidExplicitDest = _isValidExplicitDest.bind(null, isRefProxy, isNameProxy);
  9661. class LoopbackPort {
  9662. #listeners = new Map();
  9663. #deferred = Promise.resolve();
  9664. postMessage(obj, transfer) {
  9665. const event = {
  9666. data: structuredClone(obj, transfer ? {
  9667. transfer
  9668. } : null)
  9669. };
  9670. this.#deferred.then(() => {
  9671. for (const [listener] of this.#listeners) {
  9672. listener.call(this, event);
  9673. }
  9674. });
  9675. }
  9676. addEventListener(name, listener, options = null) {
  9677. let rmAbort = null;
  9678. if (options?.signal instanceof AbortSignal) {
  9679. const {
  9680. signal
  9681. } = options;
  9682. if (signal.aborted) {
  9683. warn("LoopbackPort - cannot use an `aborted` signal.");
  9684. return;
  9685. }
  9686. const onAbort = () => this.removeEventListener(name, listener);
  9687. rmAbort = () => signal.removeEventListener("abort", onAbort);
  9688. signal.addEventListener("abort", onAbort);
  9689. }
  9690. this.#listeners.set(listener, rmAbort);
  9691. }
  9692. removeEventListener(name, listener) {
  9693. const rmAbort = this.#listeners.get(listener);
  9694. rmAbort?.();
  9695. this.#listeners.delete(listener);
  9696. }
  9697. terminate() {
  9698. for (const [, rmAbort] of this.#listeners) {
  9699. rmAbort?.();
  9700. }
  9701. this.#listeners.clear();
  9702. }
  9703. }
  9704. ;// ./src/shared/message_handler.js
  9705. const CallbackKind = {
  9706. DATA: 1,
  9707. ERROR: 2
  9708. };
  9709. const StreamKind = {
  9710. CANCEL: 1,
  9711. CANCEL_COMPLETE: 2,
  9712. CLOSE: 3,
  9713. ENQUEUE: 4,
  9714. ERROR: 5,
  9715. PULL: 6,
  9716. PULL_COMPLETE: 7,
  9717. START_COMPLETE: 8
  9718. };
  9719. function onFn() {}
  9720. function wrapReason(ex) {
  9721. if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof PasswordException || ex instanceof ResponseException || ex instanceof UnknownErrorException) {
  9722. return ex;
  9723. }
  9724. if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) {
  9725. unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  9726. }
  9727. switch (ex.name) {
  9728. case "AbortException":
  9729. return new AbortException(ex.message);
  9730. case "InvalidPDFException":
  9731. return new InvalidPDFException(ex.message);
  9732. case "PasswordException":
  9733. return new PasswordException(ex.message, ex.code);
  9734. case "ResponseException":
  9735. return new ResponseException(ex.message, ex.status, ex.missing);
  9736. case "UnknownErrorException":
  9737. return new UnknownErrorException(ex.message, ex.details);
  9738. }
  9739. return new UnknownErrorException(ex.message, ex.toString());
  9740. }
  9741. class MessageHandler {
  9742. #messageAC = new AbortController();
  9743. constructor(sourceName, targetName, comObj) {
  9744. this.sourceName = sourceName;
  9745. this.targetName = targetName;
  9746. this.comObj = comObj;
  9747. this.callbackId = 1;
  9748. this.streamId = 1;
  9749. this.streamSinks = Object.create(null);
  9750. this.streamControllers = Object.create(null);
  9751. this.callbackCapabilities = Object.create(null);
  9752. this.actionHandler = Object.create(null);
  9753. comObj.addEventListener("message", this.#onMessage.bind(this), {
  9754. signal: this.#messageAC.signal
  9755. });
  9756. }
  9757. #onMessage({
  9758. data
  9759. }) {
  9760. if (data.targetName !== this.sourceName) {
  9761. return;
  9762. }
  9763. if (data.stream) {
  9764. this.#processStreamMessage(data);
  9765. return;
  9766. }
  9767. if (data.callback) {
  9768. const callbackId = data.callbackId;
  9769. const capability = this.callbackCapabilities[callbackId];
  9770. if (!capability) {
  9771. throw new Error(`Cannot resolve callback ${callbackId}`);
  9772. }
  9773. delete this.callbackCapabilities[callbackId];
  9774. if (data.callback === CallbackKind.DATA) {
  9775. capability.resolve(data.data);
  9776. } else if (data.callback === CallbackKind.ERROR) {
  9777. capability.reject(wrapReason(data.reason));
  9778. } else {
  9779. throw new Error("Unexpected callback case");
  9780. }
  9781. return;
  9782. }
  9783. const action = this.actionHandler[data.action];
  9784. if (!action) {
  9785. throw new Error(`Unknown action from worker: ${data.action}`);
  9786. }
  9787. if (data.callbackId) {
  9788. const sourceName = this.sourceName,
  9789. targetName = data.sourceName,
  9790. comObj = this.comObj;
  9791. Promise.try(action, data.data).then(function (result) {
  9792. comObj.postMessage({
  9793. sourceName,
  9794. targetName,
  9795. callback: CallbackKind.DATA,
  9796. callbackId: data.callbackId,
  9797. data: result
  9798. });
  9799. }, function (reason) {
  9800. comObj.postMessage({
  9801. sourceName,
  9802. targetName,
  9803. callback: CallbackKind.ERROR,
  9804. callbackId: data.callbackId,
  9805. reason: wrapReason(reason)
  9806. });
  9807. });
  9808. return;
  9809. }
  9810. if (data.streamId) {
  9811. this.#createStreamSink(data);
  9812. return;
  9813. }
  9814. action(data.data);
  9815. }
  9816. on(actionName, handler) {
  9817. const ah = this.actionHandler;
  9818. if (ah[actionName]) {
  9819. throw new Error(`There is already an actionName called "${actionName}"`);
  9820. }
  9821. ah[actionName] = handler;
  9822. }
  9823. send(actionName, data, transfers) {
  9824. this.comObj.postMessage({
  9825. sourceName: this.sourceName,
  9826. targetName: this.targetName,
  9827. action: actionName,
  9828. data
  9829. }, transfers);
  9830. }
  9831. sendWithPromise(actionName, data, transfers) {
  9832. const callbackId = this.callbackId++;
  9833. const capability = Promise.withResolvers();
  9834. this.callbackCapabilities[callbackId] = capability;
  9835. try {
  9836. this.comObj.postMessage({
  9837. sourceName: this.sourceName,
  9838. targetName: this.targetName,
  9839. action: actionName,
  9840. callbackId,
  9841. data
  9842. }, transfers);
  9843. } catch (ex) {
  9844. capability.reject(ex);
  9845. }
  9846. return capability.promise;
  9847. }
  9848. sendWithStream(actionName, data, queueingStrategy, transfers) {
  9849. const streamId = this.streamId++,
  9850. sourceName = this.sourceName,
  9851. targetName = this.targetName,
  9852. comObj = this.comObj;
  9853. return new ReadableStream({
  9854. start: controller => {
  9855. const startCapability = Promise.withResolvers();
  9856. this.streamControllers[streamId] = {
  9857. controller,
  9858. startCall: startCapability,
  9859. pullCall: null,
  9860. cancelCall: null,
  9861. isClosed: false
  9862. };
  9863. comObj.postMessage({
  9864. sourceName,
  9865. targetName,
  9866. action: actionName,
  9867. streamId,
  9868. data,
  9869. desiredSize: controller.desiredSize
  9870. }, transfers);
  9871. return startCapability.promise;
  9872. },
  9873. pull: controller => {
  9874. const pullCapability = Promise.withResolvers();
  9875. this.streamControllers[streamId].pullCall = pullCapability;
  9876. comObj.postMessage({
  9877. sourceName,
  9878. targetName,
  9879. stream: StreamKind.PULL,
  9880. streamId,
  9881. desiredSize: controller.desiredSize
  9882. });
  9883. return pullCapability.promise;
  9884. },
  9885. cancel: reason => {
  9886. assert(reason instanceof Error, "cancel must have a valid reason");
  9887. const cancelCapability = Promise.withResolvers();
  9888. this.streamControllers[streamId].cancelCall = cancelCapability;
  9889. this.streamControllers[streamId].isClosed = true;
  9890. comObj.postMessage({
  9891. sourceName,
  9892. targetName,
  9893. stream: StreamKind.CANCEL,
  9894. streamId,
  9895. reason: wrapReason(reason)
  9896. });
  9897. return cancelCapability.promise;
  9898. }
  9899. }, queueingStrategy);
  9900. }
  9901. #createStreamSink(data) {
  9902. const streamId = data.streamId,
  9903. sourceName = this.sourceName,
  9904. targetName = data.sourceName,
  9905. comObj = this.comObj;
  9906. const self = this,
  9907. action = this.actionHandler[data.action];
  9908. const streamSink = {
  9909. enqueue(chunk, size = 1, transfers) {
  9910. if (this.isCancelled) {
  9911. return;
  9912. }
  9913. const lastDesiredSize = this.desiredSize;
  9914. this.desiredSize -= size;
  9915. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  9916. this.sinkCapability = Promise.withResolvers();
  9917. this.ready = this.sinkCapability.promise;
  9918. }
  9919. comObj.postMessage({
  9920. sourceName,
  9921. targetName,
  9922. stream: StreamKind.ENQUEUE,
  9923. streamId,
  9924. chunk
  9925. }, transfers);
  9926. },
  9927. close() {
  9928. if (this.isCancelled) {
  9929. return;
  9930. }
  9931. this.isCancelled = true;
  9932. comObj.postMessage({
  9933. sourceName,
  9934. targetName,
  9935. stream: StreamKind.CLOSE,
  9936. streamId
  9937. });
  9938. delete self.streamSinks[streamId];
  9939. },
  9940. error(reason) {
  9941. assert(reason instanceof Error, "error must have a valid reason");
  9942. if (this.isCancelled) {
  9943. return;
  9944. }
  9945. this.isCancelled = true;
  9946. comObj.postMessage({
  9947. sourceName,
  9948. targetName,
  9949. stream: StreamKind.ERROR,
  9950. streamId,
  9951. reason: wrapReason(reason)
  9952. });
  9953. },
  9954. sinkCapability: Promise.withResolvers(),
  9955. onPull: null,
  9956. onCancel: null,
  9957. isCancelled: false,
  9958. desiredSize: data.desiredSize,
  9959. ready: null
  9960. };
  9961. streamSink.sinkCapability.resolve();
  9962. streamSink.ready = streamSink.sinkCapability.promise;
  9963. this.streamSinks[streamId] = streamSink;
  9964. Promise.try(action, data.data, streamSink).then(function () {
  9965. comObj.postMessage({
  9966. sourceName,
  9967. targetName,
  9968. stream: StreamKind.START_COMPLETE,
  9969. streamId,
  9970. success: true
  9971. });
  9972. }, function (reason) {
  9973. comObj.postMessage({
  9974. sourceName,
  9975. targetName,
  9976. stream: StreamKind.START_COMPLETE,
  9977. streamId,
  9978. reason: wrapReason(reason)
  9979. });
  9980. });
  9981. }
  9982. #processStreamMessage(data) {
  9983. const streamId = data.streamId,
  9984. sourceName = this.sourceName,
  9985. targetName = data.sourceName,
  9986. comObj = this.comObj;
  9987. const streamController = this.streamControllers[streamId],
  9988. streamSink = this.streamSinks[streamId];
  9989. switch (data.stream) {
  9990. case StreamKind.START_COMPLETE:
  9991. if (data.success) {
  9992. streamController.startCall.resolve();
  9993. } else {
  9994. streamController.startCall.reject(wrapReason(data.reason));
  9995. }
  9996. break;
  9997. case StreamKind.PULL_COMPLETE:
  9998. if (data.success) {
  9999. streamController.pullCall.resolve();
  10000. } else {
  10001. streamController.pullCall.reject(wrapReason(data.reason));
  10002. }
  10003. break;
  10004. case StreamKind.PULL:
  10005. if (!streamSink) {
  10006. comObj.postMessage({
  10007. sourceName,
  10008. targetName,
  10009. stream: StreamKind.PULL_COMPLETE,
  10010. streamId,
  10011. success: true
  10012. });
  10013. break;
  10014. }
  10015. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  10016. streamSink.sinkCapability.resolve();
  10017. }
  10018. streamSink.desiredSize = data.desiredSize;
  10019. Promise.try(streamSink.onPull || onFn).then(function () {
  10020. comObj.postMessage({
  10021. sourceName,
  10022. targetName,
  10023. stream: StreamKind.PULL_COMPLETE,
  10024. streamId,
  10025. success: true
  10026. });
  10027. }, function (reason) {
  10028. comObj.postMessage({
  10029. sourceName,
  10030. targetName,
  10031. stream: StreamKind.PULL_COMPLETE,
  10032. streamId,
  10033. reason: wrapReason(reason)
  10034. });
  10035. });
  10036. break;
  10037. case StreamKind.ENQUEUE:
  10038. assert(streamController, "enqueue should have stream controller");
  10039. if (streamController.isClosed) {
  10040. break;
  10041. }
  10042. streamController.controller.enqueue(data.chunk);
  10043. break;
  10044. case StreamKind.CLOSE:
  10045. assert(streamController, "close should have stream controller");
  10046. if (streamController.isClosed) {
  10047. break;
  10048. }
  10049. streamController.isClosed = true;
  10050. streamController.controller.close();
  10051. this.#deleteStreamController(streamController, streamId);
  10052. break;
  10053. case StreamKind.ERROR:
  10054. assert(streamController, "error should have stream controller");
  10055. streamController.controller.error(wrapReason(data.reason));
  10056. this.#deleteStreamController(streamController, streamId);
  10057. break;
  10058. case StreamKind.CANCEL_COMPLETE:
  10059. if (data.success) {
  10060. streamController.cancelCall.resolve();
  10061. } else {
  10062. streamController.cancelCall.reject(wrapReason(data.reason));
  10063. }
  10064. this.#deleteStreamController(streamController, streamId);
  10065. break;
  10066. case StreamKind.CANCEL:
  10067. if (!streamSink) {
  10068. break;
  10069. }
  10070. const dataReason = wrapReason(data.reason);
  10071. Promise.try(streamSink.onCancel || onFn, dataReason).then(function () {
  10072. comObj.postMessage({
  10073. sourceName,
  10074. targetName,
  10075. stream: StreamKind.CANCEL_COMPLETE,
  10076. streamId,
  10077. success: true
  10078. });
  10079. }, function (reason) {
  10080. comObj.postMessage({
  10081. sourceName,
  10082. targetName,
  10083. stream: StreamKind.CANCEL_COMPLETE,
  10084. streamId,
  10085. reason: wrapReason(reason)
  10086. });
  10087. });
  10088. streamSink.sinkCapability.reject(dataReason);
  10089. streamSink.isCancelled = true;
  10090. delete this.streamSinks[streamId];
  10091. break;
  10092. default:
  10093. throw new Error("Unexpected stream case");
  10094. }
  10095. }
  10096. async #deleteStreamController(streamController, streamId) {
  10097. await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
  10098. delete this.streamControllers[streamId];
  10099. }
  10100. destroy() {
  10101. this.#messageAC?.abort();
  10102. this.#messageAC = null;
  10103. }
  10104. }
  10105. ;// ./src/display/canvas_factory.js
  10106. class BaseCanvasFactory {
  10107. #enableHWA = false;
  10108. constructor({
  10109. enableHWA = false
  10110. }) {
  10111. this.#enableHWA = enableHWA;
  10112. }
  10113. create(width, height) {
  10114. if (width <= 0 || height <= 0) {
  10115. throw new Error("Invalid canvas size");
  10116. }
  10117. const canvas = this._createCanvas(width, height);
  10118. return {
  10119. canvas,
  10120. context: canvas.getContext("2d", {
  10121. willReadFrequently: !this.#enableHWA
  10122. })
  10123. };
  10124. }
  10125. reset(canvasAndContext, width, height) {
  10126. if (!canvasAndContext.canvas) {
  10127. throw new Error("Canvas is not specified");
  10128. }
  10129. if (width <= 0 || height <= 0) {
  10130. throw new Error("Invalid canvas size");
  10131. }
  10132. canvasAndContext.canvas.width = width;
  10133. canvasAndContext.canvas.height = height;
  10134. }
  10135. destroy(canvasAndContext) {
  10136. if (!canvasAndContext.canvas) {
  10137. throw new Error("Canvas is not specified");
  10138. }
  10139. canvasAndContext.canvas.width = 0;
  10140. canvasAndContext.canvas.height = 0;
  10141. canvasAndContext.canvas = null;
  10142. canvasAndContext.context = null;
  10143. }
  10144. _createCanvas(width, height) {
  10145. unreachable("Abstract method `_createCanvas` called.");
  10146. }
  10147. }
  10148. class DOMCanvasFactory extends BaseCanvasFactory {
  10149. constructor({
  10150. ownerDocument = globalThis.document,
  10151. enableHWA = false
  10152. }) {
  10153. super({
  10154. enableHWA
  10155. });
  10156. this._document = ownerDocument;
  10157. }
  10158. _createCanvas(width, height) {
  10159. const canvas = this._document.createElement("canvas");
  10160. canvas.width = width;
  10161. canvas.height = height;
  10162. return canvas;
  10163. }
  10164. }
  10165. ;// ./src/display/cmap_reader_factory.js
  10166. class BaseCMapReaderFactory {
  10167. constructor({
  10168. baseUrl = null,
  10169. isCompressed = true
  10170. }) {
  10171. this.baseUrl = baseUrl;
  10172. this.isCompressed = isCompressed;
  10173. }
  10174. async fetch({
  10175. name
  10176. }) {
  10177. if (!this.baseUrl) {
  10178. throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");
  10179. }
  10180. if (!name) {
  10181. throw new Error("CMap name must be specified.");
  10182. }
  10183. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  10184. return this._fetch(url).then(cMapData => ({
  10185. cMapData,
  10186. isCompressed: this.isCompressed
  10187. })).catch(reason => {
  10188. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  10189. });
  10190. }
  10191. async _fetch(url) {
  10192. unreachable("Abstract method `_fetch` called.");
  10193. }
  10194. }
  10195. class DOMCMapReaderFactory extends BaseCMapReaderFactory {
  10196. async _fetch(url) {
  10197. const data = await fetchData(url, this.isCompressed ? "arraybuffer" : "text");
  10198. return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data);
  10199. }
  10200. }
  10201. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.filter.js
  10202. var es_iterator_filter = __webpack_require__(2489);
  10203. ;// ./src/display/filter_factory.js
  10204. class BaseFilterFactory {
  10205. addFilter(maps) {
  10206. return "none";
  10207. }
  10208. addHCMFilter(fgColor, bgColor) {
  10209. return "none";
  10210. }
  10211. addAlphaFilter(map) {
  10212. return "none";
  10213. }
  10214. addLuminosityFilter(map) {
  10215. return "none";
  10216. }
  10217. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  10218. return "none";
  10219. }
  10220. destroy(keepHCM = false) {}
  10221. }
  10222. class DOMFilterFactory extends BaseFilterFactory {
  10223. #baseUrl;
  10224. #_cache;
  10225. #_defs;
  10226. #docId;
  10227. #document;
  10228. #_hcmCache;
  10229. #id = 0;
  10230. constructor({
  10231. docId,
  10232. ownerDocument = globalThis.document
  10233. }) {
  10234. super();
  10235. this.#docId = docId;
  10236. this.#document = ownerDocument;
  10237. }
  10238. get #cache() {
  10239. return this.#_cache ||= new Map();
  10240. }
  10241. get #hcmCache() {
  10242. return this.#_hcmCache ||= new Map();
  10243. }
  10244. get #defs() {
  10245. if (!this.#_defs) {
  10246. const div = this.#document.createElement("div");
  10247. const {
  10248. style
  10249. } = div;
  10250. style.visibility = "hidden";
  10251. style.contain = "strict";
  10252. style.width = style.height = 0;
  10253. style.position = "absolute";
  10254. style.top = style.left = 0;
  10255. style.zIndex = -1;
  10256. const svg = this.#document.createElementNS(SVG_NS, "svg");
  10257. svg.setAttribute("width", 0);
  10258. svg.setAttribute("height", 0);
  10259. this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
  10260. div.append(svg);
  10261. svg.append(this.#_defs);
  10262. this.#document.body.append(div);
  10263. }
  10264. return this.#_defs;
  10265. }
  10266. #createTables(maps) {
  10267. if (maps.length === 1) {
  10268. const mapR = maps[0];
  10269. const buffer = new Array(256);
  10270. for (let i = 0; i < 256; i++) {
  10271. buffer[i] = mapR[i] / 255;
  10272. }
  10273. const table = buffer.join(",");
  10274. return [table, table, table];
  10275. }
  10276. const [mapR, mapG, mapB] = maps;
  10277. const bufferR = new Array(256);
  10278. const bufferG = new Array(256);
  10279. const bufferB = new Array(256);
  10280. for (let i = 0; i < 256; i++) {
  10281. bufferR[i] = mapR[i] / 255;
  10282. bufferG[i] = mapG[i] / 255;
  10283. bufferB[i] = mapB[i] / 255;
  10284. }
  10285. return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
  10286. }
  10287. #createUrl(id) {
  10288. if (this.#baseUrl === undefined) {
  10289. this.#baseUrl = "";
  10290. const url = this.#document.URL;
  10291. if (url !== this.#document.baseURI) {
  10292. if (isDataScheme(url)) {
  10293. warn('#createUrl: ignore "data:"-URL for performance reasons.');
  10294. } else {
  10295. this.#baseUrl = updateUrlHash(url, "");
  10296. }
  10297. }
  10298. }
  10299. return `url(${this.#baseUrl}#${id})`;
  10300. }
  10301. addFilter(maps) {
  10302. if (!maps) {
  10303. return "none";
  10304. }
  10305. let value = this.#cache.get(maps);
  10306. if (value) {
  10307. return value;
  10308. }
  10309. const [tableR, tableG, tableB] = this.#createTables(maps);
  10310. const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
  10311. value = this.#cache.get(key);
  10312. if (value) {
  10313. this.#cache.set(maps, value);
  10314. return value;
  10315. }
  10316. const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
  10317. const url = this.#createUrl(id);
  10318. this.#cache.set(maps, url);
  10319. this.#cache.set(key, url);
  10320. const filter = this.#createFilter(id);
  10321. this.#addTransferMapConversion(tableR, tableG, tableB, filter);
  10322. return url;
  10323. }
  10324. addHCMFilter(fgColor, bgColor) {
  10325. const key = `${fgColor}-${bgColor}`;
  10326. const filterName = "base";
  10327. let info = this.#hcmCache.get(filterName);
  10328. if (info?.key === key) {
  10329. return info.url;
  10330. }
  10331. if (info) {
  10332. info.filter?.remove();
  10333. info.key = key;
  10334. info.url = "none";
  10335. info.filter = null;
  10336. } else {
  10337. info = {
  10338. key,
  10339. url: "none",
  10340. filter: null
  10341. };
  10342. this.#hcmCache.set(filterName, info);
  10343. }
  10344. if (!fgColor || !bgColor) {
  10345. return info.url;
  10346. }
  10347. const fgRGB = this.#getRGB(fgColor);
  10348. fgColor = Util.makeHexColor(...fgRGB);
  10349. const bgRGB = this.#getRGB(bgColor);
  10350. bgColor = Util.makeHexColor(...bgRGB);
  10351. this.#defs.style.color = "";
  10352. if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
  10353. return info.url;
  10354. }
  10355. const map = new Array(256);
  10356. for (let i = 0; i <= 255; i++) {
  10357. const x = i / 255;
  10358. map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  10359. }
  10360. const table = map.join(",");
  10361. const id = `g_${this.#docId}_hcm_filter`;
  10362. const filter = info.filter = this.#createFilter(id);
  10363. this.#addTransferMapConversion(table, table, table, filter);
  10364. this.#addGrayConversion(filter);
  10365. const getSteps = (c, n) => {
  10366. const start = fgRGB[c] / 255;
  10367. const end = bgRGB[c] / 255;
  10368. const arr = new Array(n + 1);
  10369. for (let i = 0; i <= n; i++) {
  10370. arr[i] = start + i / n * (end - start);
  10371. }
  10372. return arr.join(",");
  10373. };
  10374. this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
  10375. info.url = this.#createUrl(id);
  10376. return info.url;
  10377. }
  10378. addAlphaFilter(map) {
  10379. let value = this.#cache.get(map);
  10380. if (value) {
  10381. return value;
  10382. }
  10383. const [tableA] = this.#createTables([map]);
  10384. const key = `alpha_${tableA}`;
  10385. value = this.#cache.get(key);
  10386. if (value) {
  10387. this.#cache.set(map, value);
  10388. return value;
  10389. }
  10390. const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
  10391. const url = this.#createUrl(id);
  10392. this.#cache.set(map, url);
  10393. this.#cache.set(key, url);
  10394. const filter = this.#createFilter(id);
  10395. this.#addTransferMapAlphaConversion(tableA, filter);
  10396. return url;
  10397. }
  10398. addLuminosityFilter(map) {
  10399. let value = this.#cache.get(map || "luminosity");
  10400. if (value) {
  10401. return value;
  10402. }
  10403. let tableA, key;
  10404. if (map) {
  10405. [tableA] = this.#createTables([map]);
  10406. key = `luminosity_${tableA}`;
  10407. } else {
  10408. key = "luminosity";
  10409. }
  10410. value = this.#cache.get(key);
  10411. if (value) {
  10412. this.#cache.set(map, value);
  10413. return value;
  10414. }
  10415. const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
  10416. const url = this.#createUrl(id);
  10417. this.#cache.set(map, url);
  10418. this.#cache.set(key, url);
  10419. const filter = this.#createFilter(id);
  10420. this.#addLuminosityConversion(filter);
  10421. if (map) {
  10422. this.#addTransferMapAlphaConversion(tableA, filter);
  10423. }
  10424. return url;
  10425. }
  10426. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  10427. const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
  10428. let info = this.#hcmCache.get(filterName);
  10429. if (info?.key === key) {
  10430. return info.url;
  10431. }
  10432. if (info) {
  10433. info.filter?.remove();
  10434. info.key = key;
  10435. info.url = "none";
  10436. info.filter = null;
  10437. } else {
  10438. info = {
  10439. key,
  10440. url: "none",
  10441. filter: null
  10442. };
  10443. this.#hcmCache.set(filterName, info);
  10444. }
  10445. if (!fgColor || !bgColor) {
  10446. return info.url;
  10447. }
  10448. const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
  10449. let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
  10450. let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
  10451. let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
  10452. if (bgGray < fgGray) {
  10453. [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
  10454. }
  10455. this.#defs.style.color = "";
  10456. const getSteps = (fg, bg, n) => {
  10457. const arr = new Array(256);
  10458. const step = (bgGray - fgGray) / n;
  10459. const newStart = fg / 255;
  10460. const newStep = (bg - fg) / (255 * n);
  10461. let prev = 0;
  10462. for (let i = 0; i <= n; i++) {
  10463. const k = Math.round(fgGray + i * step);
  10464. const value = newStart + i * newStep;
  10465. for (let j = prev; j <= k; j++) {
  10466. arr[j] = value;
  10467. }
  10468. prev = k + 1;
  10469. }
  10470. for (let i = prev; i < 256; i++) {
  10471. arr[i] = arr[prev - 1];
  10472. }
  10473. return arr.join(",");
  10474. };
  10475. const id = `g_${this.#docId}_hcm_${filterName}_filter`;
  10476. const filter = info.filter = this.#createFilter(id);
  10477. this.#addGrayConversion(filter);
  10478. this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
  10479. info.url = this.#createUrl(id);
  10480. return info.url;
  10481. }
  10482. destroy(keepHCM = false) {
  10483. if (keepHCM && this.#_hcmCache?.size) {
  10484. return;
  10485. }
  10486. this.#_defs?.parentNode.parentNode.remove();
  10487. this.#_defs = null;
  10488. this.#_cache?.clear();
  10489. this.#_cache = null;
  10490. this.#_hcmCache?.clear();
  10491. this.#_hcmCache = null;
  10492. this.#id = 0;
  10493. }
  10494. #addLuminosityConversion(filter) {
  10495. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  10496. feColorMatrix.setAttribute("type", "matrix");
  10497. feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");
  10498. filter.append(feColorMatrix);
  10499. }
  10500. #addGrayConversion(filter) {
  10501. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  10502. feColorMatrix.setAttribute("type", "matrix");
  10503. feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");
  10504. filter.append(feColorMatrix);
  10505. }
  10506. #createFilter(id) {
  10507. const filter = this.#document.createElementNS(SVG_NS, "filter");
  10508. filter.setAttribute("color-interpolation-filters", "sRGB");
  10509. filter.setAttribute("id", id);
  10510. this.#defs.append(filter);
  10511. return filter;
  10512. }
  10513. #appendFeFunc(feComponentTransfer, func, table) {
  10514. const feFunc = this.#document.createElementNS(SVG_NS, func);
  10515. feFunc.setAttribute("type", "discrete");
  10516. feFunc.setAttribute("tableValues", table);
  10517. feComponentTransfer.append(feFunc);
  10518. }
  10519. #addTransferMapConversion(rTable, gTable, bTable, filter) {
  10520. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  10521. filter.append(feComponentTransfer);
  10522. this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
  10523. this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
  10524. this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
  10525. }
  10526. #addTransferMapAlphaConversion(aTable, filter) {
  10527. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  10528. filter.append(feComponentTransfer);
  10529. this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
  10530. }
  10531. #getRGB(color) {
  10532. this.#defs.style.color = color;
  10533. return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
  10534. }
  10535. }
  10536. ;// ./src/display/standard_fontdata_factory.js
  10537. class BaseStandardFontDataFactory {
  10538. constructor({
  10539. baseUrl = null
  10540. }) {
  10541. this.baseUrl = baseUrl;
  10542. }
  10543. async fetch({
  10544. filename
  10545. }) {
  10546. if (!this.baseUrl) {
  10547. throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");
  10548. }
  10549. if (!filename) {
  10550. throw new Error("Font filename must be specified.");
  10551. }
  10552. const url = `${this.baseUrl}${filename}`;
  10553. return this._fetch(url).catch(reason => {
  10554. throw new Error(`Unable to load font data at: ${url}`);
  10555. });
  10556. }
  10557. async _fetch(url) {
  10558. unreachable("Abstract method `_fetch` called.");
  10559. }
  10560. }
  10561. class DOMStandardFontDataFactory extends BaseStandardFontDataFactory {
  10562. async _fetch(url) {
  10563. const data = await fetchData(url, "arraybuffer");
  10564. return new Uint8Array(data);
  10565. }
  10566. }
  10567. ;// ./src/display/wasm_factory.js
  10568. class BaseWasmFactory {
  10569. constructor({
  10570. baseUrl = null
  10571. }) {
  10572. this.baseUrl = baseUrl;
  10573. }
  10574. async fetch({
  10575. filename
  10576. }) {
  10577. if (!this.baseUrl) {
  10578. throw new Error("Ensure that the `wasmUrl` API parameter is provided.");
  10579. }
  10580. if (!filename) {
  10581. throw new Error("Wasm filename must be specified.");
  10582. }
  10583. const url = `${this.baseUrl}${filename}`;
  10584. return this._fetch(url).catch(reason => {
  10585. throw new Error(`Unable to load wasm data at: ${url}`);
  10586. });
  10587. }
  10588. async _fetch(url) {
  10589. unreachable("Abstract method `_fetch` called.");
  10590. }
  10591. }
  10592. class DOMWasmFactory extends BaseWasmFactory {
  10593. async _fetch(url) {
  10594. const data = await fetchData(url, "arraybuffer");
  10595. return new Uint8Array(data);
  10596. }
  10597. }
  10598. ;// ./src/display/node_utils.js
  10599. if (isNodeJS) {
  10600. let canvas;
  10601. try {
  10602. const require = process.getBuiltinModule("module").createRequire(import.meta.url);
  10603. try {
  10604. canvas = require("@napi-rs/canvas");
  10605. } catch (ex) {
  10606. warn(`Cannot load "@napi-rs/canvas" package: "${ex}".`);
  10607. }
  10608. } catch (ex) {
  10609. warn(`Cannot access the \`require\` function: "${ex}".`);
  10610. }
  10611. if (!globalThis.DOMMatrix) {
  10612. if (canvas?.DOMMatrix) {
  10613. globalThis.DOMMatrix = canvas.DOMMatrix;
  10614. } else {
  10615. warn("Cannot polyfill `DOMMatrix`, rendering may be broken.");
  10616. }
  10617. }
  10618. if (!globalThis.ImageData) {
  10619. if (canvas?.ImageData) {
  10620. globalThis.ImageData = canvas.ImageData;
  10621. } else {
  10622. warn("Cannot polyfill `ImageData`, rendering may be broken.");
  10623. }
  10624. }
  10625. if (!globalThis.Path2D) {
  10626. if (canvas?.Path2D) {
  10627. globalThis.Path2D = canvas.Path2D;
  10628. } else {
  10629. warn("Cannot polyfill `Path2D`, rendering may be broken.");
  10630. }
  10631. }
  10632. if (!globalThis.navigator?.language) {
  10633. globalThis.navigator = {
  10634. language: "en-US",
  10635. platform: "",
  10636. userAgent: ""
  10637. };
  10638. }
  10639. }
  10640. async function node_utils_fetchData(url) {
  10641. const fs = process.getBuiltinModule("fs");
  10642. const data = await fs.promises.readFile(url);
  10643. return new Uint8Array(data);
  10644. }
  10645. class NodeFilterFactory extends BaseFilterFactory {}
  10646. class NodeCanvasFactory extends BaseCanvasFactory {
  10647. _createCanvas(width, height) {
  10648. const require = process.getBuiltinModule("module").createRequire(import.meta.url);
  10649. const canvas = require("@napi-rs/canvas");
  10650. return canvas.createCanvas(width, height);
  10651. }
  10652. }
  10653. class NodeCMapReaderFactory extends BaseCMapReaderFactory {
  10654. async _fetch(url) {
  10655. return node_utils_fetchData(url);
  10656. }
  10657. }
  10658. class NodeStandardFontDataFactory extends BaseStandardFontDataFactory {
  10659. async _fetch(url) {
  10660. return node_utils_fetchData(url);
  10661. }
  10662. }
  10663. class NodeWasmFactory extends BaseWasmFactory {
  10664. async _fetch(url) {
  10665. return node_utils_fetchData(url);
  10666. }
  10667. }
  10668. ;// ./src/display/pattern_helper.js
  10669. const PathType = {
  10670. FILL: "Fill",
  10671. STROKE: "Stroke",
  10672. SHADING: "Shading"
  10673. };
  10674. function applyBoundingBox(ctx, bbox) {
  10675. if (!bbox) {
  10676. return;
  10677. }
  10678. const width = bbox[2] - bbox[0];
  10679. const height = bbox[3] - bbox[1];
  10680. const region = new Path2D();
  10681. region.rect(bbox[0], bbox[1], width, height);
  10682. ctx.clip(region);
  10683. }
  10684. class BaseShadingPattern {
  10685. isModifyingCurrentTransform() {
  10686. return false;
  10687. }
  10688. getPattern() {
  10689. unreachable("Abstract method `getPattern` called.");
  10690. }
  10691. }
  10692. class RadialAxialShadingPattern extends BaseShadingPattern {
  10693. constructor(IR) {
  10694. super();
  10695. this._type = IR[1];
  10696. this._bbox = IR[2];
  10697. this._colorStops = IR[3];
  10698. this._p0 = IR[4];
  10699. this._p1 = IR[5];
  10700. this._r0 = IR[6];
  10701. this._r1 = IR[7];
  10702. this.matrix = null;
  10703. }
  10704. _createGradient(ctx) {
  10705. let grad;
  10706. if (this._type === "axial") {
  10707. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  10708. } else if (this._type === "radial") {
  10709. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  10710. }
  10711. for (const colorStop of this._colorStops) {
  10712. grad.addColorStop(colorStop[0], colorStop[1]);
  10713. }
  10714. return grad;
  10715. }
  10716. getPattern(ctx, owner, inverse, pathType) {
  10717. let pattern;
  10718. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  10719. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
  10720. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  10721. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  10722. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);
  10723. const tmpCtx = tmpCanvas.context;
  10724. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  10725. tmpCtx.beginPath();
  10726. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  10727. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  10728. inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  10729. tmpCtx.transform(...owner.baseTransform);
  10730. if (this.matrix) {
  10731. tmpCtx.transform(...this.matrix);
  10732. }
  10733. applyBoundingBox(tmpCtx, this._bbox);
  10734. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  10735. tmpCtx.fill();
  10736. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  10737. const domMatrix = new DOMMatrix(inverse);
  10738. pattern.setTransform(domMatrix);
  10739. } else {
  10740. applyBoundingBox(ctx, this._bbox);
  10741. pattern = this._createGradient(ctx);
  10742. }
  10743. return pattern;
  10744. }
  10745. }
  10746. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  10747. const coords = context.coords,
  10748. colors = context.colors;
  10749. const bytes = data.data,
  10750. rowSize = data.width * 4;
  10751. let tmp;
  10752. if (coords[p1 + 1] > coords[p2 + 1]) {
  10753. tmp = p1;
  10754. p1 = p2;
  10755. p2 = tmp;
  10756. tmp = c1;
  10757. c1 = c2;
  10758. c2 = tmp;
  10759. }
  10760. if (coords[p2 + 1] > coords[p3 + 1]) {
  10761. tmp = p2;
  10762. p2 = p3;
  10763. p3 = tmp;
  10764. tmp = c2;
  10765. c2 = c3;
  10766. c3 = tmp;
  10767. }
  10768. if (coords[p1 + 1] > coords[p2 + 1]) {
  10769. tmp = p1;
  10770. p1 = p2;
  10771. p2 = tmp;
  10772. tmp = c1;
  10773. c1 = c2;
  10774. c2 = tmp;
  10775. }
  10776. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  10777. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  10778. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  10779. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  10780. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  10781. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  10782. if (y1 >= y3) {
  10783. return;
  10784. }
  10785. const c1r = colors[c1],
  10786. c1g = colors[c1 + 1],
  10787. c1b = colors[c1 + 2];
  10788. const c2r = colors[c2],
  10789. c2g = colors[c2 + 1],
  10790. c2b = colors[c2 + 2];
  10791. const c3r = colors[c3],
  10792. c3g = colors[c3 + 1],
  10793. c3b = colors[c3 + 2];
  10794. const minY = Math.round(y1),
  10795. maxY = Math.round(y3);
  10796. let xa, car, cag, cab;
  10797. let xb, cbr, cbg, cbb;
  10798. for (let y = minY; y <= maxY; y++) {
  10799. if (y < y2) {
  10800. const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);
  10801. xa = x1 - (x1 - x2) * k;
  10802. car = c1r - (c1r - c2r) * k;
  10803. cag = c1g - (c1g - c2g) * k;
  10804. cab = c1b - (c1b - c2b) * k;
  10805. } else {
  10806. let k;
  10807. if (y > y3) {
  10808. k = 1;
  10809. } else if (y2 === y3) {
  10810. k = 0;
  10811. } else {
  10812. k = (y2 - y) / (y2 - y3);
  10813. }
  10814. xa = x2 - (x2 - x3) * k;
  10815. car = c2r - (c2r - c3r) * k;
  10816. cag = c2g - (c2g - c3g) * k;
  10817. cab = c2b - (c2b - c3b) * k;
  10818. }
  10819. let k;
  10820. if (y < y1) {
  10821. k = 0;
  10822. } else if (y > y3) {
  10823. k = 1;
  10824. } else {
  10825. k = (y1 - y) / (y1 - y3);
  10826. }
  10827. xb = x1 - (x1 - x3) * k;
  10828. cbr = c1r - (c1r - c3r) * k;
  10829. cbg = c1g - (c1g - c3g) * k;
  10830. cbb = c1b - (c1b - c3b) * k;
  10831. const x1_ = Math.round(Math.min(xa, xb));
  10832. const x2_ = Math.round(Math.max(xa, xb));
  10833. let j = rowSize * y + x1_ * 4;
  10834. for (let x = x1_; x <= x2_; x++) {
  10835. k = (xa - x) / (xa - xb);
  10836. if (k < 0) {
  10837. k = 0;
  10838. } else if (k > 1) {
  10839. k = 1;
  10840. }
  10841. bytes[j++] = car - (car - cbr) * k | 0;
  10842. bytes[j++] = cag - (cag - cbg) * k | 0;
  10843. bytes[j++] = cab - (cab - cbb) * k | 0;
  10844. bytes[j++] = 255;
  10845. }
  10846. }
  10847. }
  10848. function drawFigure(data, figure, context) {
  10849. const ps = figure.coords;
  10850. const cs = figure.colors;
  10851. let i, ii;
  10852. switch (figure.type) {
  10853. case "lattice":
  10854. const verticesPerRow = figure.verticesPerRow;
  10855. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  10856. const cols = verticesPerRow - 1;
  10857. for (i = 0; i < rows; i++) {
  10858. let q = i * verticesPerRow;
  10859. for (let j = 0; j < cols; j++, q++) {
  10860. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  10861. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  10862. }
  10863. }
  10864. break;
  10865. case "triangles":
  10866. for (i = 0, ii = ps.length; i < ii; i += 3) {
  10867. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  10868. }
  10869. break;
  10870. default:
  10871. throw new Error("illegal figure");
  10872. }
  10873. }
  10874. class MeshShadingPattern extends BaseShadingPattern {
  10875. constructor(IR) {
  10876. super();
  10877. this._coords = IR[2];
  10878. this._colors = IR[3];
  10879. this._figures = IR[4];
  10880. this._bounds = IR[5];
  10881. this._bbox = IR[6];
  10882. this._background = IR[7];
  10883. this.matrix = null;
  10884. }
  10885. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  10886. const EXPECTED_SCALE = 1.1;
  10887. const MAX_PATTERN_SIZE = 3000;
  10888. const BORDER_SIZE = 2;
  10889. const offsetX = Math.floor(this._bounds[0]);
  10890. const offsetY = Math.floor(this._bounds[1]);
  10891. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  10892. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  10893. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  10894. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  10895. const scaleX = boundsWidth / width;
  10896. const scaleY = boundsHeight / height;
  10897. const context = {
  10898. coords: this._coords,
  10899. colors: this._colors,
  10900. offsetX: -offsetX,
  10901. offsetY: -offsetY,
  10902. scaleX: 1 / scaleX,
  10903. scaleY: 1 / scaleY
  10904. };
  10905. const paddedWidth = width + BORDER_SIZE * 2;
  10906. const paddedHeight = height + BORDER_SIZE * 2;
  10907. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);
  10908. const tmpCtx = tmpCanvas.context;
  10909. const data = tmpCtx.createImageData(width, height);
  10910. if (backgroundColor) {
  10911. const bytes = data.data;
  10912. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  10913. bytes[i] = backgroundColor[0];
  10914. bytes[i + 1] = backgroundColor[1];
  10915. bytes[i + 2] = backgroundColor[2];
  10916. bytes[i + 3] = 255;
  10917. }
  10918. }
  10919. for (const figure of this._figures) {
  10920. drawFigure(data, figure, context);
  10921. }
  10922. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  10923. const canvas = tmpCanvas.canvas;
  10924. return {
  10925. canvas,
  10926. offsetX: offsetX - BORDER_SIZE * scaleX,
  10927. offsetY: offsetY - BORDER_SIZE * scaleY,
  10928. scaleX,
  10929. scaleY
  10930. };
  10931. }
  10932. isModifyingCurrentTransform() {
  10933. return true;
  10934. }
  10935. getPattern(ctx, owner, inverse, pathType) {
  10936. applyBoundingBox(ctx, this._bbox);
  10937. const scale = new Float32Array(2);
  10938. if (pathType === PathType.SHADING) {
  10939. Util.singularValueDecompose2dScale(getCurrentTransform(ctx), scale);
  10940. } else if (this.matrix) {
  10941. Util.singularValueDecompose2dScale(this.matrix, scale);
  10942. const [matrixScaleX, matrixScaleY] = scale;
  10943. Util.singularValueDecompose2dScale(owner.baseTransform, scale);
  10944. scale[0] *= matrixScaleX;
  10945. scale[1] *= matrixScaleY;
  10946. } else {
  10947. Util.singularValueDecompose2dScale(owner.baseTransform, scale);
  10948. }
  10949. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  10950. if (pathType !== PathType.SHADING) {
  10951. ctx.setTransform(...owner.baseTransform);
  10952. if (this.matrix) {
  10953. ctx.transform(...this.matrix);
  10954. }
  10955. }
  10956. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  10957. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  10958. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  10959. }
  10960. }
  10961. class DummyShadingPattern extends BaseShadingPattern {
  10962. getPattern() {
  10963. return "hotpink";
  10964. }
  10965. }
  10966. function getShadingPattern(IR) {
  10967. switch (IR[0]) {
  10968. case "RadialAxial":
  10969. return new RadialAxialShadingPattern(IR);
  10970. case "Mesh":
  10971. return new MeshShadingPattern(IR);
  10972. case "Dummy":
  10973. return new DummyShadingPattern();
  10974. }
  10975. throw new Error(`Unknown IR type: ${IR[0]}`);
  10976. }
  10977. const PaintType = {
  10978. COLORED: 1,
  10979. UNCOLORED: 2
  10980. };
  10981. class TilingPattern {
  10982. static MAX_PATTERN_SIZE = 3000;
  10983. constructor(IR, ctx, canvasGraphicsFactory, baseTransform) {
  10984. this.color = IR[1];
  10985. this.operatorList = IR[2];
  10986. this.matrix = IR[3];
  10987. this.bbox = IR[4];
  10988. this.xstep = IR[5];
  10989. this.ystep = IR[6];
  10990. this.paintType = IR[7];
  10991. this.tilingType = IR[8];
  10992. this.ctx = ctx;
  10993. this.canvasGraphicsFactory = canvasGraphicsFactory;
  10994. this.baseTransform = baseTransform;
  10995. }
  10996. createPatternCanvas(owner) {
  10997. const {
  10998. bbox,
  10999. operatorList,
  11000. paintType,
  11001. tilingType,
  11002. color,
  11003. canvasGraphicsFactory
  11004. } = this;
  11005. let {
  11006. xstep,
  11007. ystep
  11008. } = this;
  11009. xstep = Math.abs(xstep);
  11010. ystep = Math.abs(ystep);
  11011. info("TilingType: " + tilingType);
  11012. const x0 = bbox[0],
  11013. y0 = bbox[1],
  11014. x1 = bbox[2],
  11015. y1 = bbox[3];
  11016. const width = x1 - x0;
  11017. const height = y1 - y0;
  11018. const scale = new Float32Array(2);
  11019. Util.singularValueDecompose2dScale(this.matrix, scale);
  11020. const [matrixScaleX, matrixScaleY] = scale;
  11021. Util.singularValueDecompose2dScale(this.baseTransform, scale);
  11022. const combinedScaleX = matrixScaleX * scale[0];
  11023. const combinedScaleY = matrixScaleY * scale[1];
  11024. let canvasWidth = width,
  11025. canvasHeight = height,
  11026. redrawHorizontally = false,
  11027. redrawVertically = false;
  11028. const xScaledStep = Math.ceil(xstep * combinedScaleX);
  11029. const yScaledStep = Math.ceil(ystep * combinedScaleY);
  11030. const xScaledWidth = Math.ceil(width * combinedScaleX);
  11031. const yScaledHeight = Math.ceil(height * combinedScaleY);
  11032. if (xScaledStep >= xScaledWidth) {
  11033. canvasWidth = xstep;
  11034. } else {
  11035. redrawHorizontally = true;
  11036. }
  11037. if (yScaledStep >= yScaledHeight) {
  11038. canvasHeight = ystep;
  11039. } else {
  11040. redrawVertically = true;
  11041. }
  11042. const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  11043. const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  11044. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);
  11045. const tmpCtx = tmpCanvas.context;
  11046. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  11047. graphics.groupLevel = owner.groupLevel;
  11048. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  11049. tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);
  11050. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  11051. tmpCtx.save();
  11052. this.clipBbox(graphics, x0, y0, x1, y1);
  11053. graphics.baseTransform = getCurrentTransform(graphics.ctx);
  11054. graphics.executeOperatorList(operatorList);
  11055. graphics.endDrawing();
  11056. tmpCtx.restore();
  11057. if (redrawHorizontally || redrawVertically) {
  11058. const image = tmpCanvas.canvas;
  11059. if (redrawHorizontally) {
  11060. canvasWidth = xstep;
  11061. }
  11062. if (redrawVertically) {
  11063. canvasHeight = ystep;
  11064. }
  11065. const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  11066. const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  11067. const xSize = dimx2.size;
  11068. const ySize = dimy2.size;
  11069. const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);
  11070. const tmpCtx2 = tmpCanvas2.context;
  11071. const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;
  11072. const jj = redrawVertically ? Math.floor(height / ystep) : 0;
  11073. for (let i = 0; i <= ii; i++) {
  11074. for (let j = 0; j <= jj; j++) {
  11075. tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize);
  11076. }
  11077. }
  11078. return {
  11079. canvas: tmpCanvas2.canvas,
  11080. scaleX: dimx2.scale,
  11081. scaleY: dimy2.scale,
  11082. offsetX: x0,
  11083. offsetY: y0
  11084. };
  11085. }
  11086. return {
  11087. canvas: tmpCanvas.canvas,
  11088. scaleX: dimx.scale,
  11089. scaleY: dimy.scale,
  11090. offsetX: x0,
  11091. offsetY: y0
  11092. };
  11093. }
  11094. getSizeAndScale(step, realOutputSize, scale) {
  11095. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  11096. let size = Math.ceil(step * scale);
  11097. if (size >= maxSize) {
  11098. size = maxSize;
  11099. } else {
  11100. scale = size / step;
  11101. }
  11102. return {
  11103. scale,
  11104. size
  11105. };
  11106. }
  11107. clipBbox(graphics, x0, y0, x1, y1) {
  11108. const bboxWidth = x1 - x0;
  11109. const bboxHeight = y1 - y0;
  11110. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  11111. Util.axialAlignedBoundingBox([x0, y0, x1, y1], getCurrentTransform(graphics.ctx), graphics.current.minMax);
  11112. graphics.clip();
  11113. graphics.endPath();
  11114. }
  11115. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  11116. const context = graphics.ctx,
  11117. current = graphics.current;
  11118. switch (paintType) {
  11119. case PaintType.COLORED:
  11120. const {
  11121. fillStyle,
  11122. strokeStyle
  11123. } = this.ctx;
  11124. context.fillStyle = current.fillColor = fillStyle;
  11125. context.strokeStyle = current.strokeColor = strokeStyle;
  11126. break;
  11127. case PaintType.UNCOLORED:
  11128. context.fillStyle = context.strokeStyle = color;
  11129. current.fillColor = current.strokeColor = color;
  11130. break;
  11131. default:
  11132. throw new FormatError(`Unsupported paint type: ${paintType}`);
  11133. }
  11134. }
  11135. isModifyingCurrentTransform() {
  11136. return false;
  11137. }
  11138. getPattern(ctx, owner, inverse, pathType) {
  11139. let matrix = inverse;
  11140. if (pathType !== PathType.SHADING) {
  11141. matrix = Util.transform(matrix, owner.baseTransform);
  11142. if (this.matrix) {
  11143. matrix = Util.transform(matrix, this.matrix);
  11144. }
  11145. }
  11146. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  11147. let domMatrix = new DOMMatrix(matrix);
  11148. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  11149. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  11150. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  11151. pattern.setTransform(domMatrix);
  11152. return pattern;
  11153. }
  11154. }
  11155. ;// ./src/shared/image_utils.js
  11156. function convertToRGBA(params) {
  11157. switch (params.kind) {
  11158. case ImageKind.GRAYSCALE_1BPP:
  11159. return convertBlackAndWhiteToRGBA(params);
  11160. case ImageKind.RGB_24BPP:
  11161. return convertRGBToRGBA(params);
  11162. }
  11163. return null;
  11164. }
  11165. function convertBlackAndWhiteToRGBA({
  11166. src,
  11167. srcPos = 0,
  11168. dest,
  11169. width,
  11170. height,
  11171. nonBlackColor = 0xffffffff,
  11172. inverseDecode = false
  11173. }) {
  11174. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  11175. const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
  11176. const widthInSource = width >> 3;
  11177. const widthRemainder = width & 7;
  11178. const srcLength = src.length;
  11179. dest = new Uint32Array(dest.buffer);
  11180. let destPos = 0;
  11181. for (let i = 0; i < height; i++) {
  11182. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  11183. const elem = srcPos < srcLength ? src[srcPos] : 255;
  11184. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  11185. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  11186. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  11187. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  11188. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  11189. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  11190. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  11191. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  11192. }
  11193. if (widthRemainder === 0) {
  11194. continue;
  11195. }
  11196. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  11197. for (let j = 0; j < widthRemainder; j++) {
  11198. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  11199. }
  11200. }
  11201. return {
  11202. srcPos,
  11203. destPos
  11204. };
  11205. }
  11206. function convertRGBToRGBA({
  11207. src,
  11208. srcPos = 0,
  11209. dest,
  11210. destPos = 0,
  11211. width,
  11212. height
  11213. }) {
  11214. let i = 0;
  11215. const len = width * height * 3;
  11216. const len32 = len >> 2;
  11217. const src32 = new Uint32Array(src.buffer, srcPos, len32);
  11218. if (FeatureTest.isLittleEndian) {
  11219. for (; i < len32 - 2; i += 3, destPos += 4) {
  11220. const s1 = src32[i];
  11221. const s2 = src32[i + 1];
  11222. const s3 = src32[i + 2];
  11223. dest[destPos] = s1 | 0xff000000;
  11224. dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
  11225. dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
  11226. dest[destPos + 3] = s3 >>> 8 | 0xff000000;
  11227. }
  11228. for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {
  11229. dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
  11230. }
  11231. } else {
  11232. for (; i < len32 - 2; i += 3, destPos += 4) {
  11233. const s1 = src32[i];
  11234. const s2 = src32[i + 1];
  11235. const s3 = src32[i + 2];
  11236. dest[destPos] = s1 | 0xff;
  11237. dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
  11238. dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
  11239. dest[destPos + 3] = s3 << 8 | 0xff;
  11240. }
  11241. for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {
  11242. dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
  11243. }
  11244. }
  11245. return {
  11246. srcPos: srcPos + len,
  11247. destPos
  11248. };
  11249. }
  11250. function grayToRGBA(src, dest) {
  11251. if (FeatureTest.isLittleEndian) {
  11252. for (let i = 0, ii = src.length; i < ii; i++) {
  11253. dest[i] = src[i] * 0x10101 | 0xff000000;
  11254. }
  11255. } else {
  11256. for (let i = 0, ii = src.length; i < ii; i++) {
  11257. dest[i] = src[i] * 0x1010100 | 0x000000ff;
  11258. }
  11259. }
  11260. }
  11261. ;// ./src/display/canvas.js
  11262. const MIN_FONT_SIZE = 16;
  11263. const MAX_FONT_SIZE = 100;
  11264. const EXECUTION_TIME = 15;
  11265. const EXECUTION_STEPS = 10;
  11266. const FULL_CHUNK_HEIGHT = 16;
  11267. const SCALE_MATRIX = new DOMMatrix();
  11268. const XY = new Float32Array(2);
  11269. const MIN_MAX_INIT = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
  11270. function mirrorContextOperations(ctx, destCtx) {
  11271. if (ctx._removeMirroring) {
  11272. throw new Error("Context is already forwarding operations.");
  11273. }
  11274. ctx.__originalSave = ctx.save;
  11275. ctx.__originalRestore = ctx.restore;
  11276. ctx.__originalRotate = ctx.rotate;
  11277. ctx.__originalScale = ctx.scale;
  11278. ctx.__originalTranslate = ctx.translate;
  11279. ctx.__originalTransform = ctx.transform;
  11280. ctx.__originalSetTransform = ctx.setTransform;
  11281. ctx.__originalResetTransform = ctx.resetTransform;
  11282. ctx.__originalClip = ctx.clip;
  11283. ctx.__originalMoveTo = ctx.moveTo;
  11284. ctx.__originalLineTo = ctx.lineTo;
  11285. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  11286. ctx.__originalRect = ctx.rect;
  11287. ctx.__originalClosePath = ctx.closePath;
  11288. ctx.__originalBeginPath = ctx.beginPath;
  11289. ctx._removeMirroring = () => {
  11290. ctx.save = ctx.__originalSave;
  11291. ctx.restore = ctx.__originalRestore;
  11292. ctx.rotate = ctx.__originalRotate;
  11293. ctx.scale = ctx.__originalScale;
  11294. ctx.translate = ctx.__originalTranslate;
  11295. ctx.transform = ctx.__originalTransform;
  11296. ctx.setTransform = ctx.__originalSetTransform;
  11297. ctx.resetTransform = ctx.__originalResetTransform;
  11298. ctx.clip = ctx.__originalClip;
  11299. ctx.moveTo = ctx.__originalMoveTo;
  11300. ctx.lineTo = ctx.__originalLineTo;
  11301. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  11302. ctx.rect = ctx.__originalRect;
  11303. ctx.closePath = ctx.__originalClosePath;
  11304. ctx.beginPath = ctx.__originalBeginPath;
  11305. delete ctx._removeMirroring;
  11306. };
  11307. ctx.save = function () {
  11308. destCtx.save();
  11309. this.__originalSave();
  11310. };
  11311. ctx.restore = function () {
  11312. destCtx.restore();
  11313. this.__originalRestore();
  11314. };
  11315. ctx.translate = function (x, y) {
  11316. destCtx.translate(x, y);
  11317. this.__originalTranslate(x, y);
  11318. };
  11319. ctx.scale = function (x, y) {
  11320. destCtx.scale(x, y);
  11321. this.__originalScale(x, y);
  11322. };
  11323. ctx.transform = function (a, b, c, d, e, f) {
  11324. destCtx.transform(a, b, c, d, e, f);
  11325. this.__originalTransform(a, b, c, d, e, f);
  11326. };
  11327. ctx.setTransform = function (a, b, c, d, e, f) {
  11328. destCtx.setTransform(a, b, c, d, e, f);
  11329. this.__originalSetTransform(a, b, c, d, e, f);
  11330. };
  11331. ctx.resetTransform = function () {
  11332. destCtx.resetTransform();
  11333. this.__originalResetTransform();
  11334. };
  11335. ctx.rotate = function (angle) {
  11336. destCtx.rotate(angle);
  11337. this.__originalRotate(angle);
  11338. };
  11339. ctx.clip = function (rule) {
  11340. destCtx.clip(rule);
  11341. this.__originalClip(rule);
  11342. };
  11343. ctx.moveTo = function (x, y) {
  11344. destCtx.moveTo(x, y);
  11345. this.__originalMoveTo(x, y);
  11346. };
  11347. ctx.lineTo = function (x, y) {
  11348. destCtx.lineTo(x, y);
  11349. this.__originalLineTo(x, y);
  11350. };
  11351. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  11352. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  11353. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  11354. };
  11355. ctx.rect = function (x, y, width, height) {
  11356. destCtx.rect(x, y, width, height);
  11357. this.__originalRect(x, y, width, height);
  11358. };
  11359. ctx.closePath = function () {
  11360. destCtx.closePath();
  11361. this.__originalClosePath();
  11362. };
  11363. ctx.beginPath = function () {
  11364. destCtx.beginPath();
  11365. this.__originalBeginPath();
  11366. };
  11367. }
  11368. class CachedCanvases {
  11369. constructor(canvasFactory) {
  11370. this.canvasFactory = canvasFactory;
  11371. this.cache = Object.create(null);
  11372. }
  11373. getCanvas(id, width, height) {
  11374. let canvasEntry;
  11375. if (this.cache[id] !== undefined) {
  11376. canvasEntry = this.cache[id];
  11377. this.canvasFactory.reset(canvasEntry, width, height);
  11378. } else {
  11379. canvasEntry = this.canvasFactory.create(width, height);
  11380. this.cache[id] = canvasEntry;
  11381. }
  11382. return canvasEntry;
  11383. }
  11384. delete(id) {
  11385. delete this.cache[id];
  11386. }
  11387. clear() {
  11388. for (const id in this.cache) {
  11389. const canvasEntry = this.cache[id];
  11390. this.canvasFactory.destroy(canvasEntry);
  11391. delete this.cache[id];
  11392. }
  11393. }
  11394. }
  11395. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  11396. const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);
  11397. if (b === 0 && c === 0) {
  11398. const tlX = destX * a + tx;
  11399. const rTlX = Math.round(tlX);
  11400. const tlY = destY * d + ty;
  11401. const rTlY = Math.round(tlY);
  11402. const brX = (destX + destW) * a + tx;
  11403. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  11404. const brY = (destY + destH) * d + ty;
  11405. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  11406. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  11407. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  11408. ctx.setTransform(a, b, c, d, tx, ty);
  11409. return [rWidth, rHeight];
  11410. }
  11411. if (a === 0 && d === 0) {
  11412. const tlX = destY * c + tx;
  11413. const rTlX = Math.round(tlX);
  11414. const tlY = destX * b + ty;
  11415. const rTlY = Math.round(tlY);
  11416. const brX = (destY + destH) * c + tx;
  11417. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  11418. const brY = (destX + destW) * b + ty;
  11419. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  11420. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  11421. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  11422. ctx.setTransform(a, b, c, d, tx, ty);
  11423. return [rHeight, rWidth];
  11424. }
  11425. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  11426. const scaleX = Math.hypot(a, b);
  11427. const scaleY = Math.hypot(c, d);
  11428. return [scaleX * destW, scaleY * destH];
  11429. }
  11430. class CanvasExtraState {
  11431. alphaIsShape = false;
  11432. fontSize = 0;
  11433. fontSizeScale = 1;
  11434. textMatrix = null;
  11435. textMatrixScale = 1;
  11436. fontMatrix = FONT_IDENTITY_MATRIX;
  11437. leading = 0;
  11438. x = 0;
  11439. y = 0;
  11440. lineX = 0;
  11441. lineY = 0;
  11442. charSpacing = 0;
  11443. wordSpacing = 0;
  11444. textHScale = 1;
  11445. textRenderingMode = TextRenderingMode.FILL;
  11446. textRise = 0;
  11447. fillColor = "#000000";
  11448. strokeColor = "#000000";
  11449. patternFill = false;
  11450. patternStroke = false;
  11451. fillAlpha = 1;
  11452. strokeAlpha = 1;
  11453. lineWidth = 1;
  11454. activeSMask = null;
  11455. transferMaps = "none";
  11456. constructor(width, height) {
  11457. this.clipBox = new Float32Array([0, 0, width, height]);
  11458. this.minMax = MIN_MAX_INIT.slice();
  11459. }
  11460. clone() {
  11461. const clone = Object.create(this);
  11462. clone.clipBox = this.clipBox.slice();
  11463. clone.minMax = this.minMax.slice();
  11464. return clone;
  11465. }
  11466. getPathBoundingBox(pathType = PathType.FILL, transform = null) {
  11467. const box = this.minMax.slice();
  11468. if (pathType === PathType.STROKE) {
  11469. if (!transform) {
  11470. unreachable("Stroke bounding box must include transform.");
  11471. }
  11472. Util.singularValueDecompose2dScale(transform, XY);
  11473. const xStrokePad = XY[0] * this.lineWidth / 2;
  11474. const yStrokePad = XY[1] * this.lineWidth / 2;
  11475. box[0] -= xStrokePad;
  11476. box[1] -= yStrokePad;
  11477. box[2] += xStrokePad;
  11478. box[3] += yStrokePad;
  11479. }
  11480. return box;
  11481. }
  11482. updateClipFromPath() {
  11483. const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
  11484. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  11485. }
  11486. isEmptyClip() {
  11487. return this.minMax[0] === Infinity;
  11488. }
  11489. startNewPathAndClipBox(box) {
  11490. this.clipBox.set(box, 0);
  11491. this.minMax.set(MIN_MAX_INIT, 0);
  11492. }
  11493. getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
  11494. return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  11495. }
  11496. }
  11497. function putBinaryImageData(ctx, imgData) {
  11498. if (imgData instanceof ImageData) {
  11499. ctx.putImageData(imgData, 0, 0);
  11500. return;
  11501. }
  11502. const height = imgData.height,
  11503. width = imgData.width;
  11504. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  11505. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  11506. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  11507. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  11508. let srcPos = 0,
  11509. destPos;
  11510. const src = imgData.data;
  11511. const dest = chunkImgData.data;
  11512. let i, j, thisChunkHeight, elemsInThisChunk;
  11513. if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
  11514. const srcLength = src.byteLength;
  11515. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  11516. const dest32DataLength = dest32.length;
  11517. const fullSrcDiff = width + 7 >> 3;
  11518. const white = 0xffffffff;
  11519. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  11520. for (i = 0; i < totalChunks; i++) {
  11521. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  11522. destPos = 0;
  11523. for (j = 0; j < thisChunkHeight; j++) {
  11524. const srcDiff = srcLength - srcPos;
  11525. let k = 0;
  11526. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  11527. const kEndUnrolled = kEnd & ~7;
  11528. let mask = 0;
  11529. let srcByte = 0;
  11530. for (; k < kEndUnrolled; k += 8) {
  11531. srcByte = src[srcPos++];
  11532. dest32[destPos++] = srcByte & 128 ? white : black;
  11533. dest32[destPos++] = srcByte & 64 ? white : black;
  11534. dest32[destPos++] = srcByte & 32 ? white : black;
  11535. dest32[destPos++] = srcByte & 16 ? white : black;
  11536. dest32[destPos++] = srcByte & 8 ? white : black;
  11537. dest32[destPos++] = srcByte & 4 ? white : black;
  11538. dest32[destPos++] = srcByte & 2 ? white : black;
  11539. dest32[destPos++] = srcByte & 1 ? white : black;
  11540. }
  11541. for (; k < kEnd; k++) {
  11542. if (mask === 0) {
  11543. srcByte = src[srcPos++];
  11544. mask = 128;
  11545. }
  11546. dest32[destPos++] = srcByte & mask ? white : black;
  11547. mask >>= 1;
  11548. }
  11549. }
  11550. while (destPos < dest32DataLength) {
  11551. dest32[destPos++] = 0;
  11552. }
  11553. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  11554. }
  11555. } else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
  11556. j = 0;
  11557. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  11558. for (i = 0; i < fullChunks; i++) {
  11559. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  11560. srcPos += elemsInThisChunk;
  11561. ctx.putImageData(chunkImgData, 0, j);
  11562. j += FULL_CHUNK_HEIGHT;
  11563. }
  11564. if (i < totalChunks) {
  11565. elemsInThisChunk = width * partialChunkHeight * 4;
  11566. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  11567. ctx.putImageData(chunkImgData, 0, j);
  11568. }
  11569. } else if (imgData.kind === util_ImageKind.RGB_24BPP) {
  11570. thisChunkHeight = FULL_CHUNK_HEIGHT;
  11571. elemsInThisChunk = width * thisChunkHeight;
  11572. for (i = 0; i < totalChunks; i++) {
  11573. if (i >= fullChunks) {
  11574. thisChunkHeight = partialChunkHeight;
  11575. elemsInThisChunk = width * thisChunkHeight;
  11576. }
  11577. destPos = 0;
  11578. for (j = elemsInThisChunk; j--;) {
  11579. dest[destPos++] = src[srcPos++];
  11580. dest[destPos++] = src[srcPos++];
  11581. dest[destPos++] = src[srcPos++];
  11582. dest[destPos++] = 255;
  11583. }
  11584. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  11585. }
  11586. } else {
  11587. throw new Error(`bad image kind: ${imgData.kind}`);
  11588. }
  11589. }
  11590. function putBinaryImageMask(ctx, imgData) {
  11591. if (imgData.bitmap) {
  11592. ctx.drawImage(imgData.bitmap, 0, 0);
  11593. return;
  11594. }
  11595. const height = imgData.height,
  11596. width = imgData.width;
  11597. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  11598. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  11599. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  11600. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  11601. let srcPos = 0;
  11602. const src = imgData.data;
  11603. const dest = chunkImgData.data;
  11604. for (let i = 0; i < totalChunks; i++) {
  11605. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  11606. ({
  11607. srcPos
  11608. } = convertBlackAndWhiteToRGBA({
  11609. src,
  11610. srcPos,
  11611. dest,
  11612. width,
  11613. height: thisChunkHeight,
  11614. nonBlackColor: 0
  11615. }));
  11616. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  11617. }
  11618. }
  11619. function copyCtxState(sourceCtx, destCtx) {
  11620. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
  11621. for (const property of properties) {
  11622. if (sourceCtx[property] !== undefined) {
  11623. destCtx[property] = sourceCtx[property];
  11624. }
  11625. }
  11626. if (sourceCtx.setLineDash !== undefined) {
  11627. destCtx.setLineDash(sourceCtx.getLineDash());
  11628. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  11629. }
  11630. }
  11631. function resetCtxToDefault(ctx) {
  11632. ctx.strokeStyle = ctx.fillStyle = "#000000";
  11633. ctx.fillRule = "nonzero";
  11634. ctx.globalAlpha = 1;
  11635. ctx.lineWidth = 1;
  11636. ctx.lineCap = "butt";
  11637. ctx.lineJoin = "miter";
  11638. ctx.miterLimit = 10;
  11639. ctx.globalCompositeOperation = "source-over";
  11640. ctx.font = "10px sans-serif";
  11641. if (ctx.setLineDash !== undefined) {
  11642. ctx.setLineDash([]);
  11643. ctx.lineDashOffset = 0;
  11644. }
  11645. const {
  11646. filter
  11647. } = ctx;
  11648. if (filter !== "none" && filter !== "") {
  11649. ctx.filter = "none";
  11650. }
  11651. }
  11652. function getImageSmoothingEnabled(transform, interpolate) {
  11653. if (interpolate) {
  11654. return true;
  11655. }
  11656. Util.singularValueDecompose2dScale(transform, XY);
  11657. const actualScale = Math.fround(OutputScale.pixelRatio * PixelsPerInch.PDF_TO_CSS_UNITS);
  11658. return XY[0] <= actualScale && XY[1] <= actualScale;
  11659. }
  11660. const LINE_CAP_STYLES = ["butt", "round", "square"];
  11661. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  11662. const NORMAL_CLIP = {};
  11663. const EO_CLIP = {};
  11664. class CanvasGraphics {
  11665. constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
  11666. optionalContentConfig,
  11667. markedContentStack = null
  11668. }, annotationCanvasMap, pageColors) {
  11669. this.ctx = canvasCtx;
  11670. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  11671. this.stateStack = [];
  11672. this.pendingClip = null;
  11673. this.pendingEOFill = false;
  11674. this.res = null;
  11675. this.xobjs = null;
  11676. this.commonObjs = commonObjs;
  11677. this.objs = objs;
  11678. this.canvasFactory = canvasFactory;
  11679. this.filterFactory = filterFactory;
  11680. this.groupStack = [];
  11681. this.baseTransform = null;
  11682. this.baseTransformStack = [];
  11683. this.groupLevel = 0;
  11684. this.smaskStack = [];
  11685. this.smaskCounter = 0;
  11686. this.tempSMask = null;
  11687. this.suspendedCtx = null;
  11688. this.contentVisible = true;
  11689. this.markedContentStack = markedContentStack || [];
  11690. this.optionalContentConfig = optionalContentConfig;
  11691. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  11692. this.cachedPatterns = new Map();
  11693. this.annotationCanvasMap = annotationCanvasMap;
  11694. this.viewportScale = 1;
  11695. this.outputScaleX = 1;
  11696. this.outputScaleY = 1;
  11697. this.pageColors = pageColors;
  11698. this._cachedScaleForStroking = [-1, 0];
  11699. this._cachedGetSinglePixelWidth = null;
  11700. this._cachedBitmapsMap = new Map();
  11701. }
  11702. getObject(data, fallback = null) {
  11703. if (typeof data === "string") {
  11704. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  11705. }
  11706. return fallback;
  11707. }
  11708. beginDrawing({
  11709. transform,
  11710. viewport,
  11711. transparency = false,
  11712. background = null
  11713. }) {
  11714. const width = this.ctx.canvas.width;
  11715. const height = this.ctx.canvas.height;
  11716. const savedFillStyle = this.ctx.fillStyle;
  11717. this.ctx.fillStyle = background || "#ffffff";
  11718. this.ctx.fillRect(0, 0, width, height);
  11719. this.ctx.fillStyle = savedFillStyle;
  11720. if (transparency) {
  11721. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  11722. this.compositeCtx = this.ctx;
  11723. this.transparentCanvas = transparentCanvas.canvas;
  11724. this.ctx = transparentCanvas.context;
  11725. this.ctx.save();
  11726. this.ctx.transform(...getCurrentTransform(this.compositeCtx));
  11727. }
  11728. this.ctx.save();
  11729. resetCtxToDefault(this.ctx);
  11730. if (transform) {
  11731. this.ctx.transform(...transform);
  11732. this.outputScaleX = transform[0];
  11733. this.outputScaleY = transform[0];
  11734. }
  11735. this.ctx.transform(...viewport.transform);
  11736. this.viewportScale = viewport.scale;
  11737. this.baseTransform = getCurrentTransform(this.ctx);
  11738. }
  11739. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  11740. const argsArray = operatorList.argsArray;
  11741. const fnArray = operatorList.fnArray;
  11742. let i = executionStartIdx || 0;
  11743. const argsArrayLen = argsArray.length;
  11744. if (argsArrayLen === i) {
  11745. return i;
  11746. }
  11747. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  11748. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  11749. let steps = 0;
  11750. const commonObjs = this.commonObjs;
  11751. const objs = this.objs;
  11752. let fnId;
  11753. while (true) {
  11754. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  11755. stepper.breakIt(i, continueCallback);
  11756. return i;
  11757. }
  11758. fnId = fnArray[i];
  11759. if (fnId !== OPS.dependency) {
  11760. this[fnId].apply(this, argsArray[i]);
  11761. } else {
  11762. for (const depObjId of argsArray[i]) {
  11763. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  11764. if (!objsPool.has(depObjId)) {
  11765. objsPool.get(depObjId, continueCallback);
  11766. return i;
  11767. }
  11768. }
  11769. }
  11770. i++;
  11771. if (i === argsArrayLen) {
  11772. return i;
  11773. }
  11774. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  11775. if (Date.now() > endTime) {
  11776. continueCallback();
  11777. return i;
  11778. }
  11779. steps = 0;
  11780. }
  11781. }
  11782. }
  11783. #restoreInitialState() {
  11784. while (this.stateStack.length || this.inSMaskMode) {
  11785. this.restore();
  11786. }
  11787. this.current.activeSMask = null;
  11788. this.ctx.restore();
  11789. if (this.transparentCanvas) {
  11790. this.ctx = this.compositeCtx;
  11791. this.ctx.save();
  11792. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  11793. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  11794. this.ctx.restore();
  11795. this.transparentCanvas = null;
  11796. }
  11797. }
  11798. endDrawing() {
  11799. this.#restoreInitialState();
  11800. this.cachedCanvases.clear();
  11801. this.cachedPatterns.clear();
  11802. for (const cache of this._cachedBitmapsMap.values()) {
  11803. for (const canvas of cache.values()) {
  11804. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  11805. canvas.width = canvas.height = 0;
  11806. }
  11807. }
  11808. cache.clear();
  11809. }
  11810. this._cachedBitmapsMap.clear();
  11811. this.#drawFilter();
  11812. }
  11813. #drawFilter() {
  11814. if (this.pageColors) {
  11815. const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
  11816. if (hcmFilterId !== "none") {
  11817. const savedFilter = this.ctx.filter;
  11818. this.ctx.filter = hcmFilterId;
  11819. this.ctx.drawImage(this.ctx.canvas, 0, 0);
  11820. this.ctx.filter = savedFilter;
  11821. }
  11822. }
  11823. }
  11824. _scaleImage(img, inverseTransform) {
  11825. const width = img.width ?? img.displayWidth;
  11826. const height = img.height ?? img.displayHeight;
  11827. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  11828. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  11829. let paintWidth = width,
  11830. paintHeight = height;
  11831. let tmpCanvasId = "prescale1";
  11832. let tmpCanvas, tmpCtx;
  11833. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  11834. let newWidth = paintWidth,
  11835. newHeight = paintHeight;
  11836. if (widthScale > 2 && paintWidth > 1) {
  11837. newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
  11838. widthScale /= paintWidth / newWidth;
  11839. }
  11840. if (heightScale > 2 && paintHeight > 1) {
  11841. newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
  11842. heightScale /= paintHeight / newHeight;
  11843. }
  11844. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  11845. tmpCtx = tmpCanvas.context;
  11846. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  11847. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  11848. img = tmpCanvas.canvas;
  11849. paintWidth = newWidth;
  11850. paintHeight = newHeight;
  11851. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  11852. }
  11853. return {
  11854. img,
  11855. paintWidth,
  11856. paintHeight
  11857. };
  11858. }
  11859. _createMaskCanvas(img) {
  11860. const ctx = this.ctx;
  11861. const {
  11862. width,
  11863. height
  11864. } = img;
  11865. const fillColor = this.current.fillColor;
  11866. const isPatternFill = this.current.patternFill;
  11867. const currentTransform = getCurrentTransform(ctx);
  11868. let cache, cacheKey, scaled, maskCanvas;
  11869. if ((img.bitmap || img.data) && img.count > 1) {
  11870. const mainKey = img.bitmap || img.data.buffer;
  11871. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  11872. cache = this._cachedBitmapsMap.get(mainKey);
  11873. if (!cache) {
  11874. cache = new Map();
  11875. this._cachedBitmapsMap.set(mainKey, cache);
  11876. }
  11877. const cachedImage = cache.get(cacheKey);
  11878. if (cachedImage && !isPatternFill) {
  11879. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  11880. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  11881. return {
  11882. canvas: cachedImage,
  11883. offsetX,
  11884. offsetY
  11885. };
  11886. }
  11887. scaled = cachedImage;
  11888. }
  11889. if (!scaled) {
  11890. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  11891. putBinaryImageMask(maskCanvas.context, img);
  11892. }
  11893. let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  11894. maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  11895. const minMax = MIN_MAX_INIT.slice();
  11896. Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax);
  11897. const [minX, minY, maxX, maxY] = minMax;
  11898. const drawnWidth = Math.round(maxX - minX) || 1;
  11899. const drawnHeight = Math.round(maxY - minY) || 1;
  11900. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  11901. const fillCtx = fillCanvas.context;
  11902. const offsetX = minX;
  11903. const offsetY = minY;
  11904. fillCtx.translate(-offsetX, -offsetY);
  11905. fillCtx.transform(...maskToCanvas);
  11906. if (!scaled) {
  11907. scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
  11908. scaled = scaled.img;
  11909. if (cache && isPatternFill) {
  11910. cache.set(cacheKey, scaled);
  11911. }
  11912. }
  11913. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
  11914. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  11915. fillCtx.globalCompositeOperation = "source-in";
  11916. const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  11917. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor;
  11918. fillCtx.fillRect(0, 0, width, height);
  11919. if (cache && !isPatternFill) {
  11920. this.cachedCanvases.delete("fillCanvas");
  11921. cache.set(cacheKey, fillCanvas.canvas);
  11922. }
  11923. return {
  11924. canvas: fillCanvas.canvas,
  11925. offsetX: Math.round(offsetX),
  11926. offsetY: Math.round(offsetY)
  11927. };
  11928. }
  11929. setLineWidth(width) {
  11930. if (width !== this.current.lineWidth) {
  11931. this._cachedScaleForStroking[0] = -1;
  11932. }
  11933. this.current.lineWidth = width;
  11934. this.ctx.lineWidth = width;
  11935. }
  11936. setLineCap(style) {
  11937. this.ctx.lineCap = LINE_CAP_STYLES[style];
  11938. }
  11939. setLineJoin(style) {
  11940. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  11941. }
  11942. setMiterLimit(limit) {
  11943. this.ctx.miterLimit = limit;
  11944. }
  11945. setDash(dashArray, dashPhase) {
  11946. const ctx = this.ctx;
  11947. if (ctx.setLineDash !== undefined) {
  11948. ctx.setLineDash(dashArray);
  11949. ctx.lineDashOffset = dashPhase;
  11950. }
  11951. }
  11952. setRenderingIntent(intent) {}
  11953. setFlatness(flatness) {}
  11954. setGState(states) {
  11955. for (const [key, value] of states) {
  11956. switch (key) {
  11957. case "LW":
  11958. this.setLineWidth(value);
  11959. break;
  11960. case "LC":
  11961. this.setLineCap(value);
  11962. break;
  11963. case "LJ":
  11964. this.setLineJoin(value);
  11965. break;
  11966. case "ML":
  11967. this.setMiterLimit(value);
  11968. break;
  11969. case "D":
  11970. this.setDash(value[0], value[1]);
  11971. break;
  11972. case "RI":
  11973. this.setRenderingIntent(value);
  11974. break;
  11975. case "FL":
  11976. this.setFlatness(value);
  11977. break;
  11978. case "Font":
  11979. this.setFont(value[0], value[1]);
  11980. break;
  11981. case "CA":
  11982. this.current.strokeAlpha = value;
  11983. break;
  11984. case "ca":
  11985. this.ctx.globalAlpha = this.current.fillAlpha = value;
  11986. break;
  11987. case "BM":
  11988. this.ctx.globalCompositeOperation = value;
  11989. break;
  11990. case "SMask":
  11991. this.current.activeSMask = value ? this.tempSMask : null;
  11992. this.tempSMask = null;
  11993. this.checkSMaskState();
  11994. break;
  11995. case "TR":
  11996. this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
  11997. break;
  11998. }
  11999. }
  12000. }
  12001. get inSMaskMode() {
  12002. return !!this.suspendedCtx;
  12003. }
  12004. checkSMaskState() {
  12005. const inSMaskMode = this.inSMaskMode;
  12006. if (this.current.activeSMask && !inSMaskMode) {
  12007. this.beginSMaskMode();
  12008. } else if (!this.current.activeSMask && inSMaskMode) {
  12009. this.endSMaskMode();
  12010. }
  12011. }
  12012. beginSMaskMode() {
  12013. if (this.inSMaskMode) {
  12014. throw new Error("beginSMaskMode called while already in smask mode");
  12015. }
  12016. const drawnWidth = this.ctx.canvas.width;
  12017. const drawnHeight = this.ctx.canvas.height;
  12018. const cacheId = "smaskGroupAt" + this.groupLevel;
  12019. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  12020. this.suspendedCtx = this.ctx;
  12021. const ctx = this.ctx = scratchCanvas.context;
  12022. ctx.setTransform(this.suspendedCtx.getTransform());
  12023. copyCtxState(this.suspendedCtx, ctx);
  12024. mirrorContextOperations(ctx, this.suspendedCtx);
  12025. this.setGState([["BM", "source-over"]]);
  12026. }
  12027. endSMaskMode() {
  12028. if (!this.inSMaskMode) {
  12029. throw new Error("endSMaskMode called while not in smask mode");
  12030. }
  12031. this.ctx._removeMirroring();
  12032. copyCtxState(this.ctx, this.suspendedCtx);
  12033. this.ctx = this.suspendedCtx;
  12034. this.suspendedCtx = null;
  12035. }
  12036. compose(dirtyBox) {
  12037. if (!this.current.activeSMask) {
  12038. return;
  12039. }
  12040. if (!dirtyBox) {
  12041. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  12042. } else {
  12043. dirtyBox[0] = Math.floor(dirtyBox[0]);
  12044. dirtyBox[1] = Math.floor(dirtyBox[1]);
  12045. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  12046. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  12047. }
  12048. const smask = this.current.activeSMask;
  12049. const suspendedCtx = this.suspendedCtx;
  12050. this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  12051. this.ctx.save();
  12052. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  12053. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  12054. this.ctx.restore();
  12055. }
  12056. composeSMask(ctx, smask, layerCtx, layerBox) {
  12057. const layerOffsetX = layerBox[0];
  12058. const layerOffsetY = layerBox[1];
  12059. const layerWidth = layerBox[2] - layerOffsetX;
  12060. const layerHeight = layerBox[3] - layerOffsetY;
  12061. if (layerWidth === 0 || layerHeight === 0) {
  12062. return;
  12063. }
  12064. this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  12065. ctx.save();
  12066. ctx.globalAlpha = 1;
  12067. ctx.globalCompositeOperation = "source-over";
  12068. ctx.setTransform(1, 0, 0, 1, 0, 0);
  12069. ctx.drawImage(layerCtx.canvas, 0, 0);
  12070. ctx.restore();
  12071. }
  12072. genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  12073. let maskCanvas = maskCtx.canvas;
  12074. let maskX = layerOffsetX - maskOffsetX;
  12075. let maskY = layerOffsetY - maskOffsetY;
  12076. if (backdrop) {
  12077. if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
  12078. const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
  12079. const ctx = canvas.context;
  12080. ctx.drawImage(maskCanvas, -maskX, -maskY);
  12081. ctx.globalCompositeOperation = "destination-atop";
  12082. ctx.fillStyle = backdrop;
  12083. ctx.fillRect(0, 0, width, height);
  12084. ctx.globalCompositeOperation = "source-over";
  12085. maskCanvas = canvas.canvas;
  12086. maskX = maskY = 0;
  12087. } else {
  12088. maskCtx.save();
  12089. maskCtx.globalAlpha = 1;
  12090. maskCtx.setTransform(1, 0, 0, 1, 0, 0);
  12091. const clip = new Path2D();
  12092. clip.rect(maskX, maskY, width, height);
  12093. maskCtx.clip(clip);
  12094. maskCtx.globalCompositeOperation = "destination-atop";
  12095. maskCtx.fillStyle = backdrop;
  12096. maskCtx.fillRect(maskX, maskY, width, height);
  12097. maskCtx.restore();
  12098. }
  12099. }
  12100. layerCtx.save();
  12101. layerCtx.globalAlpha = 1;
  12102. layerCtx.setTransform(1, 0, 0, 1, 0, 0);
  12103. if (subtype === "Alpha" && transferMap) {
  12104. layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
  12105. } else if (subtype === "Luminosity") {
  12106. layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
  12107. }
  12108. const clip = new Path2D();
  12109. clip.rect(layerOffsetX, layerOffsetY, width, height);
  12110. layerCtx.clip(clip);
  12111. layerCtx.globalCompositeOperation = "destination-in";
  12112. layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
  12113. layerCtx.restore();
  12114. }
  12115. save() {
  12116. if (this.inSMaskMode) {
  12117. copyCtxState(this.ctx, this.suspendedCtx);
  12118. }
  12119. this.ctx.save();
  12120. const old = this.current;
  12121. this.stateStack.push(old);
  12122. this.current = old.clone();
  12123. }
  12124. restore() {
  12125. if (this.stateStack.length === 0) {
  12126. if (this.inSMaskMode) {
  12127. this.endSMaskMode();
  12128. }
  12129. return;
  12130. }
  12131. this.current = this.stateStack.pop();
  12132. this.ctx.restore();
  12133. if (this.inSMaskMode) {
  12134. copyCtxState(this.suspendedCtx, this.ctx);
  12135. }
  12136. this.checkSMaskState();
  12137. this.pendingClip = null;
  12138. this._cachedScaleForStroking[0] = -1;
  12139. this._cachedGetSinglePixelWidth = null;
  12140. }
  12141. transform(a, b, c, d, e, f) {
  12142. this.ctx.transform(a, b, c, d, e, f);
  12143. this._cachedScaleForStroking[0] = -1;
  12144. this._cachedGetSinglePixelWidth = null;
  12145. }
  12146. constructPath(op, data, minMax) {
  12147. let [path] = data;
  12148. if (!minMax) {
  12149. path ||= data[0] = new Path2D();
  12150. this[op](path);
  12151. return;
  12152. }
  12153. if (!(path instanceof Path2D)) {
  12154. const path2d = data[0] = new Path2D();
  12155. for (let i = 0, ii = path.length; i < ii;) {
  12156. switch (path[i++]) {
  12157. case DrawOPS.moveTo:
  12158. path2d.moveTo(path[i++], path[i++]);
  12159. break;
  12160. case DrawOPS.lineTo:
  12161. path2d.lineTo(path[i++], path[i++]);
  12162. break;
  12163. case DrawOPS.curveTo:
  12164. path2d.bezierCurveTo(path[i++], path[i++], path[i++], path[i++], path[i++], path[i++]);
  12165. break;
  12166. case DrawOPS.closePath:
  12167. path2d.closePath();
  12168. break;
  12169. default:
  12170. warn(`Unrecognized drawing path operator: ${path[i - 1]}`);
  12171. break;
  12172. }
  12173. }
  12174. path = path2d;
  12175. }
  12176. Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax);
  12177. this[op](path);
  12178. }
  12179. closePath() {
  12180. this.ctx.closePath();
  12181. }
  12182. stroke(path, consumePath = true) {
  12183. const ctx = this.ctx;
  12184. const strokeColor = this.current.strokeColor;
  12185. ctx.globalAlpha = this.current.strokeAlpha;
  12186. if (this.contentVisible) {
  12187. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  12188. const baseTransform = strokeColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;
  12189. ctx.save();
  12190. ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
  12191. if (baseTransform) {
  12192. const newPath = new Path2D();
  12193. newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
  12194. path = newPath;
  12195. }
  12196. this.rescaleAndStroke(path, false);
  12197. ctx.restore();
  12198. } else {
  12199. this.rescaleAndStroke(path, true);
  12200. }
  12201. }
  12202. if (consumePath) {
  12203. this.consumePath(path, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx)));
  12204. }
  12205. ctx.globalAlpha = this.current.fillAlpha;
  12206. }
  12207. closeStroke(path) {
  12208. this.stroke(path);
  12209. }
  12210. fill(path, consumePath = true) {
  12211. const ctx = this.ctx;
  12212. const fillColor = this.current.fillColor;
  12213. const isPatternFill = this.current.patternFill;
  12214. let needRestore = false;
  12215. if (isPatternFill) {
  12216. const baseTransform = fillColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;
  12217. ctx.save();
  12218. ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  12219. if (baseTransform) {
  12220. const newPath = new Path2D();
  12221. newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
  12222. path = newPath;
  12223. }
  12224. needRestore = true;
  12225. }
  12226. const intersect = this.current.getClippedPathBoundingBox();
  12227. if (this.contentVisible && intersect !== null) {
  12228. if (this.pendingEOFill) {
  12229. ctx.fill(path, "evenodd");
  12230. this.pendingEOFill = false;
  12231. } else {
  12232. ctx.fill(path);
  12233. }
  12234. }
  12235. if (needRestore) {
  12236. ctx.restore();
  12237. }
  12238. if (consumePath) {
  12239. this.consumePath(path, intersect);
  12240. }
  12241. }
  12242. eoFill(path) {
  12243. this.pendingEOFill = true;
  12244. this.fill(path);
  12245. }
  12246. fillStroke(path) {
  12247. this.fill(path, false);
  12248. this.stroke(path, false);
  12249. this.consumePath(path);
  12250. }
  12251. eoFillStroke(path) {
  12252. this.pendingEOFill = true;
  12253. this.fillStroke(path);
  12254. }
  12255. closeFillStroke(path) {
  12256. this.fillStroke(path);
  12257. }
  12258. closeEOFillStroke(path) {
  12259. this.pendingEOFill = true;
  12260. this.fillStroke(path);
  12261. }
  12262. endPath(path) {
  12263. this.consumePath(path);
  12264. }
  12265. rawFillPath(path) {
  12266. this.ctx.fill(path);
  12267. }
  12268. clip() {
  12269. this.pendingClip = NORMAL_CLIP;
  12270. }
  12271. eoClip() {
  12272. this.pendingClip = EO_CLIP;
  12273. }
  12274. beginText() {
  12275. this.current.textMatrix = null;
  12276. this.current.textMatrixScale = 1;
  12277. this.current.x = this.current.lineX = 0;
  12278. this.current.y = this.current.lineY = 0;
  12279. }
  12280. endText() {
  12281. const paths = this.pendingTextPaths;
  12282. const ctx = this.ctx;
  12283. if (paths === undefined) {
  12284. return;
  12285. }
  12286. const newPath = new Path2D();
  12287. const invTransf = ctx.getTransform().invertSelf();
  12288. for (const {
  12289. transform,
  12290. x,
  12291. y,
  12292. fontSize,
  12293. path
  12294. } of paths) {
  12295. newPath.addPath(path, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x, y).scale(fontSize, -fontSize));
  12296. }
  12297. ctx.clip(newPath);
  12298. delete this.pendingTextPaths;
  12299. }
  12300. setCharSpacing(spacing) {
  12301. this.current.charSpacing = spacing;
  12302. }
  12303. setWordSpacing(spacing) {
  12304. this.current.wordSpacing = spacing;
  12305. }
  12306. setHScale(scale) {
  12307. this.current.textHScale = scale / 100;
  12308. }
  12309. setLeading(leading) {
  12310. this.current.leading = -leading;
  12311. }
  12312. setFont(fontRefName, size) {
  12313. const fontObj = this.commonObjs.get(fontRefName);
  12314. const current = this.current;
  12315. if (!fontObj) {
  12316. throw new Error(`Can't find font for ${fontRefName}`);
  12317. }
  12318. current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
  12319. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  12320. warn("Invalid font matrix for font " + fontRefName);
  12321. }
  12322. if (size < 0) {
  12323. size = -size;
  12324. current.fontDirection = -1;
  12325. } else {
  12326. current.fontDirection = 1;
  12327. }
  12328. this.current.font = fontObj;
  12329. this.current.fontSize = size;
  12330. if (fontObj.isType3Font) {
  12331. return;
  12332. }
  12333. const name = fontObj.loadedName || "sans-serif";
  12334. const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
  12335. let bold = "normal";
  12336. if (fontObj.black) {
  12337. bold = "900";
  12338. } else if (fontObj.bold) {
  12339. bold = "bold";
  12340. }
  12341. const italic = fontObj.italic ? "italic" : "normal";
  12342. let browserFontSize = size;
  12343. if (size < MIN_FONT_SIZE) {
  12344. browserFontSize = MIN_FONT_SIZE;
  12345. } else if (size > MAX_FONT_SIZE) {
  12346. browserFontSize = MAX_FONT_SIZE;
  12347. }
  12348. this.current.fontSizeScale = size / browserFontSize;
  12349. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  12350. }
  12351. setTextRenderingMode(mode) {
  12352. this.current.textRenderingMode = mode;
  12353. }
  12354. setTextRise(rise) {
  12355. this.current.textRise = rise;
  12356. }
  12357. moveText(x, y) {
  12358. this.current.x = this.current.lineX += x;
  12359. this.current.y = this.current.lineY += y;
  12360. }
  12361. setLeadingMoveText(x, y) {
  12362. this.setLeading(-y);
  12363. this.moveText(x, y);
  12364. }
  12365. setTextMatrix(matrix) {
  12366. const {
  12367. current
  12368. } = this;
  12369. current.textMatrix = matrix;
  12370. current.textMatrixScale = Math.hypot(matrix[0], matrix[1]);
  12371. current.x = current.lineX = 0;
  12372. current.y = current.lineY = 0;
  12373. }
  12374. nextLine() {
  12375. this.moveText(0, this.current.leading);
  12376. }
  12377. #getScaledPath(path, currentTransform, transform) {
  12378. const newPath = new Path2D();
  12379. newPath.addPath(path, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform));
  12380. return newPath;
  12381. }
  12382. paintChar(character, x, y, patternFillTransform, patternStrokeTransform) {
  12383. const ctx = this.ctx;
  12384. const current = this.current;
  12385. const font = current.font;
  12386. const textRenderingMode = current.textRenderingMode;
  12387. const fontSize = current.fontSize / current.fontSizeScale;
  12388. const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  12389. const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  12390. const patternFill = current.patternFill && !font.missingFile;
  12391. const patternStroke = current.patternStroke && !font.missingFile;
  12392. let path;
  12393. if (font.disableFontFace || isAddToPathSet || patternFill || patternStroke) {
  12394. path = font.getPathGenerator(this.commonObjs, character);
  12395. }
  12396. if (font.disableFontFace || patternFill || patternStroke) {
  12397. ctx.save();
  12398. ctx.translate(x, y);
  12399. ctx.scale(fontSize, -fontSize);
  12400. let currentTransform;
  12401. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  12402. if (patternFillTransform) {
  12403. currentTransform = ctx.getTransform();
  12404. ctx.setTransform(...patternFillTransform);
  12405. ctx.fill(this.#getScaledPath(path, currentTransform, patternFillTransform));
  12406. } else {
  12407. ctx.fill(path);
  12408. }
  12409. }
  12410. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  12411. if (patternStrokeTransform) {
  12412. currentTransform ||= ctx.getTransform();
  12413. ctx.setTransform(...patternStrokeTransform);
  12414. const {
  12415. a,
  12416. b,
  12417. c,
  12418. d
  12419. } = currentTransform;
  12420. const invPatternTransform = Util.inverseTransform(patternStrokeTransform);
  12421. const transf = Util.transform([a, b, c, d, 0, 0], invPatternTransform);
  12422. Util.singularValueDecompose2dScale(transf, XY);
  12423. ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize;
  12424. ctx.stroke(this.#getScaledPath(path, currentTransform, patternStrokeTransform));
  12425. } else {
  12426. ctx.lineWidth /= fontSize;
  12427. ctx.stroke(path);
  12428. }
  12429. }
  12430. ctx.restore();
  12431. } else {
  12432. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  12433. ctx.fillText(character, x, y);
  12434. }
  12435. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  12436. ctx.strokeText(character, x, y);
  12437. }
  12438. }
  12439. if (isAddToPathSet) {
  12440. const paths = this.pendingTextPaths ||= [];
  12441. paths.push({
  12442. transform: getCurrentTransform(ctx),
  12443. x,
  12444. y,
  12445. fontSize,
  12446. path
  12447. });
  12448. }
  12449. }
  12450. get isFontSubpixelAAEnabled() {
  12451. const {
  12452. context: ctx
  12453. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  12454. ctx.scale(1.5, 1);
  12455. ctx.fillText("I", 0, 10);
  12456. const data = ctx.getImageData(0, 0, 10, 10).data;
  12457. let enabled = false;
  12458. for (let i = 3; i < data.length; i += 4) {
  12459. if (data[i] > 0 && data[i] < 255) {
  12460. enabled = true;
  12461. break;
  12462. }
  12463. }
  12464. return shadow(this, "isFontSubpixelAAEnabled", enabled);
  12465. }
  12466. showText(glyphs) {
  12467. const current = this.current;
  12468. const font = current.font;
  12469. if (font.isType3Font) {
  12470. return this.showType3Text(glyphs);
  12471. }
  12472. const fontSize = current.fontSize;
  12473. if (fontSize === 0) {
  12474. return undefined;
  12475. }
  12476. const ctx = this.ctx;
  12477. const fontSizeScale = current.fontSizeScale;
  12478. const charSpacing = current.charSpacing;
  12479. const wordSpacing = current.wordSpacing;
  12480. const fontDirection = current.fontDirection;
  12481. const textHScale = current.textHScale * fontDirection;
  12482. const glyphsLength = glyphs.length;
  12483. const vertical = font.vertical;
  12484. const spacingDir = vertical ? 1 : -1;
  12485. const defaultVMetrics = font.defaultVMetrics;
  12486. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  12487. const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  12488. ctx.save();
  12489. if (current.textMatrix) {
  12490. ctx.transform(...current.textMatrix);
  12491. }
  12492. ctx.translate(current.x, current.y + current.textRise);
  12493. if (fontDirection > 0) {
  12494. ctx.scale(textHScale, -1);
  12495. } else {
  12496. ctx.scale(textHScale, 1);
  12497. }
  12498. let patternFillTransform, patternStrokeTransform;
  12499. if (current.patternFill) {
  12500. ctx.save();
  12501. const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  12502. patternFillTransform = getCurrentTransform(ctx);
  12503. ctx.restore();
  12504. ctx.fillStyle = pattern;
  12505. }
  12506. if (current.patternStroke) {
  12507. ctx.save();
  12508. const pattern = current.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
  12509. patternStrokeTransform = getCurrentTransform(ctx);
  12510. ctx.restore();
  12511. ctx.strokeStyle = pattern;
  12512. }
  12513. let lineWidth = current.lineWidth;
  12514. const scale = current.textMatrixScale;
  12515. if (scale === 0 || lineWidth === 0) {
  12516. const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  12517. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  12518. lineWidth = this.getSinglePixelWidth();
  12519. }
  12520. } else {
  12521. lineWidth /= scale;
  12522. }
  12523. if (fontSizeScale !== 1.0) {
  12524. ctx.scale(fontSizeScale, fontSizeScale);
  12525. lineWidth /= fontSizeScale;
  12526. }
  12527. ctx.lineWidth = lineWidth;
  12528. if (font.isInvalidPDFjsFont) {
  12529. const chars = [];
  12530. let width = 0;
  12531. for (const glyph of glyphs) {
  12532. chars.push(glyph.unicode);
  12533. width += glyph.width;
  12534. }
  12535. ctx.fillText(chars.join(""), 0, 0);
  12536. current.x += width * widthAdvanceScale * textHScale;
  12537. ctx.restore();
  12538. this.compose();
  12539. return undefined;
  12540. }
  12541. let x = 0,
  12542. i;
  12543. for (i = 0; i < glyphsLength; ++i) {
  12544. const glyph = glyphs[i];
  12545. if (typeof glyph === "number") {
  12546. x += spacingDir * glyph * fontSize / 1000;
  12547. continue;
  12548. }
  12549. let restoreNeeded = false;
  12550. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  12551. const character = glyph.fontChar;
  12552. const accent = glyph.accent;
  12553. let scaledX, scaledY;
  12554. let width = glyph.width;
  12555. if (vertical) {
  12556. const vmetric = glyph.vmetric || defaultVMetrics;
  12557. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  12558. const vy = vmetric[2] * widthAdvanceScale;
  12559. width = vmetric ? -vmetric[0] : width;
  12560. scaledX = vx / fontSizeScale;
  12561. scaledY = (x + vy) / fontSizeScale;
  12562. } else {
  12563. scaledX = x / fontSizeScale;
  12564. scaledY = 0;
  12565. }
  12566. if (font.remeasure && width > 0) {
  12567. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  12568. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  12569. const characterScaleX = width / measuredWidth;
  12570. restoreNeeded = true;
  12571. ctx.save();
  12572. ctx.scale(characterScaleX, 1);
  12573. scaledX /= characterScaleX;
  12574. } else if (width !== measuredWidth) {
  12575. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  12576. }
  12577. }
  12578. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  12579. if (simpleFillText && !accent) {
  12580. ctx.fillText(character, scaledX, scaledY);
  12581. } else {
  12582. this.paintChar(character, scaledX, scaledY, patternFillTransform, patternStrokeTransform);
  12583. if (accent) {
  12584. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  12585. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  12586. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform);
  12587. }
  12588. }
  12589. }
  12590. const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
  12591. x += charWidth;
  12592. if (restoreNeeded) {
  12593. ctx.restore();
  12594. }
  12595. }
  12596. if (vertical) {
  12597. current.y -= x;
  12598. } else {
  12599. current.x += x * textHScale;
  12600. }
  12601. ctx.restore();
  12602. this.compose();
  12603. return undefined;
  12604. }
  12605. showType3Text(glyphs) {
  12606. const ctx = this.ctx;
  12607. const current = this.current;
  12608. const font = current.font;
  12609. const fontSize = current.fontSize;
  12610. const fontDirection = current.fontDirection;
  12611. const spacingDir = font.vertical ? 1 : -1;
  12612. const charSpacing = current.charSpacing;
  12613. const wordSpacing = current.wordSpacing;
  12614. const textHScale = current.textHScale * fontDirection;
  12615. const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  12616. const glyphsLength = glyphs.length;
  12617. const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  12618. let i, glyph, width, spacingLength;
  12619. if (isTextInvisible || fontSize === 0) {
  12620. return;
  12621. }
  12622. this._cachedScaleForStroking[0] = -1;
  12623. this._cachedGetSinglePixelWidth = null;
  12624. ctx.save();
  12625. if (current.textMatrix) {
  12626. ctx.transform(...current.textMatrix);
  12627. }
  12628. ctx.translate(current.x, current.y + current.textRise);
  12629. ctx.scale(textHScale, fontDirection);
  12630. for (i = 0; i < glyphsLength; ++i) {
  12631. glyph = glyphs[i];
  12632. if (typeof glyph === "number") {
  12633. spacingLength = spacingDir * glyph * fontSize / 1000;
  12634. this.ctx.translate(spacingLength, 0);
  12635. current.x += spacingLength * textHScale;
  12636. continue;
  12637. }
  12638. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  12639. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  12640. if (!operatorList) {
  12641. warn(`Type3 character "${glyph.operatorListId}" is not available.`);
  12642. } else if (this.contentVisible) {
  12643. this.save();
  12644. ctx.scale(fontSize, fontSize);
  12645. ctx.transform(...fontMatrix);
  12646. this.executeOperatorList(operatorList);
  12647. this.restore();
  12648. }
  12649. const p = [glyph.width, 0];
  12650. Util.applyTransform(p, fontMatrix);
  12651. width = p[0] * fontSize + spacing;
  12652. ctx.translate(width, 0);
  12653. current.x += width * textHScale;
  12654. }
  12655. ctx.restore();
  12656. }
  12657. setCharWidth(xWidth, yWidth) {}
  12658. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  12659. const clip = new Path2D();
  12660. clip.rect(llx, lly, urx - llx, ury - lly);
  12661. this.ctx.clip(clip);
  12662. this.endPath();
  12663. }
  12664. getColorN_Pattern(IR) {
  12665. let pattern;
  12666. if (IR[0] === "TilingPattern") {
  12667. const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
  12668. const canvasGraphicsFactory = {
  12669. createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  12670. optionalContentConfig: this.optionalContentConfig,
  12671. markedContentStack: this.markedContentStack
  12672. })
  12673. };
  12674. pattern = new TilingPattern(IR, this.ctx, canvasGraphicsFactory, baseTransform);
  12675. } else {
  12676. pattern = this._getPattern(IR[1], IR[2]);
  12677. }
  12678. return pattern;
  12679. }
  12680. setStrokeColorN() {
  12681. this.current.strokeColor = this.getColorN_Pattern(arguments);
  12682. this.current.patternStroke = true;
  12683. }
  12684. setFillColorN() {
  12685. this.current.fillColor = this.getColorN_Pattern(arguments);
  12686. this.current.patternFill = true;
  12687. }
  12688. setStrokeRGBColor(color) {
  12689. this.ctx.strokeStyle = this.current.strokeColor = color;
  12690. this.current.patternStroke = false;
  12691. }
  12692. setStrokeTransparent() {
  12693. this.ctx.strokeStyle = this.current.strokeColor = "transparent";
  12694. this.current.patternStroke = false;
  12695. }
  12696. setFillRGBColor(color) {
  12697. this.ctx.fillStyle = this.current.fillColor = color;
  12698. this.current.patternFill = false;
  12699. }
  12700. setFillTransparent() {
  12701. this.ctx.fillStyle = this.current.fillColor = "transparent";
  12702. this.current.patternFill = false;
  12703. }
  12704. _getPattern(objId, matrix = null) {
  12705. let pattern;
  12706. if (this.cachedPatterns.has(objId)) {
  12707. pattern = this.cachedPatterns.get(objId);
  12708. } else {
  12709. pattern = getShadingPattern(this.getObject(objId));
  12710. this.cachedPatterns.set(objId, pattern);
  12711. }
  12712. if (matrix) {
  12713. pattern.matrix = matrix;
  12714. }
  12715. return pattern;
  12716. }
  12717. shadingFill(objId) {
  12718. if (!this.contentVisible) {
  12719. return;
  12720. }
  12721. const ctx = this.ctx;
  12722. this.save();
  12723. const pattern = this._getPattern(objId);
  12724. ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING);
  12725. const inv = getCurrentTransformInverse(ctx);
  12726. if (inv) {
  12727. const {
  12728. width,
  12729. height
  12730. } = ctx.canvas;
  12731. const minMax = MIN_MAX_INIT.slice();
  12732. Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax);
  12733. const [x0, y0, x1, y1] = minMax;
  12734. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  12735. } else {
  12736. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  12737. }
  12738. this.compose(this.current.getClippedPathBoundingBox());
  12739. this.restore();
  12740. }
  12741. beginInlineImage() {
  12742. unreachable("Should not call beginInlineImage");
  12743. }
  12744. beginImageData() {
  12745. unreachable("Should not call beginImageData");
  12746. }
  12747. paintFormXObjectBegin(matrix, bbox) {
  12748. if (!this.contentVisible) {
  12749. return;
  12750. }
  12751. this.save();
  12752. this.baseTransformStack.push(this.baseTransform);
  12753. if (matrix) {
  12754. this.transform(...matrix);
  12755. }
  12756. this.baseTransform = getCurrentTransform(this.ctx);
  12757. if (bbox) {
  12758. Util.axialAlignedBoundingBox(bbox, this.baseTransform, this.current.minMax);
  12759. const [x0, y0, x1, y1] = bbox;
  12760. const clip = new Path2D();
  12761. clip.rect(x0, y0, x1 - x0, y1 - y0);
  12762. this.ctx.clip(clip);
  12763. this.endPath();
  12764. }
  12765. }
  12766. paintFormXObjectEnd() {
  12767. if (!this.contentVisible) {
  12768. return;
  12769. }
  12770. this.restore();
  12771. this.baseTransform = this.baseTransformStack.pop();
  12772. }
  12773. beginGroup(group) {
  12774. if (!this.contentVisible) {
  12775. return;
  12776. }
  12777. this.save();
  12778. if (this.inSMaskMode) {
  12779. this.endSMaskMode();
  12780. this.current.activeSMask = null;
  12781. }
  12782. const currentCtx = this.ctx;
  12783. if (!group.isolated) {
  12784. info("TODO: Support non-isolated groups.");
  12785. }
  12786. if (group.knockout) {
  12787. warn("Knockout groups not supported.");
  12788. }
  12789. const currentTransform = getCurrentTransform(currentCtx);
  12790. if (group.matrix) {
  12791. currentCtx.transform(...group.matrix);
  12792. }
  12793. if (!group.bbox) {
  12794. throw new Error("Bounding box is required.");
  12795. }
  12796. let bounds = MIN_MAX_INIT.slice();
  12797. Util.axialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx), bounds);
  12798. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  12799. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  12800. const offsetX = Math.floor(bounds[0]);
  12801. const offsetY = Math.floor(bounds[1]);
  12802. const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  12803. const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  12804. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  12805. let cacheId = "groupAt" + this.groupLevel;
  12806. if (group.smask) {
  12807. cacheId += "_smask_" + this.smaskCounter++ % 2;
  12808. }
  12809. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  12810. const groupCtx = scratchCanvas.context;
  12811. groupCtx.translate(-offsetX, -offsetY);
  12812. groupCtx.transform(...currentTransform);
  12813. let clip = new Path2D();
  12814. const [x0, y0, x1, y1] = group.bbox;
  12815. clip.rect(x0, y0, x1 - x0, y1 - y0);
  12816. if (group.matrix) {
  12817. const path = new Path2D();
  12818. path.addPath(clip, new DOMMatrix(group.matrix));
  12819. clip = path;
  12820. }
  12821. groupCtx.clip(clip);
  12822. if (group.smask) {
  12823. this.smaskStack.push({
  12824. canvas: scratchCanvas.canvas,
  12825. context: groupCtx,
  12826. offsetX,
  12827. offsetY,
  12828. subtype: group.smask.subtype,
  12829. backdrop: group.smask.backdrop,
  12830. transferMap: group.smask.transferMap || null,
  12831. startTransformInverse: null
  12832. });
  12833. } else {
  12834. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  12835. currentCtx.translate(offsetX, offsetY);
  12836. currentCtx.save();
  12837. }
  12838. copyCtxState(currentCtx, groupCtx);
  12839. this.ctx = groupCtx;
  12840. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  12841. this.groupStack.push(currentCtx);
  12842. this.groupLevel++;
  12843. }
  12844. endGroup(group) {
  12845. if (!this.contentVisible) {
  12846. return;
  12847. }
  12848. this.groupLevel--;
  12849. const groupCtx = this.ctx;
  12850. const ctx = this.groupStack.pop();
  12851. this.ctx = ctx;
  12852. this.ctx.imageSmoothingEnabled = false;
  12853. if (group.smask) {
  12854. this.tempSMask = this.smaskStack.pop();
  12855. this.restore();
  12856. } else {
  12857. this.ctx.restore();
  12858. const currentMtx = getCurrentTransform(this.ctx);
  12859. this.restore();
  12860. this.ctx.save();
  12861. this.ctx.setTransform(...currentMtx);
  12862. const dirtyBox = MIN_MAX_INIT.slice();
  12863. Util.axialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx, dirtyBox);
  12864. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  12865. this.ctx.restore();
  12866. this.compose(dirtyBox);
  12867. }
  12868. }
  12869. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  12870. this.#restoreInitialState();
  12871. resetCtxToDefault(this.ctx);
  12872. this.ctx.save();
  12873. this.save();
  12874. if (this.baseTransform) {
  12875. this.ctx.setTransform(...this.baseTransform);
  12876. }
  12877. if (rect) {
  12878. const width = rect[2] - rect[0];
  12879. const height = rect[3] - rect[1];
  12880. if (hasOwnCanvas && this.annotationCanvasMap) {
  12881. transform = transform.slice();
  12882. transform[4] -= rect[0];
  12883. transform[5] -= rect[1];
  12884. rect = rect.slice();
  12885. rect[0] = rect[1] = 0;
  12886. rect[2] = width;
  12887. rect[3] = height;
  12888. Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx), XY);
  12889. const {
  12890. viewportScale
  12891. } = this;
  12892. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  12893. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  12894. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  12895. const {
  12896. canvas,
  12897. context
  12898. } = this.annotationCanvas;
  12899. this.annotationCanvasMap.set(id, canvas);
  12900. this.annotationCanvas.savedCtx = this.ctx;
  12901. this.ctx = context;
  12902. this.ctx.save();
  12903. this.ctx.setTransform(XY[0], 0, 0, -XY[1], 0, height * XY[1]);
  12904. resetCtxToDefault(this.ctx);
  12905. } else {
  12906. resetCtxToDefault(this.ctx);
  12907. this.endPath();
  12908. const clip = new Path2D();
  12909. clip.rect(rect[0], rect[1], width, height);
  12910. this.ctx.clip(clip);
  12911. }
  12912. }
  12913. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  12914. this.transform(...transform);
  12915. this.transform(...matrix);
  12916. }
  12917. endAnnotation() {
  12918. if (this.annotationCanvas) {
  12919. this.ctx.restore();
  12920. this.#drawFilter();
  12921. this.ctx = this.annotationCanvas.savedCtx;
  12922. delete this.annotationCanvas.savedCtx;
  12923. delete this.annotationCanvas;
  12924. }
  12925. }
  12926. paintImageMaskXObject(img) {
  12927. if (!this.contentVisible) {
  12928. return;
  12929. }
  12930. const count = img.count;
  12931. img = this.getObject(img.data, img);
  12932. img.count = count;
  12933. const ctx = this.ctx;
  12934. const mask = this._createMaskCanvas(img);
  12935. const maskCanvas = mask.canvas;
  12936. ctx.save();
  12937. ctx.setTransform(1, 0, 0, 1, 0, 0);
  12938. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  12939. ctx.restore();
  12940. this.compose();
  12941. }
  12942. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  12943. if (!this.contentVisible) {
  12944. return;
  12945. }
  12946. img = this.getObject(img.data, img);
  12947. const ctx = this.ctx;
  12948. ctx.save();
  12949. const currentTransform = getCurrentTransform(ctx);
  12950. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  12951. const mask = this._createMaskCanvas(img);
  12952. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  12953. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  12954. const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  12955. ctx.drawImage(mask.canvas, trans[4], trans[5]);
  12956. }
  12957. ctx.restore();
  12958. this.compose();
  12959. }
  12960. paintImageMaskXObjectGroup(images) {
  12961. if (!this.contentVisible) {
  12962. return;
  12963. }
  12964. const ctx = this.ctx;
  12965. const fillColor = this.current.fillColor;
  12966. const isPatternFill = this.current.patternFill;
  12967. for (const image of images) {
  12968. const {
  12969. data,
  12970. width,
  12971. height,
  12972. transform
  12973. } = image;
  12974. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  12975. const maskCtx = maskCanvas.context;
  12976. maskCtx.save();
  12977. const img = this.getObject(data, image);
  12978. putBinaryImageMask(maskCtx, img);
  12979. maskCtx.globalCompositeOperation = "source-in";
  12980. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor;
  12981. maskCtx.fillRect(0, 0, width, height);
  12982. maskCtx.restore();
  12983. ctx.save();
  12984. ctx.transform(...transform);
  12985. ctx.scale(1, -1);
  12986. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  12987. ctx.restore();
  12988. }
  12989. this.compose();
  12990. }
  12991. paintImageXObject(objId) {
  12992. if (!this.contentVisible) {
  12993. return;
  12994. }
  12995. const imgData = this.getObject(objId);
  12996. if (!imgData) {
  12997. warn("Dependent image isn't ready yet");
  12998. return;
  12999. }
  13000. this.paintInlineImageXObject(imgData);
  13001. }
  13002. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  13003. if (!this.contentVisible) {
  13004. return;
  13005. }
  13006. const imgData = this.getObject(objId);
  13007. if (!imgData) {
  13008. warn("Dependent image isn't ready yet");
  13009. return;
  13010. }
  13011. const width = imgData.width;
  13012. const height = imgData.height;
  13013. const map = [];
  13014. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  13015. map.push({
  13016. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  13017. x: 0,
  13018. y: 0,
  13019. w: width,
  13020. h: height
  13021. });
  13022. }
  13023. this.paintInlineImageXObjectGroup(imgData, map);
  13024. }
  13025. applyTransferMapsToCanvas(ctx) {
  13026. if (this.current.transferMaps !== "none") {
  13027. ctx.filter = this.current.transferMaps;
  13028. ctx.drawImage(ctx.canvas, 0, 0);
  13029. ctx.filter = "none";
  13030. }
  13031. return ctx.canvas;
  13032. }
  13033. applyTransferMapsToBitmap(imgData) {
  13034. if (this.current.transferMaps === "none") {
  13035. return imgData.bitmap;
  13036. }
  13037. const {
  13038. bitmap,
  13039. width,
  13040. height
  13041. } = imgData;
  13042. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  13043. const tmpCtx = tmpCanvas.context;
  13044. tmpCtx.filter = this.current.transferMaps;
  13045. tmpCtx.drawImage(bitmap, 0, 0);
  13046. tmpCtx.filter = "none";
  13047. return tmpCanvas.canvas;
  13048. }
  13049. paintInlineImageXObject(imgData) {
  13050. if (!this.contentVisible) {
  13051. return;
  13052. }
  13053. const width = imgData.width;
  13054. const height = imgData.height;
  13055. const ctx = this.ctx;
  13056. this.save();
  13057. const {
  13058. filter
  13059. } = ctx;
  13060. if (filter !== "none" && filter !== "") {
  13061. ctx.filter = "none";
  13062. }
  13063. ctx.scale(1 / width, -1 / height);
  13064. let imgToPaint;
  13065. if (imgData.bitmap) {
  13066. imgToPaint = this.applyTransferMapsToBitmap(imgData);
  13067. } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  13068. imgToPaint = imgData;
  13069. } else {
  13070. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  13071. const tmpCtx = tmpCanvas.context;
  13072. putBinaryImageData(tmpCtx, imgData);
  13073. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  13074. }
  13075. const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
  13076. ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
  13077. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  13078. this.compose();
  13079. this.restore();
  13080. }
  13081. paintInlineImageXObjectGroup(imgData, map) {
  13082. if (!this.contentVisible) {
  13083. return;
  13084. }
  13085. const ctx = this.ctx;
  13086. let imgToPaint;
  13087. if (imgData.bitmap) {
  13088. imgToPaint = imgData.bitmap;
  13089. } else {
  13090. const w = imgData.width;
  13091. const h = imgData.height;
  13092. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  13093. const tmpCtx = tmpCanvas.context;
  13094. putBinaryImageData(tmpCtx, imgData);
  13095. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  13096. }
  13097. for (const entry of map) {
  13098. ctx.save();
  13099. ctx.transform(...entry.transform);
  13100. ctx.scale(1, -1);
  13101. drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  13102. ctx.restore();
  13103. }
  13104. this.compose();
  13105. }
  13106. paintSolidColorImageMask() {
  13107. if (!this.contentVisible) {
  13108. return;
  13109. }
  13110. this.ctx.fillRect(0, 0, 1, 1);
  13111. this.compose();
  13112. }
  13113. markPoint(tag) {}
  13114. markPointProps(tag, properties) {}
  13115. beginMarkedContent(tag) {
  13116. this.markedContentStack.push({
  13117. visible: true
  13118. });
  13119. }
  13120. beginMarkedContentProps(tag, properties) {
  13121. if (tag === "OC") {
  13122. this.markedContentStack.push({
  13123. visible: this.optionalContentConfig.isVisible(properties)
  13124. });
  13125. } else {
  13126. this.markedContentStack.push({
  13127. visible: true
  13128. });
  13129. }
  13130. this.contentVisible = this.isContentVisible();
  13131. }
  13132. endMarkedContent() {
  13133. this.markedContentStack.pop();
  13134. this.contentVisible = this.isContentVisible();
  13135. }
  13136. beginCompat() {}
  13137. endCompat() {}
  13138. consumePath(path, clipBox) {
  13139. const isEmpty = this.current.isEmptyClip();
  13140. if (this.pendingClip) {
  13141. this.current.updateClipFromPath();
  13142. }
  13143. if (!this.pendingClip) {
  13144. this.compose(clipBox);
  13145. }
  13146. const ctx = this.ctx;
  13147. if (this.pendingClip) {
  13148. if (!isEmpty) {
  13149. if (this.pendingClip === EO_CLIP) {
  13150. ctx.clip(path, "evenodd");
  13151. } else {
  13152. ctx.clip(path);
  13153. }
  13154. }
  13155. this.pendingClip = null;
  13156. }
  13157. this.current.startNewPathAndClipBox(this.current.clipBox);
  13158. }
  13159. getSinglePixelWidth() {
  13160. if (!this._cachedGetSinglePixelWidth) {
  13161. const m = getCurrentTransform(this.ctx);
  13162. if (m[1] === 0 && m[2] === 0) {
  13163. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  13164. } else {
  13165. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  13166. const normX = Math.hypot(m[0], m[2]);
  13167. const normY = Math.hypot(m[1], m[3]);
  13168. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  13169. }
  13170. }
  13171. return this._cachedGetSinglePixelWidth;
  13172. }
  13173. getScaleForStroking() {
  13174. if (this._cachedScaleForStroking[0] === -1) {
  13175. const {
  13176. lineWidth
  13177. } = this.current;
  13178. const {
  13179. a,
  13180. b,
  13181. c,
  13182. d
  13183. } = this.ctx.getTransform();
  13184. let scaleX, scaleY;
  13185. if (b === 0 && c === 0) {
  13186. const normX = Math.abs(a);
  13187. const normY = Math.abs(d);
  13188. if (normX === normY) {
  13189. if (lineWidth === 0) {
  13190. scaleX = scaleY = 1 / normX;
  13191. } else {
  13192. const scaledLineWidth = normX * lineWidth;
  13193. scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
  13194. }
  13195. } else if (lineWidth === 0) {
  13196. scaleX = 1 / normX;
  13197. scaleY = 1 / normY;
  13198. } else {
  13199. const scaledXLineWidth = normX * lineWidth;
  13200. const scaledYLineWidth = normY * lineWidth;
  13201. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  13202. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  13203. }
  13204. } else {
  13205. const absDet = Math.abs(a * d - b * c);
  13206. const normX = Math.hypot(a, b);
  13207. const normY = Math.hypot(c, d);
  13208. if (lineWidth === 0) {
  13209. scaleX = normY / absDet;
  13210. scaleY = normX / absDet;
  13211. } else {
  13212. const baseArea = lineWidth * absDet;
  13213. scaleX = normY > baseArea ? normY / baseArea : 1;
  13214. scaleY = normX > baseArea ? normX / baseArea : 1;
  13215. }
  13216. }
  13217. this._cachedScaleForStroking[0] = scaleX;
  13218. this._cachedScaleForStroking[1] = scaleY;
  13219. }
  13220. return this._cachedScaleForStroking;
  13221. }
  13222. rescaleAndStroke(path, saveRestore) {
  13223. const {
  13224. ctx,
  13225. current: {
  13226. lineWidth
  13227. }
  13228. } = this;
  13229. const [scaleX, scaleY] = this.getScaleForStroking();
  13230. if (scaleX === scaleY) {
  13231. ctx.lineWidth = (lineWidth || 1) * scaleX;
  13232. ctx.stroke(path);
  13233. return;
  13234. }
  13235. const dashes = ctx.getLineDash();
  13236. if (saveRestore) {
  13237. ctx.save();
  13238. }
  13239. ctx.scale(scaleX, scaleY);
  13240. SCALE_MATRIX.a = 1 / scaleX;
  13241. SCALE_MATRIX.d = 1 / scaleY;
  13242. const newPath = new Path2D();
  13243. newPath.addPath(path, SCALE_MATRIX);
  13244. if (dashes.length > 0) {
  13245. const scale = Math.max(scaleX, scaleY);
  13246. ctx.setLineDash(dashes.map(x => x / scale));
  13247. ctx.lineDashOffset /= scale;
  13248. }
  13249. ctx.lineWidth = lineWidth || 1;
  13250. ctx.stroke(newPath);
  13251. if (saveRestore) {
  13252. ctx.restore();
  13253. }
  13254. }
  13255. isContentVisible() {
  13256. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  13257. if (!this.markedContentStack[i].visible) {
  13258. return false;
  13259. }
  13260. }
  13261. return true;
  13262. }
  13263. }
  13264. for (const op in OPS) {
  13265. if (CanvasGraphics.prototype[op] !== undefined) {
  13266. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  13267. }
  13268. }
  13269. ;// ./src/display/worker_options.js
  13270. class GlobalWorkerOptions {
  13271. static #port = null;
  13272. static #src = "";
  13273. static get workerPort() {
  13274. return this.#port;
  13275. }
  13276. static set workerPort(val) {
  13277. if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) {
  13278. throw new Error("Invalid `workerPort` type.");
  13279. }
  13280. this.#port = val;
  13281. }
  13282. static get workerSrc() {
  13283. return this.#src;
  13284. }
  13285. static set workerSrc(val) {
  13286. if (typeof val !== "string") {
  13287. throw new Error("Invalid `workerSrc` type.");
  13288. }
  13289. this.#src = val;
  13290. }
  13291. }
  13292. ;// ./src/display/metadata.js
  13293. class Metadata {
  13294. #map;
  13295. #data;
  13296. constructor({
  13297. parsedData,
  13298. rawData
  13299. }) {
  13300. this.#map = parsedData;
  13301. this.#data = rawData;
  13302. }
  13303. getRaw() {
  13304. return this.#data;
  13305. }
  13306. get(name) {
  13307. return this.#map.get(name) ?? null;
  13308. }
  13309. [Symbol.iterator]() {
  13310. return this.#map.entries();
  13311. }
  13312. }
  13313. ;// ./src/display/optional_content_config.js
  13314. const INTERNAL = Symbol("INTERNAL");
  13315. class OptionalContentGroup {
  13316. #isDisplay = false;
  13317. #isPrint = false;
  13318. #userSet = false;
  13319. #visible = true;
  13320. constructor(renderingIntent, {
  13321. name,
  13322. intent,
  13323. usage,
  13324. rbGroups
  13325. }) {
  13326. this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
  13327. this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  13328. this.name = name;
  13329. this.intent = intent;
  13330. this.usage = usage;
  13331. this.rbGroups = rbGroups;
  13332. }
  13333. get visible() {
  13334. if (this.#userSet) {
  13335. return this.#visible;
  13336. }
  13337. if (!this.#visible) {
  13338. return false;
  13339. }
  13340. const {
  13341. print,
  13342. view
  13343. } = this.usage;
  13344. if (this.#isDisplay) {
  13345. return view?.viewState !== "OFF";
  13346. } else if (this.#isPrint) {
  13347. return print?.printState !== "OFF";
  13348. }
  13349. return true;
  13350. }
  13351. _setVisible(internal, visible, userSet = false) {
  13352. if (internal !== INTERNAL) {
  13353. unreachable("Internal method `_setVisible` called.");
  13354. }
  13355. this.#userSet = userSet;
  13356. this.#visible = visible;
  13357. }
  13358. }
  13359. class OptionalContentConfig {
  13360. #cachedGetHash = null;
  13361. #groups = new Map();
  13362. #initialHash = null;
  13363. #order = null;
  13364. constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
  13365. this.renderingIntent = renderingIntent;
  13366. this.name = null;
  13367. this.creator = null;
  13368. if (data === null) {
  13369. return;
  13370. }
  13371. this.name = data.name;
  13372. this.creator = data.creator;
  13373. this.#order = data.order;
  13374. for (const group of data.groups) {
  13375. this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
  13376. }
  13377. if (data.baseState === "OFF") {
  13378. for (const group of this.#groups.values()) {
  13379. group._setVisible(INTERNAL, false);
  13380. }
  13381. }
  13382. for (const on of data.on) {
  13383. this.#groups.get(on)._setVisible(INTERNAL, true);
  13384. }
  13385. for (const off of data.off) {
  13386. this.#groups.get(off)._setVisible(INTERNAL, false);
  13387. }
  13388. this.#initialHash = this.getHash();
  13389. }
  13390. #evaluateVisibilityExpression(array) {
  13391. const length = array.length;
  13392. if (length < 2) {
  13393. return true;
  13394. }
  13395. const operator = array[0];
  13396. for (let i = 1; i < length; i++) {
  13397. const element = array[i];
  13398. let state;
  13399. if (Array.isArray(element)) {
  13400. state = this.#evaluateVisibilityExpression(element);
  13401. } else if (this.#groups.has(element)) {
  13402. state = this.#groups.get(element).visible;
  13403. } else {
  13404. warn(`Optional content group not found: ${element}`);
  13405. return true;
  13406. }
  13407. switch (operator) {
  13408. case "And":
  13409. if (!state) {
  13410. return false;
  13411. }
  13412. break;
  13413. case "Or":
  13414. if (state) {
  13415. return true;
  13416. }
  13417. break;
  13418. case "Not":
  13419. return !state;
  13420. default:
  13421. return true;
  13422. }
  13423. }
  13424. return operator === "And";
  13425. }
  13426. isVisible(group) {
  13427. if (this.#groups.size === 0) {
  13428. return true;
  13429. }
  13430. if (!group) {
  13431. info("Optional content group not defined.");
  13432. return true;
  13433. }
  13434. if (group.type === "OCG") {
  13435. if (!this.#groups.has(group.id)) {
  13436. warn(`Optional content group not found: ${group.id}`);
  13437. return true;
  13438. }
  13439. return this.#groups.get(group.id).visible;
  13440. } else if (group.type === "OCMD") {
  13441. if (group.expression) {
  13442. return this.#evaluateVisibilityExpression(group.expression);
  13443. }
  13444. if (!group.policy || group.policy === "AnyOn") {
  13445. for (const id of group.ids) {
  13446. if (!this.#groups.has(id)) {
  13447. warn(`Optional content group not found: ${id}`);
  13448. return true;
  13449. }
  13450. if (this.#groups.get(id).visible) {
  13451. return true;
  13452. }
  13453. }
  13454. return false;
  13455. } else if (group.policy === "AllOn") {
  13456. for (const id of group.ids) {
  13457. if (!this.#groups.has(id)) {
  13458. warn(`Optional content group not found: ${id}`);
  13459. return true;
  13460. }
  13461. if (!this.#groups.get(id).visible) {
  13462. return false;
  13463. }
  13464. }
  13465. return true;
  13466. } else if (group.policy === "AnyOff") {
  13467. for (const id of group.ids) {
  13468. if (!this.#groups.has(id)) {
  13469. warn(`Optional content group not found: ${id}`);
  13470. return true;
  13471. }
  13472. if (!this.#groups.get(id).visible) {
  13473. return true;
  13474. }
  13475. }
  13476. return false;
  13477. } else if (group.policy === "AllOff") {
  13478. for (const id of group.ids) {
  13479. if (!this.#groups.has(id)) {
  13480. warn(`Optional content group not found: ${id}`);
  13481. return true;
  13482. }
  13483. if (this.#groups.get(id).visible) {
  13484. return false;
  13485. }
  13486. }
  13487. return true;
  13488. }
  13489. warn(`Unknown optional content policy ${group.policy}.`);
  13490. return true;
  13491. }
  13492. warn(`Unknown group type ${group.type}.`);
  13493. return true;
  13494. }
  13495. setVisibility(id, visible = true, preserveRB = true) {
  13496. const group = this.#groups.get(id);
  13497. if (!group) {
  13498. warn(`Optional content group not found: ${id}`);
  13499. return;
  13500. }
  13501. if (preserveRB && visible && group.rbGroups.length) {
  13502. for (const rbGroup of group.rbGroups) {
  13503. for (const otherId of rbGroup) {
  13504. if (otherId !== id) {
  13505. this.#groups.get(otherId)?._setVisible(INTERNAL, false, true);
  13506. }
  13507. }
  13508. }
  13509. }
  13510. group._setVisible(INTERNAL, !!visible, true);
  13511. this.#cachedGetHash = null;
  13512. }
  13513. setOCGState({
  13514. state,
  13515. preserveRB
  13516. }) {
  13517. let operator;
  13518. for (const elem of state) {
  13519. switch (elem) {
  13520. case "ON":
  13521. case "OFF":
  13522. case "Toggle":
  13523. operator = elem;
  13524. continue;
  13525. }
  13526. const group = this.#groups.get(elem);
  13527. if (!group) {
  13528. continue;
  13529. }
  13530. switch (operator) {
  13531. case "ON":
  13532. this.setVisibility(elem, true, preserveRB);
  13533. break;
  13534. case "OFF":
  13535. this.setVisibility(elem, false, preserveRB);
  13536. break;
  13537. case "Toggle":
  13538. this.setVisibility(elem, !group.visible, preserveRB);
  13539. break;
  13540. }
  13541. }
  13542. this.#cachedGetHash = null;
  13543. }
  13544. get hasInitialVisibility() {
  13545. return this.#initialHash === null || this.getHash() === this.#initialHash;
  13546. }
  13547. getOrder() {
  13548. if (!this.#groups.size) {
  13549. return null;
  13550. }
  13551. if (this.#order) {
  13552. return this.#order.slice();
  13553. }
  13554. return [...this.#groups.keys()];
  13555. }
  13556. getGroup(id) {
  13557. return this.#groups.get(id) || null;
  13558. }
  13559. getHash() {
  13560. if (this.#cachedGetHash !== null) {
  13561. return this.#cachedGetHash;
  13562. }
  13563. const hash = new MurmurHash3_64();
  13564. for (const [id, group] of this.#groups) {
  13565. hash.update(`${id}:${group.visible}`);
  13566. }
  13567. return this.#cachedGetHash = hash.hexdigest();
  13568. }
  13569. [Symbol.iterator]() {
  13570. return this.#groups.entries();
  13571. }
  13572. }
  13573. ;// ./src/display/transport_stream.js
  13574. class PDFDataTransportStream {
  13575. constructor(pdfDataRangeTransport, {
  13576. disableRange = false,
  13577. disableStream = false
  13578. }) {
  13579. assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  13580. const {
  13581. length,
  13582. initialData,
  13583. progressiveDone,
  13584. contentDispositionFilename
  13585. } = pdfDataRangeTransport;
  13586. this._queuedChunks = [];
  13587. this._progressiveDone = progressiveDone;
  13588. this._contentDispositionFilename = contentDispositionFilename;
  13589. if (initialData?.length > 0) {
  13590. const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
  13591. this._queuedChunks.push(buffer);
  13592. }
  13593. this._pdfDataRangeTransport = pdfDataRangeTransport;
  13594. this._isStreamingSupported = !disableStream;
  13595. this._isRangeSupported = !disableRange;
  13596. this._contentLength = length;
  13597. this._fullRequestReader = null;
  13598. this._rangeReaders = [];
  13599. pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  13600. this._onReceiveData({
  13601. begin,
  13602. chunk
  13603. });
  13604. });
  13605. pdfDataRangeTransport.addProgressListener((loaded, total) => {
  13606. this._onProgress({
  13607. loaded,
  13608. total
  13609. });
  13610. });
  13611. pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  13612. this._onReceiveData({
  13613. chunk
  13614. });
  13615. });
  13616. pdfDataRangeTransport.addProgressiveDoneListener(() => {
  13617. this._onProgressiveDone();
  13618. });
  13619. pdfDataRangeTransport.transportReady();
  13620. }
  13621. _onReceiveData({
  13622. begin,
  13623. chunk
  13624. }) {
  13625. const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
  13626. if (begin === undefined) {
  13627. if (this._fullRequestReader) {
  13628. this._fullRequestReader._enqueue(buffer);
  13629. } else {
  13630. this._queuedChunks.push(buffer);
  13631. }
  13632. } else {
  13633. const found = this._rangeReaders.some(function (rangeReader) {
  13634. if (rangeReader._begin !== begin) {
  13635. return false;
  13636. }
  13637. rangeReader._enqueue(buffer);
  13638. return true;
  13639. });
  13640. assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  13641. }
  13642. }
  13643. get _progressiveDataLength() {
  13644. return this._fullRequestReader?._loaded ?? 0;
  13645. }
  13646. _onProgress(evt) {
  13647. if (evt.total === undefined) {
  13648. this._rangeReaders[0]?.onProgress?.({
  13649. loaded: evt.loaded
  13650. });
  13651. } else {
  13652. this._fullRequestReader?.onProgress?.({
  13653. loaded: evt.loaded,
  13654. total: evt.total
  13655. });
  13656. }
  13657. }
  13658. _onProgressiveDone() {
  13659. this._fullRequestReader?.progressiveDone();
  13660. this._progressiveDone = true;
  13661. }
  13662. _removeRangeReader(reader) {
  13663. const i = this._rangeReaders.indexOf(reader);
  13664. if (i >= 0) {
  13665. this._rangeReaders.splice(i, 1);
  13666. }
  13667. }
  13668. getFullReader() {
  13669. assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  13670. const queuedChunks = this._queuedChunks;
  13671. this._queuedChunks = null;
  13672. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  13673. }
  13674. getRangeReader(begin, end) {
  13675. if (end <= this._progressiveDataLength) {
  13676. return null;
  13677. }
  13678. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  13679. this._pdfDataRangeTransport.requestDataRange(begin, end);
  13680. this._rangeReaders.push(reader);
  13681. return reader;
  13682. }
  13683. cancelAllRequests(reason) {
  13684. this._fullRequestReader?.cancel(reason);
  13685. for (const reader of this._rangeReaders.slice(0)) {
  13686. reader.cancel(reason);
  13687. }
  13688. this._pdfDataRangeTransport.abort();
  13689. }
  13690. }
  13691. class PDFDataTransportStreamReader {
  13692. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  13693. this._stream = stream;
  13694. this._done = progressiveDone || false;
  13695. this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
  13696. this._queuedChunks = queuedChunks || [];
  13697. this._loaded = 0;
  13698. for (const chunk of this._queuedChunks) {
  13699. this._loaded += chunk.byteLength;
  13700. }
  13701. this._requests = [];
  13702. this._headersReady = Promise.resolve();
  13703. stream._fullRequestReader = this;
  13704. this.onProgress = null;
  13705. }
  13706. _enqueue(chunk) {
  13707. if (this._done) {
  13708. return;
  13709. }
  13710. if (this._requests.length > 0) {
  13711. const requestCapability = this._requests.shift();
  13712. requestCapability.resolve({
  13713. value: chunk,
  13714. done: false
  13715. });
  13716. } else {
  13717. this._queuedChunks.push(chunk);
  13718. }
  13719. this._loaded += chunk.byteLength;
  13720. }
  13721. get headersReady() {
  13722. return this._headersReady;
  13723. }
  13724. get filename() {
  13725. return this._filename;
  13726. }
  13727. get isRangeSupported() {
  13728. return this._stream._isRangeSupported;
  13729. }
  13730. get isStreamingSupported() {
  13731. return this._stream._isStreamingSupported;
  13732. }
  13733. get contentLength() {
  13734. return this._stream._contentLength;
  13735. }
  13736. async read() {
  13737. if (this._queuedChunks.length > 0) {
  13738. const chunk = this._queuedChunks.shift();
  13739. return {
  13740. value: chunk,
  13741. done: false
  13742. };
  13743. }
  13744. if (this._done) {
  13745. return {
  13746. value: undefined,
  13747. done: true
  13748. };
  13749. }
  13750. const requestCapability = Promise.withResolvers();
  13751. this._requests.push(requestCapability);
  13752. return requestCapability.promise;
  13753. }
  13754. cancel(reason) {
  13755. this._done = true;
  13756. for (const requestCapability of this._requests) {
  13757. requestCapability.resolve({
  13758. value: undefined,
  13759. done: true
  13760. });
  13761. }
  13762. this._requests.length = 0;
  13763. }
  13764. progressiveDone() {
  13765. if (this._done) {
  13766. return;
  13767. }
  13768. this._done = true;
  13769. }
  13770. }
  13771. class PDFDataTransportStreamRangeReader {
  13772. constructor(stream, begin, end) {
  13773. this._stream = stream;
  13774. this._begin = begin;
  13775. this._end = end;
  13776. this._queuedChunk = null;
  13777. this._requests = [];
  13778. this._done = false;
  13779. this.onProgress = null;
  13780. }
  13781. _enqueue(chunk) {
  13782. if (this._done) {
  13783. return;
  13784. }
  13785. if (this._requests.length === 0) {
  13786. this._queuedChunk = chunk;
  13787. } else {
  13788. const requestsCapability = this._requests.shift();
  13789. requestsCapability.resolve({
  13790. value: chunk,
  13791. done: false
  13792. });
  13793. for (const requestCapability of this._requests) {
  13794. requestCapability.resolve({
  13795. value: undefined,
  13796. done: true
  13797. });
  13798. }
  13799. this._requests.length = 0;
  13800. }
  13801. this._done = true;
  13802. this._stream._removeRangeReader(this);
  13803. }
  13804. get isStreamingSupported() {
  13805. return false;
  13806. }
  13807. async read() {
  13808. if (this._queuedChunk) {
  13809. const chunk = this._queuedChunk;
  13810. this._queuedChunk = null;
  13811. return {
  13812. value: chunk,
  13813. done: false
  13814. };
  13815. }
  13816. if (this._done) {
  13817. return {
  13818. value: undefined,
  13819. done: true
  13820. };
  13821. }
  13822. const requestCapability = Promise.withResolvers();
  13823. this._requests.push(requestCapability);
  13824. return requestCapability.promise;
  13825. }
  13826. cancel(reason) {
  13827. this._done = true;
  13828. for (const requestCapability of this._requests) {
  13829. requestCapability.resolve({
  13830. value: undefined,
  13831. done: true
  13832. });
  13833. }
  13834. this._requests.length = 0;
  13835. this._stream._removeRangeReader(this);
  13836. }
  13837. }
  13838. ;// ./src/display/content_disposition.js
  13839. function getFilenameFromContentDispositionHeader(contentDisposition) {
  13840. let needsEncodingFixup = true;
  13841. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  13842. if (tmp) {
  13843. tmp = tmp[1];
  13844. let filename = rfc2616unquote(tmp);
  13845. filename = unescape(filename);
  13846. filename = rfc5987decode(filename);
  13847. filename = rfc2047decode(filename);
  13848. return fixupEncoding(filename);
  13849. }
  13850. tmp = rfc2231getparam(contentDisposition);
  13851. if (tmp) {
  13852. const filename = rfc2047decode(tmp);
  13853. return fixupEncoding(filename);
  13854. }
  13855. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  13856. if (tmp) {
  13857. tmp = tmp[1];
  13858. let filename = rfc2616unquote(tmp);
  13859. filename = rfc2047decode(filename);
  13860. return fixupEncoding(filename);
  13861. }
  13862. function toParamRegExp(attributePattern, flags) {
  13863. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  13864. }
  13865. function textdecode(encoding, value) {
  13866. if (encoding) {
  13867. if (!/^[\x00-\xFF]+$/.test(value)) {
  13868. return value;
  13869. }
  13870. try {
  13871. const decoder = new TextDecoder(encoding, {
  13872. fatal: true
  13873. });
  13874. const buffer = stringToBytes(value);
  13875. value = decoder.decode(buffer);
  13876. needsEncodingFixup = false;
  13877. } catch {}
  13878. }
  13879. return value;
  13880. }
  13881. function fixupEncoding(value) {
  13882. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  13883. value = textdecode("utf-8", value);
  13884. if (needsEncodingFixup) {
  13885. value = textdecode("iso-8859-1", value);
  13886. }
  13887. }
  13888. return value;
  13889. }
  13890. function rfc2231getparam(contentDispositionStr) {
  13891. const matches = [];
  13892. let match;
  13893. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  13894. while ((match = iter.exec(contentDispositionStr)) !== null) {
  13895. let [, n, quot, part] = match;
  13896. n = parseInt(n, 10);
  13897. if (n in matches) {
  13898. if (n === 0) {
  13899. break;
  13900. }
  13901. continue;
  13902. }
  13903. matches[n] = [quot, part];
  13904. }
  13905. const parts = [];
  13906. for (let n = 0; n < matches.length; ++n) {
  13907. if (!(n in matches)) {
  13908. break;
  13909. }
  13910. let [quot, part] = matches[n];
  13911. part = rfc2616unquote(part);
  13912. if (quot) {
  13913. part = unescape(part);
  13914. if (n === 0) {
  13915. part = rfc5987decode(part);
  13916. }
  13917. }
  13918. parts.push(part);
  13919. }
  13920. return parts.join("");
  13921. }
  13922. function rfc2616unquote(value) {
  13923. if (value.startsWith('"')) {
  13924. const parts = value.slice(1).split('\\"');
  13925. for (let i = 0; i < parts.length; ++i) {
  13926. const quotindex = parts[i].indexOf('"');
  13927. if (quotindex !== -1) {
  13928. parts[i] = parts[i].slice(0, quotindex);
  13929. parts.length = i + 1;
  13930. }
  13931. parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
  13932. }
  13933. value = parts.join('"');
  13934. }
  13935. return value;
  13936. }
  13937. function rfc5987decode(extvalue) {
  13938. const encodingend = extvalue.indexOf("'");
  13939. if (encodingend === -1) {
  13940. return extvalue;
  13941. }
  13942. const encoding = extvalue.slice(0, encodingend);
  13943. const langvalue = extvalue.slice(encodingend + 1);
  13944. const value = langvalue.replace(/^[^']*'/, "");
  13945. return textdecode(encoding, value);
  13946. }
  13947. function rfc2047decode(value) {
  13948. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  13949. return value;
  13950. }
  13951. return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  13952. if (encoding === "q" || encoding === "Q") {
  13953. text = text.replaceAll("_", " ");
  13954. text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  13955. return String.fromCharCode(parseInt(hex, 16));
  13956. });
  13957. return textdecode(charset, text);
  13958. }
  13959. try {
  13960. text = atob(text);
  13961. } catch {}
  13962. return textdecode(charset, text);
  13963. });
  13964. }
  13965. return "";
  13966. }
  13967. ;// ./src/display/network_utils.js
  13968. function createHeaders(isHttp, httpHeaders) {
  13969. const headers = new Headers();
  13970. if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {
  13971. return headers;
  13972. }
  13973. for (const key in httpHeaders) {
  13974. const val = httpHeaders[key];
  13975. if (val !== undefined) {
  13976. headers.append(key, val);
  13977. }
  13978. }
  13979. return headers;
  13980. }
  13981. function getResponseOrigin(url) {
  13982. return URL.parse(url)?.origin ?? null;
  13983. }
  13984. function validateRangeRequestCapabilities({
  13985. responseHeaders,
  13986. isHttp,
  13987. rangeChunkSize,
  13988. disableRange
  13989. }) {
  13990. const returnValues = {
  13991. allowRangeRequests: false,
  13992. suggestedLength: undefined
  13993. };
  13994. const length = parseInt(responseHeaders.get("Content-Length"), 10);
  13995. if (!Number.isInteger(length)) {
  13996. return returnValues;
  13997. }
  13998. returnValues.suggestedLength = length;
  13999. if (length <= 2 * rangeChunkSize) {
  14000. return returnValues;
  14001. }
  14002. if (disableRange || !isHttp) {
  14003. return returnValues;
  14004. }
  14005. if (responseHeaders.get("Accept-Ranges") !== "bytes") {
  14006. return returnValues;
  14007. }
  14008. const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";
  14009. if (contentEncoding !== "identity") {
  14010. return returnValues;
  14011. }
  14012. returnValues.allowRangeRequests = true;
  14013. return returnValues;
  14014. }
  14015. function extractFilenameFromHeader(responseHeaders) {
  14016. const contentDisposition = responseHeaders.get("Content-Disposition");
  14017. if (contentDisposition) {
  14018. let filename = getFilenameFromContentDispositionHeader(contentDisposition);
  14019. if (filename.includes("%")) {
  14020. try {
  14021. filename = decodeURIComponent(filename);
  14022. } catch {}
  14023. }
  14024. if (isPdfFile(filename)) {
  14025. return filename;
  14026. }
  14027. }
  14028. return null;
  14029. }
  14030. function createResponseError(status, url) {
  14031. return new ResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status, status === 404 || status === 0 && url.startsWith("file:"));
  14032. }
  14033. function validateResponseStatus(status) {
  14034. return status === 200 || status === 206;
  14035. }
  14036. ;// ./src/display/fetch_stream.js
  14037. function createFetchOptions(headers, withCredentials, abortController) {
  14038. return {
  14039. method: "GET",
  14040. headers,
  14041. signal: abortController.signal,
  14042. mode: "cors",
  14043. credentials: withCredentials ? "include" : "same-origin",
  14044. redirect: "follow"
  14045. };
  14046. }
  14047. function getArrayBuffer(val) {
  14048. if (val instanceof Uint8Array) {
  14049. return val.buffer;
  14050. }
  14051. if (val instanceof ArrayBuffer) {
  14052. return val;
  14053. }
  14054. warn(`getArrayBuffer - unexpected data format: ${val}`);
  14055. return new Uint8Array(val).buffer;
  14056. }
  14057. class PDFFetchStream {
  14058. _responseOrigin = null;
  14059. constructor(source) {
  14060. this.source = source;
  14061. this.isHttp = /^https?:/i.test(source.url);
  14062. this.headers = createHeaders(this.isHttp, source.httpHeaders);
  14063. this._fullRequestReader = null;
  14064. this._rangeRequestReaders = [];
  14065. }
  14066. get _progressiveDataLength() {
  14067. return this._fullRequestReader?._loaded ?? 0;
  14068. }
  14069. getFullReader() {
  14070. assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  14071. this._fullRequestReader = new PDFFetchStreamReader(this);
  14072. return this._fullRequestReader;
  14073. }
  14074. getRangeReader(begin, end) {
  14075. if (end <= this._progressiveDataLength) {
  14076. return null;
  14077. }
  14078. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  14079. this._rangeRequestReaders.push(reader);
  14080. return reader;
  14081. }
  14082. cancelAllRequests(reason) {
  14083. this._fullRequestReader?.cancel(reason);
  14084. for (const reader of this._rangeRequestReaders.slice(0)) {
  14085. reader.cancel(reason);
  14086. }
  14087. }
  14088. }
  14089. class PDFFetchStreamReader {
  14090. constructor(stream) {
  14091. this._stream = stream;
  14092. this._reader = null;
  14093. this._loaded = 0;
  14094. this._filename = null;
  14095. const source = stream.source;
  14096. this._withCredentials = source.withCredentials || false;
  14097. this._contentLength = source.length;
  14098. this._headersCapability = Promise.withResolvers();
  14099. this._disableRange = source.disableRange || false;
  14100. this._rangeChunkSize = source.rangeChunkSize;
  14101. if (!this._rangeChunkSize && !this._disableRange) {
  14102. this._disableRange = true;
  14103. }
  14104. this._abortController = new AbortController();
  14105. this._isStreamingSupported = !source.disableStream;
  14106. this._isRangeSupported = !source.disableRange;
  14107. const headers = new Headers(stream.headers);
  14108. const url = source.url;
  14109. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  14110. stream._responseOrigin = getResponseOrigin(response.url);
  14111. if (!validateResponseStatus(response.status)) {
  14112. throw createResponseError(response.status, url);
  14113. }
  14114. this._reader = response.body.getReader();
  14115. this._headersCapability.resolve();
  14116. const responseHeaders = response.headers;
  14117. const {
  14118. allowRangeRequests,
  14119. suggestedLength
  14120. } = validateRangeRequestCapabilities({
  14121. responseHeaders,
  14122. isHttp: stream.isHttp,
  14123. rangeChunkSize: this._rangeChunkSize,
  14124. disableRange: this._disableRange
  14125. });
  14126. this._isRangeSupported = allowRangeRequests;
  14127. this._contentLength = suggestedLength || this._contentLength;
  14128. this._filename = extractFilenameFromHeader(responseHeaders);
  14129. if (!this._isStreamingSupported && this._isRangeSupported) {
  14130. this.cancel(new AbortException("Streaming is disabled."));
  14131. }
  14132. }).catch(this._headersCapability.reject);
  14133. this.onProgress = null;
  14134. }
  14135. get headersReady() {
  14136. return this._headersCapability.promise;
  14137. }
  14138. get filename() {
  14139. return this._filename;
  14140. }
  14141. get contentLength() {
  14142. return this._contentLength;
  14143. }
  14144. get isRangeSupported() {
  14145. return this._isRangeSupported;
  14146. }
  14147. get isStreamingSupported() {
  14148. return this._isStreamingSupported;
  14149. }
  14150. async read() {
  14151. await this._headersCapability.promise;
  14152. const {
  14153. value,
  14154. done
  14155. } = await this._reader.read();
  14156. if (done) {
  14157. return {
  14158. value,
  14159. done
  14160. };
  14161. }
  14162. this._loaded += value.byteLength;
  14163. this.onProgress?.({
  14164. loaded: this._loaded,
  14165. total: this._contentLength
  14166. });
  14167. return {
  14168. value: getArrayBuffer(value),
  14169. done: false
  14170. };
  14171. }
  14172. cancel(reason) {
  14173. this._reader?.cancel(reason);
  14174. this._abortController.abort();
  14175. }
  14176. }
  14177. class PDFFetchStreamRangeReader {
  14178. constructor(stream, begin, end) {
  14179. this._stream = stream;
  14180. this._reader = null;
  14181. this._loaded = 0;
  14182. const source = stream.source;
  14183. this._withCredentials = source.withCredentials || false;
  14184. this._readCapability = Promise.withResolvers();
  14185. this._isStreamingSupported = !source.disableStream;
  14186. this._abortController = new AbortController();
  14187. const headers = new Headers(stream.headers);
  14188. headers.append("Range", `bytes=${begin}-${end - 1}`);
  14189. const url = source.url;
  14190. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  14191. const responseOrigin = getResponseOrigin(response.url);
  14192. if (responseOrigin !== stream._responseOrigin) {
  14193. throw new Error(`Expected range response-origin "${responseOrigin}" to match "${stream._responseOrigin}".`);
  14194. }
  14195. if (!validateResponseStatus(response.status)) {
  14196. throw createResponseError(response.status, url);
  14197. }
  14198. this._readCapability.resolve();
  14199. this._reader = response.body.getReader();
  14200. }).catch(this._readCapability.reject);
  14201. this.onProgress = null;
  14202. }
  14203. get isStreamingSupported() {
  14204. return this._isStreamingSupported;
  14205. }
  14206. async read() {
  14207. await this._readCapability.promise;
  14208. const {
  14209. value,
  14210. done
  14211. } = await this._reader.read();
  14212. if (done) {
  14213. return {
  14214. value,
  14215. done
  14216. };
  14217. }
  14218. this._loaded += value.byteLength;
  14219. this.onProgress?.({
  14220. loaded: this._loaded
  14221. });
  14222. return {
  14223. value: getArrayBuffer(value),
  14224. done: false
  14225. };
  14226. }
  14227. cancel(reason) {
  14228. this._reader?.cancel(reason);
  14229. this._abortController.abort();
  14230. }
  14231. }
  14232. ;// ./src/display/network.js
  14233. const OK_RESPONSE = 200;
  14234. const PARTIAL_CONTENT_RESPONSE = 206;
  14235. function network_getArrayBuffer(xhr) {
  14236. const data = xhr.response;
  14237. if (typeof data !== "string") {
  14238. return data;
  14239. }
  14240. return stringToBytes(data).buffer;
  14241. }
  14242. class NetworkManager {
  14243. _responseOrigin = null;
  14244. constructor({
  14245. url,
  14246. httpHeaders,
  14247. withCredentials
  14248. }) {
  14249. this.url = url;
  14250. this.isHttp = /^https?:/i.test(url);
  14251. this.headers = createHeaders(this.isHttp, httpHeaders);
  14252. this.withCredentials = withCredentials || false;
  14253. this.currXhrId = 0;
  14254. this.pendingRequests = Object.create(null);
  14255. }
  14256. request(args) {
  14257. const xhr = new XMLHttpRequest();
  14258. const xhrId = this.currXhrId++;
  14259. const pendingRequest = this.pendingRequests[xhrId] = {
  14260. xhr
  14261. };
  14262. xhr.open("GET", this.url);
  14263. xhr.withCredentials = this.withCredentials;
  14264. for (const [key, val] of this.headers) {
  14265. xhr.setRequestHeader(key, val);
  14266. }
  14267. if (this.isHttp && "begin" in args && "end" in args) {
  14268. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  14269. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  14270. } else {
  14271. pendingRequest.expectedStatus = OK_RESPONSE;
  14272. }
  14273. xhr.responseType = "arraybuffer";
  14274. assert(args.onError, "Expected `onError` callback to be provided.");
  14275. xhr.onerror = () => {
  14276. args.onError(xhr.status);
  14277. };
  14278. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  14279. xhr.onprogress = this.onProgress.bind(this, xhrId);
  14280. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  14281. pendingRequest.onDone = args.onDone;
  14282. pendingRequest.onError = args.onError;
  14283. pendingRequest.onProgress = args.onProgress;
  14284. xhr.send(null);
  14285. return xhrId;
  14286. }
  14287. onProgress(xhrId, evt) {
  14288. const pendingRequest = this.pendingRequests[xhrId];
  14289. if (!pendingRequest) {
  14290. return;
  14291. }
  14292. pendingRequest.onProgress?.(evt);
  14293. }
  14294. onStateChange(xhrId, evt) {
  14295. const pendingRequest = this.pendingRequests[xhrId];
  14296. if (!pendingRequest) {
  14297. return;
  14298. }
  14299. const xhr = pendingRequest.xhr;
  14300. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  14301. pendingRequest.onHeadersReceived();
  14302. delete pendingRequest.onHeadersReceived;
  14303. }
  14304. if (xhr.readyState !== 4) {
  14305. return;
  14306. }
  14307. if (!(xhrId in this.pendingRequests)) {
  14308. return;
  14309. }
  14310. delete this.pendingRequests[xhrId];
  14311. if (xhr.status === 0 && this.isHttp) {
  14312. pendingRequest.onError(xhr.status);
  14313. return;
  14314. }
  14315. const xhrStatus = xhr.status || OK_RESPONSE;
  14316. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  14317. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  14318. pendingRequest.onError(xhr.status);
  14319. return;
  14320. }
  14321. const chunk = network_getArrayBuffer(xhr);
  14322. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  14323. const rangeHeader = xhr.getResponseHeader("Content-Range");
  14324. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  14325. if (matches) {
  14326. pendingRequest.onDone({
  14327. begin: parseInt(matches[1], 10),
  14328. chunk
  14329. });
  14330. } else {
  14331. warn(`Missing or invalid "Content-Range" header.`);
  14332. pendingRequest.onError(0);
  14333. }
  14334. } else if (chunk) {
  14335. pendingRequest.onDone({
  14336. begin: 0,
  14337. chunk
  14338. });
  14339. } else {
  14340. pendingRequest.onError(xhr.status);
  14341. }
  14342. }
  14343. getRequestXhr(xhrId) {
  14344. return this.pendingRequests[xhrId].xhr;
  14345. }
  14346. isPendingRequest(xhrId) {
  14347. return xhrId in this.pendingRequests;
  14348. }
  14349. abortRequest(xhrId) {
  14350. const xhr = this.pendingRequests[xhrId].xhr;
  14351. delete this.pendingRequests[xhrId];
  14352. xhr.abort();
  14353. }
  14354. }
  14355. class PDFNetworkStream {
  14356. constructor(source) {
  14357. this._source = source;
  14358. this._manager = new NetworkManager(source);
  14359. this._rangeChunkSize = source.rangeChunkSize;
  14360. this._fullRequestReader = null;
  14361. this._rangeRequestReaders = [];
  14362. }
  14363. _onRangeRequestReaderClosed(reader) {
  14364. const i = this._rangeRequestReaders.indexOf(reader);
  14365. if (i >= 0) {
  14366. this._rangeRequestReaders.splice(i, 1);
  14367. }
  14368. }
  14369. getFullReader() {
  14370. assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  14371. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  14372. return this._fullRequestReader;
  14373. }
  14374. getRangeReader(begin, end) {
  14375. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  14376. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  14377. this._rangeRequestReaders.push(reader);
  14378. return reader;
  14379. }
  14380. cancelAllRequests(reason) {
  14381. this._fullRequestReader?.cancel(reason);
  14382. for (const reader of this._rangeRequestReaders.slice(0)) {
  14383. reader.cancel(reason);
  14384. }
  14385. }
  14386. }
  14387. class PDFNetworkStreamFullRequestReader {
  14388. constructor(manager, source) {
  14389. this._manager = manager;
  14390. this._url = source.url;
  14391. this._fullRequestId = manager.request({
  14392. onHeadersReceived: this._onHeadersReceived.bind(this),
  14393. onDone: this._onDone.bind(this),
  14394. onError: this._onError.bind(this),
  14395. onProgress: this._onProgress.bind(this)
  14396. });
  14397. this._headersCapability = Promise.withResolvers();
  14398. this._disableRange = source.disableRange || false;
  14399. this._contentLength = source.length;
  14400. this._rangeChunkSize = source.rangeChunkSize;
  14401. if (!this._rangeChunkSize && !this._disableRange) {
  14402. this._disableRange = true;
  14403. }
  14404. this._isStreamingSupported = false;
  14405. this._isRangeSupported = false;
  14406. this._cachedChunks = [];
  14407. this._requests = [];
  14408. this._done = false;
  14409. this._storedError = undefined;
  14410. this._filename = null;
  14411. this.onProgress = null;
  14412. }
  14413. _onHeadersReceived() {
  14414. const fullRequestXhrId = this._fullRequestId;
  14415. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  14416. this._manager._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL);
  14417. const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders();
  14418. const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\S ]+$/, "").split(/[\r\n]+/).map(x => {
  14419. const [key, ...val] = x.split(": ");
  14420. return [key, val.join(": ")];
  14421. }) : []);
  14422. const {
  14423. allowRangeRequests,
  14424. suggestedLength
  14425. } = validateRangeRequestCapabilities({
  14426. responseHeaders,
  14427. isHttp: this._manager.isHttp,
  14428. rangeChunkSize: this._rangeChunkSize,
  14429. disableRange: this._disableRange
  14430. });
  14431. if (allowRangeRequests) {
  14432. this._isRangeSupported = true;
  14433. }
  14434. this._contentLength = suggestedLength || this._contentLength;
  14435. this._filename = extractFilenameFromHeader(responseHeaders);
  14436. if (this._isRangeSupported) {
  14437. this._manager.abortRequest(fullRequestXhrId);
  14438. }
  14439. this._headersCapability.resolve();
  14440. }
  14441. _onDone(data) {
  14442. if (data) {
  14443. if (this._requests.length > 0) {
  14444. const requestCapability = this._requests.shift();
  14445. requestCapability.resolve({
  14446. value: data.chunk,
  14447. done: false
  14448. });
  14449. } else {
  14450. this._cachedChunks.push(data.chunk);
  14451. }
  14452. }
  14453. this._done = true;
  14454. if (this._cachedChunks.length > 0) {
  14455. return;
  14456. }
  14457. for (const requestCapability of this._requests) {
  14458. requestCapability.resolve({
  14459. value: undefined,
  14460. done: true
  14461. });
  14462. }
  14463. this._requests.length = 0;
  14464. }
  14465. _onError(status) {
  14466. this._storedError = createResponseError(status, this._url);
  14467. this._headersCapability.reject(this._storedError);
  14468. for (const requestCapability of this._requests) {
  14469. requestCapability.reject(this._storedError);
  14470. }
  14471. this._requests.length = 0;
  14472. this._cachedChunks.length = 0;
  14473. }
  14474. _onProgress(evt) {
  14475. this.onProgress?.({
  14476. loaded: evt.loaded,
  14477. total: evt.lengthComputable ? evt.total : this._contentLength
  14478. });
  14479. }
  14480. get filename() {
  14481. return this._filename;
  14482. }
  14483. get isRangeSupported() {
  14484. return this._isRangeSupported;
  14485. }
  14486. get isStreamingSupported() {
  14487. return this._isStreamingSupported;
  14488. }
  14489. get contentLength() {
  14490. return this._contentLength;
  14491. }
  14492. get headersReady() {
  14493. return this._headersCapability.promise;
  14494. }
  14495. async read() {
  14496. await this._headersCapability.promise;
  14497. if (this._storedError) {
  14498. throw this._storedError;
  14499. }
  14500. if (this._cachedChunks.length > 0) {
  14501. const chunk = this._cachedChunks.shift();
  14502. return {
  14503. value: chunk,
  14504. done: false
  14505. };
  14506. }
  14507. if (this._done) {
  14508. return {
  14509. value: undefined,
  14510. done: true
  14511. };
  14512. }
  14513. const requestCapability = Promise.withResolvers();
  14514. this._requests.push(requestCapability);
  14515. return requestCapability.promise;
  14516. }
  14517. cancel(reason) {
  14518. this._done = true;
  14519. this._headersCapability.reject(reason);
  14520. for (const requestCapability of this._requests) {
  14521. requestCapability.resolve({
  14522. value: undefined,
  14523. done: true
  14524. });
  14525. }
  14526. this._requests.length = 0;
  14527. if (this._manager.isPendingRequest(this._fullRequestId)) {
  14528. this._manager.abortRequest(this._fullRequestId);
  14529. }
  14530. this._fullRequestReader = null;
  14531. }
  14532. }
  14533. class PDFNetworkStreamRangeRequestReader {
  14534. constructor(manager, begin, end) {
  14535. this._manager = manager;
  14536. this._url = manager.url;
  14537. this._requestId = manager.request({
  14538. begin,
  14539. end,
  14540. onHeadersReceived: this._onHeadersReceived.bind(this),
  14541. onDone: this._onDone.bind(this),
  14542. onError: this._onError.bind(this),
  14543. onProgress: this._onProgress.bind(this)
  14544. });
  14545. this._requests = [];
  14546. this._queuedChunk = null;
  14547. this._done = false;
  14548. this._storedError = undefined;
  14549. this.onProgress = null;
  14550. this.onClosed = null;
  14551. }
  14552. _onHeadersReceived() {
  14553. const responseOrigin = getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);
  14554. if (responseOrigin !== this._manager._responseOrigin) {
  14555. this._storedError = new Error(`Expected range response-origin "${responseOrigin}" to match "${this._manager._responseOrigin}".`);
  14556. this._onError(0);
  14557. }
  14558. }
  14559. _close() {
  14560. this.onClosed?.(this);
  14561. }
  14562. _onDone(data) {
  14563. const chunk = data.chunk;
  14564. if (this._requests.length > 0) {
  14565. const requestCapability = this._requests.shift();
  14566. requestCapability.resolve({
  14567. value: chunk,
  14568. done: false
  14569. });
  14570. } else {
  14571. this._queuedChunk = chunk;
  14572. }
  14573. this._done = true;
  14574. for (const requestCapability of this._requests) {
  14575. requestCapability.resolve({
  14576. value: undefined,
  14577. done: true
  14578. });
  14579. }
  14580. this._requests.length = 0;
  14581. this._close();
  14582. }
  14583. _onError(status) {
  14584. this._storedError ??= createResponseError(status, this._url);
  14585. for (const requestCapability of this._requests) {
  14586. requestCapability.reject(this._storedError);
  14587. }
  14588. this._requests.length = 0;
  14589. this._queuedChunk = null;
  14590. }
  14591. _onProgress(evt) {
  14592. if (!this.isStreamingSupported) {
  14593. this.onProgress?.({
  14594. loaded: evt.loaded
  14595. });
  14596. }
  14597. }
  14598. get isStreamingSupported() {
  14599. return false;
  14600. }
  14601. async read() {
  14602. if (this._storedError) {
  14603. throw this._storedError;
  14604. }
  14605. if (this._queuedChunk !== null) {
  14606. const chunk = this._queuedChunk;
  14607. this._queuedChunk = null;
  14608. return {
  14609. value: chunk,
  14610. done: false
  14611. };
  14612. }
  14613. if (this._done) {
  14614. return {
  14615. value: undefined,
  14616. done: true
  14617. };
  14618. }
  14619. const requestCapability = Promise.withResolvers();
  14620. this._requests.push(requestCapability);
  14621. return requestCapability.promise;
  14622. }
  14623. cancel(reason) {
  14624. this._done = true;
  14625. for (const requestCapability of this._requests) {
  14626. requestCapability.resolve({
  14627. value: undefined,
  14628. done: true
  14629. });
  14630. }
  14631. this._requests.length = 0;
  14632. if (this._manager.isPendingRequest(this._requestId)) {
  14633. this._manager.abortRequest(this._requestId);
  14634. }
  14635. this._close();
  14636. }
  14637. }
  14638. ;// ./src/display/node_stream.js
  14639. const urlRegex = /^[a-z][a-z0-9\-+.]+:/i;
  14640. function parseUrlOrPath(sourceUrl) {
  14641. if (urlRegex.test(sourceUrl)) {
  14642. return new URL(sourceUrl);
  14643. }
  14644. const url = process.getBuiltinModule("url");
  14645. return new URL(url.pathToFileURL(sourceUrl));
  14646. }
  14647. class PDFNodeStream {
  14648. constructor(source) {
  14649. this.source = source;
  14650. this.url = parseUrlOrPath(source.url);
  14651. assert(this.url.protocol === "file:", "PDFNodeStream only supports file:// URLs.");
  14652. this._fullRequestReader = null;
  14653. this._rangeRequestReaders = [];
  14654. }
  14655. get _progressiveDataLength() {
  14656. return this._fullRequestReader?._loaded ?? 0;
  14657. }
  14658. getFullReader() {
  14659. assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  14660. this._fullRequestReader = new PDFNodeStreamFsFullReader(this);
  14661. return this._fullRequestReader;
  14662. }
  14663. getRangeReader(start, end) {
  14664. if (end <= this._progressiveDataLength) {
  14665. return null;
  14666. }
  14667. const rangeReader = new PDFNodeStreamFsRangeReader(this, start, end);
  14668. this._rangeRequestReaders.push(rangeReader);
  14669. return rangeReader;
  14670. }
  14671. cancelAllRequests(reason) {
  14672. this._fullRequestReader?.cancel(reason);
  14673. for (const reader of this._rangeRequestReaders.slice(0)) {
  14674. reader.cancel(reason);
  14675. }
  14676. }
  14677. }
  14678. class PDFNodeStreamFsFullReader {
  14679. constructor(stream) {
  14680. this._url = stream.url;
  14681. this._done = false;
  14682. this._storedError = null;
  14683. this.onProgress = null;
  14684. const source = stream.source;
  14685. this._contentLength = source.length;
  14686. this._loaded = 0;
  14687. this._filename = null;
  14688. this._disableRange = source.disableRange || false;
  14689. this._rangeChunkSize = source.rangeChunkSize;
  14690. if (!this._rangeChunkSize && !this._disableRange) {
  14691. this._disableRange = true;
  14692. }
  14693. this._isStreamingSupported = !source.disableStream;
  14694. this._isRangeSupported = !source.disableRange;
  14695. this._readableStream = null;
  14696. this._readCapability = Promise.withResolvers();
  14697. this._headersCapability = Promise.withResolvers();
  14698. const fs = process.getBuiltinModule("fs");
  14699. fs.promises.lstat(this._url).then(stat => {
  14700. this._contentLength = stat.size;
  14701. this._setReadableStream(fs.createReadStream(this._url));
  14702. this._headersCapability.resolve();
  14703. }, error => {
  14704. if (error.code === "ENOENT") {
  14705. error = createResponseError(0, this._url.href);
  14706. }
  14707. this._storedError = error;
  14708. this._headersCapability.reject(error);
  14709. });
  14710. }
  14711. get headersReady() {
  14712. return this._headersCapability.promise;
  14713. }
  14714. get filename() {
  14715. return this._filename;
  14716. }
  14717. get contentLength() {
  14718. return this._contentLength;
  14719. }
  14720. get isRangeSupported() {
  14721. return this._isRangeSupported;
  14722. }
  14723. get isStreamingSupported() {
  14724. return this._isStreamingSupported;
  14725. }
  14726. async read() {
  14727. await this._readCapability.promise;
  14728. if (this._done) {
  14729. return {
  14730. value: undefined,
  14731. done: true
  14732. };
  14733. }
  14734. if (this._storedError) {
  14735. throw this._storedError;
  14736. }
  14737. const chunk = this._readableStream.read();
  14738. if (chunk === null) {
  14739. this._readCapability = Promise.withResolvers();
  14740. return this.read();
  14741. }
  14742. this._loaded += chunk.length;
  14743. this.onProgress?.({
  14744. loaded: this._loaded,
  14745. total: this._contentLength
  14746. });
  14747. const buffer = new Uint8Array(chunk).buffer;
  14748. return {
  14749. value: buffer,
  14750. done: false
  14751. };
  14752. }
  14753. cancel(reason) {
  14754. if (!this._readableStream) {
  14755. this._error(reason);
  14756. return;
  14757. }
  14758. this._readableStream.destroy(reason);
  14759. }
  14760. _error(reason) {
  14761. this._storedError = reason;
  14762. this._readCapability.resolve();
  14763. }
  14764. _setReadableStream(readableStream) {
  14765. this._readableStream = readableStream;
  14766. readableStream.on("readable", () => {
  14767. this._readCapability.resolve();
  14768. });
  14769. readableStream.on("end", () => {
  14770. readableStream.destroy();
  14771. this._done = true;
  14772. this._readCapability.resolve();
  14773. });
  14774. readableStream.on("error", reason => {
  14775. this._error(reason);
  14776. });
  14777. if (!this._isStreamingSupported && this._isRangeSupported) {
  14778. this._error(new AbortException("streaming is disabled"));
  14779. }
  14780. if (this._storedError) {
  14781. this._readableStream.destroy(this._storedError);
  14782. }
  14783. }
  14784. }
  14785. class PDFNodeStreamFsRangeReader {
  14786. constructor(stream, start, end) {
  14787. this._url = stream.url;
  14788. this._done = false;
  14789. this._storedError = null;
  14790. this.onProgress = null;
  14791. this._loaded = 0;
  14792. this._readableStream = null;
  14793. this._readCapability = Promise.withResolvers();
  14794. const source = stream.source;
  14795. this._isStreamingSupported = !source.disableStream;
  14796. const fs = process.getBuiltinModule("fs");
  14797. this._setReadableStream(fs.createReadStream(this._url, {
  14798. start,
  14799. end: end - 1
  14800. }));
  14801. }
  14802. get isStreamingSupported() {
  14803. return this._isStreamingSupported;
  14804. }
  14805. async read() {
  14806. await this._readCapability.promise;
  14807. if (this._done) {
  14808. return {
  14809. value: undefined,
  14810. done: true
  14811. };
  14812. }
  14813. if (this._storedError) {
  14814. throw this._storedError;
  14815. }
  14816. const chunk = this._readableStream.read();
  14817. if (chunk === null) {
  14818. this._readCapability = Promise.withResolvers();
  14819. return this.read();
  14820. }
  14821. this._loaded += chunk.length;
  14822. this.onProgress?.({
  14823. loaded: this._loaded
  14824. });
  14825. const buffer = new Uint8Array(chunk).buffer;
  14826. return {
  14827. value: buffer,
  14828. done: false
  14829. };
  14830. }
  14831. cancel(reason) {
  14832. if (!this._readableStream) {
  14833. this._error(reason);
  14834. return;
  14835. }
  14836. this._readableStream.destroy(reason);
  14837. }
  14838. _error(reason) {
  14839. this._storedError = reason;
  14840. this._readCapability.resolve();
  14841. }
  14842. _setReadableStream(readableStream) {
  14843. this._readableStream = readableStream;
  14844. readableStream.on("readable", () => {
  14845. this._readCapability.resolve();
  14846. });
  14847. readableStream.on("end", () => {
  14848. readableStream.destroy();
  14849. this._done = true;
  14850. this._readCapability.resolve();
  14851. });
  14852. readableStream.on("error", reason => {
  14853. this._error(reason);
  14854. });
  14855. if (this._storedError) {
  14856. this._readableStream.destroy(this._storedError);
  14857. }
  14858. }
  14859. }
  14860. ;// ./src/display/pdf_objects.js
  14861. const INITIAL_DATA = Symbol("INITIAL_DATA");
  14862. class PDFObjects {
  14863. #objs = Object.create(null);
  14864. #ensureObj(objId) {
  14865. return this.#objs[objId] ||= {
  14866. ...Promise.withResolvers(),
  14867. data: INITIAL_DATA
  14868. };
  14869. }
  14870. get(objId, callback = null) {
  14871. if (callback) {
  14872. const obj = this.#ensureObj(objId);
  14873. obj.promise.then(() => callback(obj.data));
  14874. return null;
  14875. }
  14876. const obj = this.#objs[objId];
  14877. if (!obj || obj.data === INITIAL_DATA) {
  14878. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  14879. }
  14880. return obj.data;
  14881. }
  14882. has(objId) {
  14883. const obj = this.#objs[objId];
  14884. return !!obj && obj.data !== INITIAL_DATA;
  14885. }
  14886. delete(objId) {
  14887. const obj = this.#objs[objId];
  14888. if (!obj || obj.data === INITIAL_DATA) {
  14889. return false;
  14890. }
  14891. delete this.#objs[objId];
  14892. return true;
  14893. }
  14894. resolve(objId, data = null) {
  14895. const obj = this.#ensureObj(objId);
  14896. obj.data = data;
  14897. obj.resolve();
  14898. }
  14899. clear() {
  14900. for (const objId in this.#objs) {
  14901. const {
  14902. data
  14903. } = this.#objs[objId];
  14904. data?.bitmap?.close();
  14905. }
  14906. this.#objs = Object.create(null);
  14907. }
  14908. *[Symbol.iterator]() {
  14909. for (const objId in this.#objs) {
  14910. const {
  14911. data
  14912. } = this.#objs[objId];
  14913. if (data === INITIAL_DATA) {
  14914. continue;
  14915. }
  14916. yield [objId, data];
  14917. }
  14918. }
  14919. }
  14920. ;// ./src/display/text_layer.js
  14921. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  14922. const DEFAULT_FONT_SIZE = 30;
  14923. class TextLayer {
  14924. #capability = Promise.withResolvers();
  14925. #container = null;
  14926. #disableProcessItems = false;
  14927. #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  14928. #lang = null;
  14929. #layoutTextParams = null;
  14930. #pageHeight = 0;
  14931. #pageWidth = 0;
  14932. #reader = null;
  14933. #rootContainer = null;
  14934. #rotation = 0;
  14935. #scale = 0;
  14936. #styleCache = Object.create(null);
  14937. #textContentItemsStr = [];
  14938. #textContentSource = null;
  14939. #textDivs = [];
  14940. #textDivProperties = new WeakMap();
  14941. #transform = null;
  14942. static #ascentCache = new Map();
  14943. static #canvasContexts = new Map();
  14944. static #canvasCtxFonts = new WeakMap();
  14945. static #minFontSize = null;
  14946. static #pendingTextLayers = new Set();
  14947. constructor({
  14948. textContentSource,
  14949. container,
  14950. viewport
  14951. }) {
  14952. if (textContentSource instanceof ReadableStream) {
  14953. this.#textContentSource = textContentSource;
  14954. } else if (typeof textContentSource === "object") {
  14955. this.#textContentSource = new ReadableStream({
  14956. start(controller) {
  14957. controller.enqueue(textContentSource);
  14958. controller.close();
  14959. }
  14960. });
  14961. } else {
  14962. throw new Error('No "textContentSource" parameter specified.');
  14963. }
  14964. this.#container = this.#rootContainer = container;
  14965. this.#scale = viewport.scale * OutputScale.pixelRatio;
  14966. this.#rotation = viewport.rotation;
  14967. this.#layoutTextParams = {
  14968. div: null,
  14969. properties: null,
  14970. ctx: null
  14971. };
  14972. const {
  14973. pageWidth,
  14974. pageHeight,
  14975. pageX,
  14976. pageY
  14977. } = viewport.rawDims;
  14978. this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
  14979. this.#pageWidth = pageWidth;
  14980. this.#pageHeight = pageHeight;
  14981. TextLayer.#ensureMinFontSizeComputed();
  14982. setLayerDimensions(container, viewport);
  14983. this.#capability.promise.finally(() => {
  14984. TextLayer.#pendingTextLayers.delete(this);
  14985. this.#layoutTextParams = null;
  14986. this.#styleCache = null;
  14987. }).catch(() => {});
  14988. }
  14989. static get fontFamilyMap() {
  14990. const {
  14991. isWindows,
  14992. isFirefox
  14993. } = util_FeatureTest.platform;
  14994. return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));
  14995. }
  14996. render() {
  14997. const pump = () => {
  14998. this.#reader.read().then(({
  14999. value,
  15000. done
  15001. }) => {
  15002. if (done) {
  15003. this.#capability.resolve();
  15004. return;
  15005. }
  15006. this.#lang ??= value.lang;
  15007. Object.assign(this.#styleCache, value.styles);
  15008. this.#processItems(value.items);
  15009. pump();
  15010. }, this.#capability.reject);
  15011. };
  15012. this.#reader = this.#textContentSource.getReader();
  15013. TextLayer.#pendingTextLayers.add(this);
  15014. pump();
  15015. return this.#capability.promise;
  15016. }
  15017. update({
  15018. viewport,
  15019. onBefore = null
  15020. }) {
  15021. const scale = viewport.scale * OutputScale.pixelRatio;
  15022. const rotation = viewport.rotation;
  15023. if (rotation !== this.#rotation) {
  15024. onBefore?.();
  15025. this.#rotation = rotation;
  15026. setLayerDimensions(this.#rootContainer, {
  15027. rotation
  15028. });
  15029. }
  15030. if (scale !== this.#scale) {
  15031. onBefore?.();
  15032. this.#scale = scale;
  15033. const params = {
  15034. div: null,
  15035. properties: null,
  15036. ctx: TextLayer.#getCtx(this.#lang)
  15037. };
  15038. for (const div of this.#textDivs) {
  15039. params.properties = this.#textDivProperties.get(div);
  15040. params.div = div;
  15041. this.#layout(params);
  15042. }
  15043. }
  15044. }
  15045. cancel() {
  15046. const abortEx = new AbortException("TextLayer task cancelled.");
  15047. this.#reader?.cancel(abortEx).catch(() => {});
  15048. this.#reader = null;
  15049. this.#capability.reject(abortEx);
  15050. }
  15051. get textDivs() {
  15052. return this.#textDivs;
  15053. }
  15054. get textContentItemsStr() {
  15055. return this.#textContentItemsStr;
  15056. }
  15057. #processItems(items) {
  15058. if (this.#disableProcessItems) {
  15059. return;
  15060. }
  15061. this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);
  15062. const textDivs = this.#textDivs,
  15063. textContentItemsStr = this.#textContentItemsStr;
  15064. for (const item of items) {
  15065. if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
  15066. warn("Ignoring additional textDivs for performance reasons.");
  15067. this.#disableProcessItems = true;
  15068. return;
  15069. }
  15070. if (item.str === undefined) {
  15071. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  15072. const parent = this.#container;
  15073. this.#container = document.createElement("span");
  15074. this.#container.classList.add("markedContent");
  15075. if (item.id !== null) {
  15076. this.#container.setAttribute("id", `${item.id}`);
  15077. }
  15078. parent.append(this.#container);
  15079. } else if (item.type === "endMarkedContent") {
  15080. this.#container = this.#container.parentNode;
  15081. }
  15082. continue;
  15083. }
  15084. textContentItemsStr.push(item.str);
  15085. this.#appendText(item);
  15086. }
  15087. }
  15088. #appendText(geom) {
  15089. const textDiv = document.createElement("span");
  15090. const textDivProperties = {
  15091. angle: 0,
  15092. canvasWidth: 0,
  15093. hasText: geom.str !== "",
  15094. hasEOL: geom.hasEOL,
  15095. fontSize: 0
  15096. };
  15097. this.#textDivs.push(textDiv);
  15098. const tx = Util.transform(this.#transform, geom.transform);
  15099. let angle = Math.atan2(tx[1], tx[0]);
  15100. const style = this.#styleCache[geom.fontName];
  15101. if (style.vertical) {
  15102. angle += Math.PI / 2;
  15103. }
  15104. let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
  15105. fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
  15106. const fontHeight = Math.hypot(tx[2], tx[3]);
  15107. const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, style, this.#lang);
  15108. let left, top;
  15109. if (angle === 0) {
  15110. left = tx[4];
  15111. top = tx[5] - fontAscent;
  15112. } else {
  15113. left = tx[4] + fontAscent * Math.sin(angle);
  15114. top = tx[5] - fontAscent * Math.cos(angle);
  15115. }
  15116. const scaleFactorStr = "calc(var(--total-scale-factor) *";
  15117. const divStyle = textDiv.style;
  15118. if (this.#container === this.#rootContainer) {
  15119. divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
  15120. divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
  15121. } else {
  15122. divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
  15123. divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  15124. }
  15125. divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;
  15126. divStyle.fontFamily = fontFamily;
  15127. textDivProperties.fontSize = fontHeight;
  15128. textDiv.setAttribute("role", "presentation");
  15129. textDiv.textContent = geom.str;
  15130. textDiv.dir = geom.dir;
  15131. if (this.#fontInspectorEnabled) {
  15132. textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
  15133. }
  15134. if (angle !== 0) {
  15135. textDivProperties.angle = angle * (180 / Math.PI);
  15136. }
  15137. let shouldScaleText = false;
  15138. if (geom.str.length > 1) {
  15139. shouldScaleText = true;
  15140. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  15141. const absScaleX = Math.abs(geom.transform[0]),
  15142. absScaleY = Math.abs(geom.transform[3]);
  15143. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  15144. shouldScaleText = true;
  15145. }
  15146. }
  15147. if (shouldScaleText) {
  15148. textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  15149. }
  15150. this.#textDivProperties.set(textDiv, textDivProperties);
  15151. this.#layoutTextParams.div = textDiv;
  15152. this.#layoutTextParams.properties = textDivProperties;
  15153. this.#layout(this.#layoutTextParams);
  15154. if (textDivProperties.hasText) {
  15155. this.#container.append(textDiv);
  15156. }
  15157. if (textDivProperties.hasEOL) {
  15158. const br = document.createElement("br");
  15159. br.setAttribute("role", "presentation");
  15160. this.#container.append(br);
  15161. }
  15162. }
  15163. #layout(params) {
  15164. const {
  15165. div,
  15166. properties,
  15167. ctx
  15168. } = params;
  15169. const {
  15170. style
  15171. } = div;
  15172. let transform = "";
  15173. if (TextLayer.#minFontSize > 1) {
  15174. transform = `scale(${1 / TextLayer.#minFontSize})`;
  15175. }
  15176. if (properties.canvasWidth !== 0 && properties.hasText) {
  15177. const {
  15178. fontFamily
  15179. } = style;
  15180. const {
  15181. canvasWidth,
  15182. fontSize
  15183. } = properties;
  15184. TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);
  15185. const {
  15186. width
  15187. } = ctx.measureText(div.textContent);
  15188. if (width > 0) {
  15189. transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`;
  15190. }
  15191. }
  15192. if (properties.angle !== 0) {
  15193. transform = `rotate(${properties.angle}deg) ${transform}`;
  15194. }
  15195. if (transform.length > 0) {
  15196. style.transform = transform;
  15197. }
  15198. }
  15199. static cleanup() {
  15200. if (this.#pendingTextLayers.size > 0) {
  15201. return;
  15202. }
  15203. this.#ascentCache.clear();
  15204. for (const {
  15205. canvas
  15206. } of this.#canvasContexts.values()) {
  15207. canvas.remove();
  15208. }
  15209. this.#canvasContexts.clear();
  15210. }
  15211. static #getCtx(lang = null) {
  15212. let ctx = this.#canvasContexts.get(lang ||= "");
  15213. if (!ctx) {
  15214. const canvas = document.createElement("canvas");
  15215. canvas.className = "hiddenCanvasElement";
  15216. canvas.lang = lang;
  15217. document.body.append(canvas);
  15218. ctx = canvas.getContext("2d", {
  15219. alpha: false,
  15220. willReadFrequently: true
  15221. });
  15222. this.#canvasContexts.set(lang, ctx);
  15223. this.#canvasCtxFonts.set(ctx, {
  15224. size: 0,
  15225. family: ""
  15226. });
  15227. }
  15228. return ctx;
  15229. }
  15230. static #ensureCtxFont(ctx, size, family) {
  15231. const cached = this.#canvasCtxFonts.get(ctx);
  15232. if (size === cached.size && family === cached.family) {
  15233. return;
  15234. }
  15235. ctx.font = `${size}px ${family}`;
  15236. cached.size = size;
  15237. cached.family = family;
  15238. }
  15239. static #ensureMinFontSizeComputed() {
  15240. if (this.#minFontSize !== null) {
  15241. return;
  15242. }
  15243. const div = document.createElement("div");
  15244. div.style.opacity = 0;
  15245. div.style.lineHeight = 1;
  15246. div.style.fontSize = "1px";
  15247. div.style.position = "absolute";
  15248. div.textContent = "X";
  15249. document.body.append(div);
  15250. this.#minFontSize = div.getBoundingClientRect().height;
  15251. div.remove();
  15252. }
  15253. static #getAscent(fontFamily, style, lang) {
  15254. const cachedAscent = this.#ascentCache.get(fontFamily);
  15255. if (cachedAscent) {
  15256. return cachedAscent;
  15257. }
  15258. const ctx = this.#getCtx(lang);
  15259. ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
  15260. this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);
  15261. const metrics = ctx.measureText("");
  15262. const ascent = metrics.fontBoundingBoxAscent;
  15263. const descent = Math.abs(metrics.fontBoundingBoxDescent);
  15264. ctx.canvas.width = ctx.canvas.height = 0;
  15265. let ratio = 0.8;
  15266. if (ascent) {
  15267. ratio = ascent / (ascent + descent);
  15268. } else {
  15269. if (util_FeatureTest.platform.isFirefox) {
  15270. warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference " + "in `about:config` to improve TextLayer rendering.");
  15271. }
  15272. if (style.ascent) {
  15273. ratio = style.ascent;
  15274. } else if (style.descent) {
  15275. ratio = 1 + style.descent;
  15276. }
  15277. }
  15278. this.#ascentCache.set(fontFamily, ratio);
  15279. return ratio;
  15280. }
  15281. }
  15282. ;// ./src/display/xfa_text.js
  15283. class XfaText {
  15284. static textContent(xfa) {
  15285. const items = [];
  15286. const output = {
  15287. items,
  15288. styles: Object.create(null)
  15289. };
  15290. function walk(node) {
  15291. if (!node) {
  15292. return;
  15293. }
  15294. let str = null;
  15295. const name = node.name;
  15296. if (name === "#text") {
  15297. str = node.value;
  15298. } else if (!XfaText.shouldBuildText(name)) {
  15299. return;
  15300. } else if (node?.attributes?.textContent) {
  15301. str = node.attributes.textContent;
  15302. } else if (node.value) {
  15303. str = node.value;
  15304. }
  15305. if (str !== null) {
  15306. items.push({
  15307. str
  15308. });
  15309. }
  15310. if (!node.children) {
  15311. return;
  15312. }
  15313. for (const child of node.children) {
  15314. walk(child);
  15315. }
  15316. }
  15317. walk(xfa);
  15318. return output;
  15319. }
  15320. static shouldBuildText(name) {
  15321. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  15322. }
  15323. }
  15324. ;// ./src/display/api.js
  15325. const RENDERING_CANCELLED_TIMEOUT = 100;
  15326. function getDocument(src = {}) {
  15327. if (typeof src === "string" || src instanceof URL) {
  15328. src = {
  15329. url: src
  15330. };
  15331. } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
  15332. src = {
  15333. data: src
  15334. };
  15335. }
  15336. const task = new PDFDocumentLoadingTask();
  15337. const {
  15338. docId
  15339. } = task;
  15340. const url = src.url ? getUrlProp(src.url) : null;
  15341. const data = src.data ? getDataProp(src.data) : null;
  15342. const httpHeaders = src.httpHeaders || null;
  15343. const withCredentials = src.withCredentials === true;
  15344. const password = src.password ?? null;
  15345. const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  15346. const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : 2 ** 16;
  15347. let worker = src.worker instanceof PDFWorker ? src.worker : null;
  15348. const verbosity = src.verbosity;
  15349. const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
  15350. const cMapUrl = getFactoryUrlProp(src.cMapUrl);
  15351. const cMapPacked = src.cMapPacked !== false;
  15352. const CMapReaderFactory = src.CMapReaderFactory || (isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory);
  15353. const iccUrl = getFactoryUrlProp(src.iccUrl);
  15354. const standardFontDataUrl = getFactoryUrlProp(src.standardFontDataUrl);
  15355. const StandardFontDataFactory = src.StandardFontDataFactory || (isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory);
  15356. const wasmUrl = getFactoryUrlProp(src.wasmUrl);
  15357. const WasmFactory = src.WasmFactory || (isNodeJS ? NodeWasmFactory : DOMWasmFactory);
  15358. const ignoreErrors = src.stopAtErrors !== true;
  15359. const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  15360. const isEvalSupported = src.isEvalSupported !== false;
  15361. const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
  15362. const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (util_FeatureTest.platform.isFirefox || !globalThis.chrome);
  15363. const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
  15364. const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
  15365. const fontExtraProperties = src.fontExtraProperties === true;
  15366. const enableXfa = src.enableXfa === true;
  15367. const ownerDocument = src.ownerDocument || globalThis.document;
  15368. const disableRange = src.disableRange === true;
  15369. const disableStream = src.disableStream === true;
  15370. const disableAutoFetch = src.disableAutoFetch === true;
  15371. const pdfBug = src.pdfBug === true;
  15372. const CanvasFactory = src.CanvasFactory || (isNodeJS ? NodeCanvasFactory : DOMCanvasFactory);
  15373. const FilterFactory = src.FilterFactory || (isNodeJS ? NodeFilterFactory : DOMFilterFactory);
  15374. const enableHWA = src.enableHWA === true;
  15375. const useWasm = src.useWasm !== false;
  15376. const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  15377. const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
  15378. const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : !!(CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && WasmFactory === DOMWasmFactory && cMapUrl && standardFontDataUrl && wasmUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI) && isValidFetchUrl(wasmUrl, document.baseURI));
  15379. const styleElement = null;
  15380. setVerbosityLevel(verbosity);
  15381. const transportFactory = {
  15382. canvasFactory: new CanvasFactory({
  15383. ownerDocument,
  15384. enableHWA
  15385. }),
  15386. filterFactory: new FilterFactory({
  15387. docId,
  15388. ownerDocument
  15389. }),
  15390. cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({
  15391. baseUrl: cMapUrl,
  15392. isCompressed: cMapPacked
  15393. }),
  15394. standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({
  15395. baseUrl: standardFontDataUrl
  15396. }),
  15397. wasmFactory: useWorkerFetch ? null : new WasmFactory({
  15398. baseUrl: wasmUrl
  15399. })
  15400. };
  15401. if (!worker) {
  15402. worker = PDFWorker.create({
  15403. verbosity,
  15404. port: GlobalWorkerOptions.workerPort
  15405. });
  15406. task._worker = worker;
  15407. }
  15408. const docParams = {
  15409. docId,
  15410. apiVersion: "5.3.31",
  15411. data,
  15412. password,
  15413. disableAutoFetch,
  15414. rangeChunkSize,
  15415. length,
  15416. docBaseUrl,
  15417. enableXfa,
  15418. evaluatorOptions: {
  15419. maxImageSize,
  15420. disableFontFace,
  15421. ignoreErrors,
  15422. isEvalSupported,
  15423. isOffscreenCanvasSupported,
  15424. isImageDecoderSupported,
  15425. canvasMaxAreaInBytes,
  15426. fontExtraProperties,
  15427. useSystemFonts,
  15428. useWasm,
  15429. useWorkerFetch,
  15430. cMapUrl,
  15431. iccUrl,
  15432. standardFontDataUrl,
  15433. wasmUrl
  15434. }
  15435. };
  15436. const transportParams = {
  15437. ownerDocument,
  15438. pdfBug,
  15439. styleElement,
  15440. loadingParams: {
  15441. disableAutoFetch,
  15442. enableXfa
  15443. }
  15444. };
  15445. worker.promise.then(function () {
  15446. if (task.destroyed) {
  15447. throw new Error("Loading aborted");
  15448. }
  15449. if (worker.destroyed) {
  15450. throw new Error("Worker was destroyed");
  15451. }
  15452. const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
  15453. let networkStream;
  15454. if (rangeTransport) {
  15455. networkStream = new PDFDataTransportStream(rangeTransport, {
  15456. disableRange,
  15457. disableStream
  15458. });
  15459. } else if (!data) {
  15460. if (!url) {
  15461. throw new Error("getDocument - no `url` parameter provided.");
  15462. }
  15463. const NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : isNodeJS ? PDFNodeStream : PDFNetworkStream;
  15464. networkStream = new NetworkStream({
  15465. url,
  15466. length,
  15467. httpHeaders,
  15468. withCredentials,
  15469. rangeChunkSize,
  15470. disableRange,
  15471. disableStream
  15472. });
  15473. }
  15474. return workerIdPromise.then(workerId => {
  15475. if (task.destroyed) {
  15476. throw new Error("Loading aborted");
  15477. }
  15478. if (worker.destroyed) {
  15479. throw new Error("Worker was destroyed");
  15480. }
  15481. const messageHandler = new MessageHandler(docId, workerId, worker.port);
  15482. const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
  15483. task._transport = transport;
  15484. messageHandler.send("Ready", null);
  15485. });
  15486. }).catch(task._capability.reject);
  15487. return task;
  15488. }
  15489. class PDFDocumentLoadingTask {
  15490. static #docId = 0;
  15491. _capability = Promise.withResolvers();
  15492. _transport = null;
  15493. _worker = null;
  15494. docId = `d${PDFDocumentLoadingTask.#docId++}`;
  15495. destroyed = false;
  15496. onPassword = null;
  15497. onProgress = null;
  15498. get promise() {
  15499. return this._capability.promise;
  15500. }
  15501. async destroy() {
  15502. this.destroyed = true;
  15503. try {
  15504. if (this._worker?.port) {
  15505. this._worker._pendingDestroy = true;
  15506. }
  15507. await this._transport?.destroy();
  15508. } catch (ex) {
  15509. if (this._worker?.port) {
  15510. delete this._worker._pendingDestroy;
  15511. }
  15512. throw ex;
  15513. }
  15514. this._transport = null;
  15515. this._worker?.destroy();
  15516. this._worker = null;
  15517. }
  15518. async getData() {
  15519. return this._transport.getData();
  15520. }
  15521. }
  15522. class PDFDataRangeTransport {
  15523. #capability = Promise.withResolvers();
  15524. #progressiveDoneListeners = [];
  15525. #progressiveReadListeners = [];
  15526. #progressListeners = [];
  15527. #rangeListeners = [];
  15528. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  15529. this.length = length;
  15530. this.initialData = initialData;
  15531. this.progressiveDone = progressiveDone;
  15532. this.contentDispositionFilename = contentDispositionFilename;
  15533. }
  15534. addRangeListener(listener) {
  15535. this.#rangeListeners.push(listener);
  15536. }
  15537. addProgressListener(listener) {
  15538. this.#progressListeners.push(listener);
  15539. }
  15540. addProgressiveReadListener(listener) {
  15541. this.#progressiveReadListeners.push(listener);
  15542. }
  15543. addProgressiveDoneListener(listener) {
  15544. this.#progressiveDoneListeners.push(listener);
  15545. }
  15546. onDataRange(begin, chunk) {
  15547. for (const listener of this.#rangeListeners) {
  15548. listener(begin, chunk);
  15549. }
  15550. }
  15551. onDataProgress(loaded, total) {
  15552. this.#capability.promise.then(() => {
  15553. for (const listener of this.#progressListeners) {
  15554. listener(loaded, total);
  15555. }
  15556. });
  15557. }
  15558. onDataProgressiveRead(chunk) {
  15559. this.#capability.promise.then(() => {
  15560. for (const listener of this.#progressiveReadListeners) {
  15561. listener(chunk);
  15562. }
  15563. });
  15564. }
  15565. onDataProgressiveDone() {
  15566. this.#capability.promise.then(() => {
  15567. for (const listener of this.#progressiveDoneListeners) {
  15568. listener();
  15569. }
  15570. });
  15571. }
  15572. transportReady() {
  15573. this.#capability.resolve();
  15574. }
  15575. requestDataRange(begin, end) {
  15576. unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
  15577. }
  15578. abort() {}
  15579. }
  15580. class PDFDocumentProxy {
  15581. constructor(pdfInfo, transport) {
  15582. this._pdfInfo = pdfInfo;
  15583. this._transport = transport;
  15584. }
  15585. get annotationStorage() {
  15586. return this._transport.annotationStorage;
  15587. }
  15588. get canvasFactory() {
  15589. return this._transport.canvasFactory;
  15590. }
  15591. get filterFactory() {
  15592. return this._transport.filterFactory;
  15593. }
  15594. get numPages() {
  15595. return this._pdfInfo.numPages;
  15596. }
  15597. get fingerprints() {
  15598. return this._pdfInfo.fingerprints;
  15599. }
  15600. get isPureXfa() {
  15601. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  15602. }
  15603. get allXfaHtml() {
  15604. return this._transport._htmlForXfa;
  15605. }
  15606. getPage(pageNumber) {
  15607. return this._transport.getPage(pageNumber);
  15608. }
  15609. getPageIndex(ref) {
  15610. return this._transport.getPageIndex(ref);
  15611. }
  15612. getDestinations() {
  15613. return this._transport.getDestinations();
  15614. }
  15615. getDestination(id) {
  15616. return this._transport.getDestination(id);
  15617. }
  15618. getPageLabels() {
  15619. return this._transport.getPageLabels();
  15620. }
  15621. getPageLayout() {
  15622. return this._transport.getPageLayout();
  15623. }
  15624. getPageMode() {
  15625. return this._transport.getPageMode();
  15626. }
  15627. getViewerPreferences() {
  15628. return this._transport.getViewerPreferences();
  15629. }
  15630. getOpenAction() {
  15631. return this._transport.getOpenAction();
  15632. }
  15633. getAttachments() {
  15634. return this._transport.getAttachments();
  15635. }
  15636. getJSActions() {
  15637. return this._transport.getDocJSActions();
  15638. }
  15639. getOutline() {
  15640. return this._transport.getOutline();
  15641. }
  15642. getOptionalContentConfig({
  15643. intent = "display"
  15644. } = {}) {
  15645. const {
  15646. renderingIntent
  15647. } = this._transport.getRenderingIntent(intent);
  15648. return this._transport.getOptionalContentConfig(renderingIntent);
  15649. }
  15650. getPermissions() {
  15651. return this._transport.getPermissions();
  15652. }
  15653. getMetadata() {
  15654. return this._transport.getMetadata();
  15655. }
  15656. getMarkInfo() {
  15657. return this._transport.getMarkInfo();
  15658. }
  15659. getData() {
  15660. return this._transport.getData();
  15661. }
  15662. saveDocument() {
  15663. return this._transport.saveDocument();
  15664. }
  15665. getDownloadInfo() {
  15666. return this._transport.downloadInfoCapability.promise;
  15667. }
  15668. cleanup(keepLoadedFonts = false) {
  15669. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  15670. }
  15671. destroy() {
  15672. return this.loadingTask.destroy();
  15673. }
  15674. cachedPageNumber(ref) {
  15675. return this._transport.cachedPageNumber(ref);
  15676. }
  15677. get loadingParams() {
  15678. return this._transport.loadingParams;
  15679. }
  15680. get loadingTask() {
  15681. return this._transport.loadingTask;
  15682. }
  15683. getFieldObjects() {
  15684. return this._transport.getFieldObjects();
  15685. }
  15686. hasJSActions() {
  15687. return this._transport.hasJSActions();
  15688. }
  15689. getCalculationOrderIds() {
  15690. return this._transport.getCalculationOrderIds();
  15691. }
  15692. }
  15693. class PDFPageProxy {
  15694. #pendingCleanup = false;
  15695. constructor(pageIndex, pageInfo, transport, pdfBug = false) {
  15696. this._pageIndex = pageIndex;
  15697. this._pageInfo = pageInfo;
  15698. this._transport = transport;
  15699. this._stats = pdfBug ? new StatTimer() : null;
  15700. this._pdfBug = pdfBug;
  15701. this.commonObjs = transport.commonObjs;
  15702. this.objs = new PDFObjects();
  15703. this._intentStates = new Map();
  15704. this.destroyed = false;
  15705. }
  15706. get pageNumber() {
  15707. return this._pageIndex + 1;
  15708. }
  15709. get rotate() {
  15710. return this._pageInfo.rotate;
  15711. }
  15712. get ref() {
  15713. return this._pageInfo.ref;
  15714. }
  15715. get userUnit() {
  15716. return this._pageInfo.userUnit;
  15717. }
  15718. get view() {
  15719. return this._pageInfo.view;
  15720. }
  15721. getViewport({
  15722. scale,
  15723. rotation = this.rotate,
  15724. offsetX = 0,
  15725. offsetY = 0,
  15726. dontFlip = false
  15727. } = {}) {
  15728. return new PageViewport({
  15729. viewBox: this.view,
  15730. userUnit: this.userUnit,
  15731. scale,
  15732. rotation,
  15733. offsetX,
  15734. offsetY,
  15735. dontFlip
  15736. });
  15737. }
  15738. getAnnotations({
  15739. intent = "display"
  15740. } = {}) {
  15741. const {
  15742. renderingIntent
  15743. } = this._transport.getRenderingIntent(intent);
  15744. return this._transport.getAnnotations(this._pageIndex, renderingIntent);
  15745. }
  15746. getJSActions() {
  15747. return this._transport.getPageJSActions(this._pageIndex);
  15748. }
  15749. get filterFactory() {
  15750. return this._transport.filterFactory;
  15751. }
  15752. get isPureXfa() {
  15753. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  15754. }
  15755. async getXfa() {
  15756. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  15757. }
  15758. render({
  15759. canvasContext,
  15760. viewport,
  15761. intent = "display",
  15762. annotationMode = AnnotationMode.ENABLE,
  15763. transform = null,
  15764. background = null,
  15765. optionalContentConfigPromise = null,
  15766. annotationCanvasMap = null,
  15767. pageColors = null,
  15768. printAnnotationStorage = null,
  15769. isEditing = false
  15770. }) {
  15771. this._stats?.time("Overall");
  15772. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);
  15773. const {
  15774. renderingIntent,
  15775. cacheKey
  15776. } = intentArgs;
  15777. this.#pendingCleanup = false;
  15778. optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
  15779. let intentState = this._intentStates.get(cacheKey);
  15780. if (!intentState) {
  15781. intentState = Object.create(null);
  15782. this._intentStates.set(cacheKey, intentState);
  15783. }
  15784. if (intentState.streamReaderCancelTimeout) {
  15785. clearTimeout(intentState.streamReaderCancelTimeout);
  15786. intentState.streamReaderCancelTimeout = null;
  15787. }
  15788. const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  15789. if (!intentState.displayReadyCapability) {
  15790. intentState.displayReadyCapability = Promise.withResolvers();
  15791. intentState.operatorList = {
  15792. fnArray: [],
  15793. argsArray: [],
  15794. lastChunk: false,
  15795. separateAnnots: null
  15796. };
  15797. this._stats?.time("Page Request");
  15798. this._pumpOperatorList(intentArgs);
  15799. }
  15800. const complete = error => {
  15801. intentState.renderTasks.delete(internalRenderTask);
  15802. if (intentPrint) {
  15803. this.#pendingCleanup = true;
  15804. }
  15805. this.#tryCleanup();
  15806. if (error) {
  15807. internalRenderTask.capability.reject(error);
  15808. this._abortOperatorList({
  15809. intentState,
  15810. reason: error instanceof Error ? error : new Error(error)
  15811. });
  15812. } else {
  15813. internalRenderTask.capability.resolve();
  15814. }
  15815. if (this._stats) {
  15816. this._stats.timeEnd("Rendering");
  15817. this._stats.timeEnd("Overall");
  15818. if (globalThis.Stats?.enabled) {
  15819. globalThis.Stats.add(this.pageNumber, this._stats);
  15820. }
  15821. }
  15822. };
  15823. const internalRenderTask = new InternalRenderTask({
  15824. callback: complete,
  15825. params: {
  15826. canvasContext,
  15827. viewport,
  15828. transform,
  15829. background
  15830. },
  15831. objs: this.objs,
  15832. commonObjs: this.commonObjs,
  15833. annotationCanvasMap,
  15834. operatorList: intentState.operatorList,
  15835. pageIndex: this._pageIndex,
  15836. canvasFactory: this._transport.canvasFactory,
  15837. filterFactory: this._transport.filterFactory,
  15838. useRequestAnimationFrame: !intentPrint,
  15839. pdfBug: this._pdfBug,
  15840. pageColors
  15841. });
  15842. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  15843. const renderTask = internalRenderTask.task;
  15844. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  15845. if (this.destroyed) {
  15846. complete();
  15847. return;
  15848. }
  15849. this._stats?.time("Rendering");
  15850. if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
  15851. throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods.");
  15852. }
  15853. internalRenderTask.initializeGraphics({
  15854. transparency,
  15855. optionalContentConfig
  15856. });
  15857. internalRenderTask.operatorListChanged();
  15858. }).catch(complete);
  15859. return renderTask;
  15860. }
  15861. getOperatorList({
  15862. intent = "display",
  15863. annotationMode = AnnotationMode.ENABLE,
  15864. printAnnotationStorage = null,
  15865. isEditing = false
  15866. } = {}) {
  15867. function operatorListChanged() {
  15868. if (intentState.operatorList.lastChunk) {
  15869. intentState.opListReadCapability.resolve(intentState.operatorList);
  15870. intentState.renderTasks.delete(opListTask);
  15871. }
  15872. }
  15873. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);
  15874. let intentState = this._intentStates.get(intentArgs.cacheKey);
  15875. if (!intentState) {
  15876. intentState = Object.create(null);
  15877. this._intentStates.set(intentArgs.cacheKey, intentState);
  15878. }
  15879. let opListTask;
  15880. if (!intentState.opListReadCapability) {
  15881. opListTask = Object.create(null);
  15882. opListTask.operatorListChanged = operatorListChanged;
  15883. intentState.opListReadCapability = Promise.withResolvers();
  15884. (intentState.renderTasks ||= new Set()).add(opListTask);
  15885. intentState.operatorList = {
  15886. fnArray: [],
  15887. argsArray: [],
  15888. lastChunk: false,
  15889. separateAnnots: null
  15890. };
  15891. this._stats?.time("Page Request");
  15892. this._pumpOperatorList(intentArgs);
  15893. }
  15894. return intentState.opListReadCapability.promise;
  15895. }
  15896. streamTextContent({
  15897. includeMarkedContent = false,
  15898. disableNormalization = false
  15899. } = {}) {
  15900. const TEXT_CONTENT_CHUNK_SIZE = 100;
  15901. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  15902. pageIndex: this._pageIndex,
  15903. includeMarkedContent: includeMarkedContent === true,
  15904. disableNormalization: disableNormalization === true
  15905. }, {
  15906. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  15907. size(textContent) {
  15908. return textContent.items.length;
  15909. }
  15910. });
  15911. }
  15912. getTextContent(params = {}) {
  15913. if (this._transport._htmlForXfa) {
  15914. return this.getXfa().then(xfa => XfaText.textContent(xfa));
  15915. }
  15916. const readableStream = this.streamTextContent(params);
  15917. return new Promise(function (resolve, reject) {
  15918. function pump() {
  15919. reader.read().then(function ({
  15920. value,
  15921. done
  15922. }) {
  15923. if (done) {
  15924. resolve(textContent);
  15925. return;
  15926. }
  15927. textContent.lang ??= value.lang;
  15928. Object.assign(textContent.styles, value.styles);
  15929. textContent.items.push(...value.items);
  15930. pump();
  15931. }, reject);
  15932. }
  15933. const reader = readableStream.getReader();
  15934. const textContent = {
  15935. items: [],
  15936. styles: Object.create(null),
  15937. lang: null
  15938. };
  15939. pump();
  15940. });
  15941. }
  15942. getStructTree() {
  15943. return this._transport.getStructTree(this._pageIndex);
  15944. }
  15945. _destroy() {
  15946. this.destroyed = true;
  15947. const waitOn = [];
  15948. for (const intentState of this._intentStates.values()) {
  15949. this._abortOperatorList({
  15950. intentState,
  15951. reason: new Error("Page was destroyed."),
  15952. force: true
  15953. });
  15954. if (intentState.opListReadCapability) {
  15955. continue;
  15956. }
  15957. for (const internalRenderTask of intentState.renderTasks) {
  15958. waitOn.push(internalRenderTask.completed);
  15959. internalRenderTask.cancel();
  15960. }
  15961. }
  15962. this.objs.clear();
  15963. this.#pendingCleanup = false;
  15964. return Promise.all(waitOn);
  15965. }
  15966. cleanup(resetStats = false) {
  15967. this.#pendingCleanup = true;
  15968. const success = this.#tryCleanup();
  15969. if (resetStats && success) {
  15970. this._stats &&= new StatTimer();
  15971. }
  15972. return success;
  15973. }
  15974. #tryCleanup() {
  15975. if (!this.#pendingCleanup || this.destroyed) {
  15976. return false;
  15977. }
  15978. for (const {
  15979. renderTasks,
  15980. operatorList
  15981. } of this._intentStates.values()) {
  15982. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  15983. return false;
  15984. }
  15985. }
  15986. this._intentStates.clear();
  15987. this.objs.clear();
  15988. this.#pendingCleanup = false;
  15989. return true;
  15990. }
  15991. _startRenderPage(transparency, cacheKey) {
  15992. const intentState = this._intentStates.get(cacheKey);
  15993. if (!intentState) {
  15994. return;
  15995. }
  15996. this._stats?.timeEnd("Page Request");
  15997. intentState.displayReadyCapability?.resolve(transparency);
  15998. }
  15999. _renderPageChunk(operatorListChunk, intentState) {
  16000. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  16001. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  16002. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  16003. }
  16004. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  16005. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  16006. for (const internalRenderTask of intentState.renderTasks) {
  16007. internalRenderTask.operatorListChanged();
  16008. }
  16009. if (operatorListChunk.lastChunk) {
  16010. this.#tryCleanup();
  16011. }
  16012. }
  16013. _pumpOperatorList({
  16014. renderingIntent,
  16015. cacheKey,
  16016. annotationStorageSerializable,
  16017. modifiedIds
  16018. }) {
  16019. const {
  16020. map,
  16021. transfer
  16022. } = annotationStorageSerializable;
  16023. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  16024. pageIndex: this._pageIndex,
  16025. intent: renderingIntent,
  16026. cacheKey,
  16027. annotationStorage: map,
  16028. modifiedIds
  16029. }, transfer);
  16030. const reader = readableStream.getReader();
  16031. const intentState = this._intentStates.get(cacheKey);
  16032. intentState.streamReader = reader;
  16033. const pump = () => {
  16034. reader.read().then(({
  16035. value,
  16036. done
  16037. }) => {
  16038. if (done) {
  16039. intentState.streamReader = null;
  16040. return;
  16041. }
  16042. if (this._transport.destroyed) {
  16043. return;
  16044. }
  16045. this._renderPageChunk(value, intentState);
  16046. pump();
  16047. }, reason => {
  16048. intentState.streamReader = null;
  16049. if (this._transport.destroyed) {
  16050. return;
  16051. }
  16052. if (intentState.operatorList) {
  16053. intentState.operatorList.lastChunk = true;
  16054. for (const internalRenderTask of intentState.renderTasks) {
  16055. internalRenderTask.operatorListChanged();
  16056. }
  16057. this.#tryCleanup();
  16058. }
  16059. if (intentState.displayReadyCapability) {
  16060. intentState.displayReadyCapability.reject(reason);
  16061. } else if (intentState.opListReadCapability) {
  16062. intentState.opListReadCapability.reject(reason);
  16063. } else {
  16064. throw reason;
  16065. }
  16066. });
  16067. };
  16068. pump();
  16069. }
  16070. _abortOperatorList({
  16071. intentState,
  16072. reason,
  16073. force = false
  16074. }) {
  16075. if (!intentState.streamReader) {
  16076. return;
  16077. }
  16078. if (intentState.streamReaderCancelTimeout) {
  16079. clearTimeout(intentState.streamReaderCancelTimeout);
  16080. intentState.streamReaderCancelTimeout = null;
  16081. }
  16082. if (!force) {
  16083. if (intentState.renderTasks.size > 0) {
  16084. return;
  16085. }
  16086. if (reason instanceof RenderingCancelledException) {
  16087. let delay = RENDERING_CANCELLED_TIMEOUT;
  16088. if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
  16089. delay += reason.extraDelay;
  16090. }
  16091. intentState.streamReaderCancelTimeout = setTimeout(() => {
  16092. intentState.streamReaderCancelTimeout = null;
  16093. this._abortOperatorList({
  16094. intentState,
  16095. reason,
  16096. force: true
  16097. });
  16098. }, delay);
  16099. return;
  16100. }
  16101. }
  16102. intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {});
  16103. intentState.streamReader = null;
  16104. if (this._transport.destroyed) {
  16105. return;
  16106. }
  16107. for (const [curCacheKey, curIntentState] of this._intentStates) {
  16108. if (curIntentState === intentState) {
  16109. this._intentStates.delete(curCacheKey);
  16110. break;
  16111. }
  16112. }
  16113. this.cleanup();
  16114. }
  16115. get stats() {
  16116. return this._stats;
  16117. }
  16118. }
  16119. class PDFWorker {
  16120. #capability = Promise.withResolvers();
  16121. #messageHandler = null;
  16122. #port = null;
  16123. #webWorker = null;
  16124. static #fakeWorkerId = 0;
  16125. static #isWorkerDisabled = false;
  16126. static #workerPorts = new WeakMap();
  16127. static {
  16128. if (isNodeJS) {
  16129. this.#isWorkerDisabled = true;
  16130. GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";
  16131. }
  16132. this._isSameOrigin = (baseUrl, otherUrl) => {
  16133. const base = URL.parse(baseUrl);
  16134. if (!base?.origin || base.origin === "null") {
  16135. return false;
  16136. }
  16137. const other = new URL(otherUrl, base);
  16138. return base.origin === other.origin;
  16139. };
  16140. this._createCDNWrapper = url => {
  16141. const wrapper = `await import("${url}");`;
  16142. return URL.createObjectURL(new Blob([wrapper], {
  16143. type: "text/javascript"
  16144. }));
  16145. };
  16146. this.fromPort = params => {
  16147. deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead.");
  16148. if (!params?.port) {
  16149. throw new Error("PDFWorker.fromPort - invalid method signature.");
  16150. }
  16151. return this.create(params);
  16152. };
  16153. }
  16154. constructor({
  16155. name = null,
  16156. port = null,
  16157. verbosity = getVerbosityLevel()
  16158. } = {}) {
  16159. this.name = name;
  16160. this.destroyed = false;
  16161. this.verbosity = verbosity;
  16162. if (port) {
  16163. if (PDFWorker.#workerPorts.has(port)) {
  16164. throw new Error("Cannot use more than one PDFWorker per port.");
  16165. }
  16166. PDFWorker.#workerPorts.set(port, this);
  16167. this.#initializeFromPort(port);
  16168. } else {
  16169. this.#initialize();
  16170. }
  16171. }
  16172. get promise() {
  16173. return this.#capability.promise;
  16174. }
  16175. #resolve() {
  16176. this.#capability.resolve();
  16177. this.#messageHandler.send("configure", {
  16178. verbosity: this.verbosity
  16179. });
  16180. }
  16181. get port() {
  16182. return this.#port;
  16183. }
  16184. get messageHandler() {
  16185. return this.#messageHandler;
  16186. }
  16187. #initializeFromPort(port) {
  16188. this.#port = port;
  16189. this.#messageHandler = new MessageHandler("main", "worker", port);
  16190. this.#messageHandler.on("ready", () => {});
  16191. this.#resolve();
  16192. }
  16193. #initialize() {
  16194. if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) {
  16195. this.#setupFakeWorker();
  16196. return;
  16197. }
  16198. let {
  16199. workerSrc
  16200. } = PDFWorker;
  16201. try {
  16202. if (!PDFWorker._isSameOrigin(window.location, workerSrc)) {
  16203. workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);
  16204. }
  16205. const worker = new Worker(workerSrc, {
  16206. type: "module"
  16207. });
  16208. const messageHandler = new MessageHandler("main", "worker", worker);
  16209. const terminateEarly = () => {
  16210. ac.abort();
  16211. messageHandler.destroy();
  16212. worker.terminate();
  16213. if (this.destroyed) {
  16214. this.#capability.reject(new Error("Worker was destroyed"));
  16215. } else {
  16216. this.#setupFakeWorker();
  16217. }
  16218. };
  16219. const ac = new AbortController();
  16220. worker.addEventListener("error", () => {
  16221. if (!this.#webWorker) {
  16222. terminateEarly();
  16223. }
  16224. }, {
  16225. signal: ac.signal
  16226. });
  16227. messageHandler.on("test", data => {
  16228. ac.abort();
  16229. if (this.destroyed || !data) {
  16230. terminateEarly();
  16231. return;
  16232. }
  16233. this.#messageHandler = messageHandler;
  16234. this.#port = worker;
  16235. this.#webWorker = worker;
  16236. this.#resolve();
  16237. });
  16238. messageHandler.on("ready", data => {
  16239. ac.abort();
  16240. if (this.destroyed) {
  16241. terminateEarly();
  16242. return;
  16243. }
  16244. try {
  16245. sendTest();
  16246. } catch {
  16247. this.#setupFakeWorker();
  16248. }
  16249. });
  16250. const sendTest = () => {
  16251. const testObj = new Uint8Array();
  16252. messageHandler.send("test", testObj, [testObj.buffer]);
  16253. };
  16254. sendTest();
  16255. return;
  16256. } catch {
  16257. info("The worker has been disabled.");
  16258. }
  16259. this.#setupFakeWorker();
  16260. }
  16261. #setupFakeWorker() {
  16262. if (!PDFWorker.#isWorkerDisabled) {
  16263. warn("Setting up fake worker.");
  16264. PDFWorker.#isWorkerDisabled = true;
  16265. }
  16266. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  16267. if (this.destroyed) {
  16268. this.#capability.reject(new Error("Worker was destroyed"));
  16269. return;
  16270. }
  16271. const port = new LoopbackPort();
  16272. this.#port = port;
  16273. const id = `fake${PDFWorker.#fakeWorkerId++}`;
  16274. const workerHandler = new MessageHandler(id + "_worker", id, port);
  16275. WorkerMessageHandler.setup(workerHandler, port);
  16276. this.#messageHandler = new MessageHandler(id, id + "_worker", port);
  16277. this.#resolve();
  16278. }).catch(reason => {
  16279. this.#capability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  16280. });
  16281. }
  16282. destroy() {
  16283. this.destroyed = true;
  16284. this.#webWorker?.terminate();
  16285. this.#webWorker = null;
  16286. PDFWorker.#workerPorts.delete(this.#port);
  16287. this.#port = null;
  16288. this.#messageHandler?.destroy();
  16289. this.#messageHandler = null;
  16290. }
  16291. static create(params) {
  16292. const cachedPort = this.#workerPorts.get(params?.port);
  16293. if (cachedPort) {
  16294. if (cachedPort._pendingDestroy) {
  16295. throw new Error("PDFWorker.create - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
  16296. }
  16297. return cachedPort;
  16298. }
  16299. return new PDFWorker(params);
  16300. }
  16301. static get workerSrc() {
  16302. if (GlobalWorkerOptions.workerSrc) {
  16303. return GlobalWorkerOptions.workerSrc;
  16304. }
  16305. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  16306. }
  16307. static get #mainThreadWorkerMessageHandler() {
  16308. try {
  16309. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  16310. } catch {
  16311. return null;
  16312. }
  16313. }
  16314. static get _setupFakeWorkerGlobal() {
  16315. const loader = async () => {
  16316. if (this.#mainThreadWorkerMessageHandler) {
  16317. return this.#mainThreadWorkerMessageHandler;
  16318. }
  16319. const worker = await import(
  16320. /*webpackIgnore: true*/
  16321. /*@vite-ignore*/
  16322. this.workerSrc);
  16323. return worker.WorkerMessageHandler;
  16324. };
  16325. return shadow(this, "_setupFakeWorkerGlobal", loader());
  16326. }
  16327. }
  16328. class WorkerTransport {
  16329. #methodPromises = new Map();
  16330. #pageCache = new Map();
  16331. #pagePromises = new Map();
  16332. #pageRefCache = new Map();
  16333. #passwordCapability = null;
  16334. constructor(messageHandler, loadingTask, networkStream, params, factory) {
  16335. this.messageHandler = messageHandler;
  16336. this.loadingTask = loadingTask;
  16337. this.commonObjs = new PDFObjects();
  16338. this.fontLoader = new FontLoader({
  16339. ownerDocument: params.ownerDocument,
  16340. styleElement: params.styleElement
  16341. });
  16342. this.loadingParams = params.loadingParams;
  16343. this._params = params;
  16344. this.canvasFactory = factory.canvasFactory;
  16345. this.filterFactory = factory.filterFactory;
  16346. this.cMapReaderFactory = factory.cMapReaderFactory;
  16347. this.standardFontDataFactory = factory.standardFontDataFactory;
  16348. this.wasmFactory = factory.wasmFactory;
  16349. this.destroyed = false;
  16350. this.destroyCapability = null;
  16351. this._networkStream = networkStream;
  16352. this._fullReader = null;
  16353. this._lastProgress = null;
  16354. this.downloadInfoCapability = Promise.withResolvers();
  16355. this.setupMessageHandler();
  16356. }
  16357. #cacheSimpleMethod(name, data = null) {
  16358. const cachedPromise = this.#methodPromises.get(name);
  16359. if (cachedPromise) {
  16360. return cachedPromise;
  16361. }
  16362. const promise = this.messageHandler.sendWithPromise(name, data);
  16363. this.#methodPromises.set(name, promise);
  16364. return promise;
  16365. }
  16366. get annotationStorage() {
  16367. return shadow(this, "annotationStorage", new AnnotationStorage());
  16368. }
  16369. getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {
  16370. let renderingIntent = RenderingIntentFlag.DISPLAY;
  16371. let annotationStorageSerializable = SerializableEmpty;
  16372. switch (intent) {
  16373. case "any":
  16374. renderingIntent = RenderingIntentFlag.ANY;
  16375. break;
  16376. case "display":
  16377. break;
  16378. case "print":
  16379. renderingIntent = RenderingIntentFlag.PRINT;
  16380. break;
  16381. default:
  16382. warn(`getRenderingIntent - invalid intent: ${intent}`);
  16383. }
  16384. const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  16385. switch (annotationMode) {
  16386. case AnnotationMode.DISABLE:
  16387. renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
  16388. break;
  16389. case AnnotationMode.ENABLE:
  16390. break;
  16391. case AnnotationMode.ENABLE_FORMS:
  16392. renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
  16393. break;
  16394. case AnnotationMode.ENABLE_STORAGE:
  16395. renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
  16396. annotationStorageSerializable = annotationStorage.serializable;
  16397. break;
  16398. default:
  16399. warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  16400. }
  16401. if (isEditing) {
  16402. renderingIntent += RenderingIntentFlag.IS_EDITING;
  16403. }
  16404. if (isOpList) {
  16405. renderingIntent += RenderingIntentFlag.OPLIST;
  16406. }
  16407. const {
  16408. ids: modifiedIds,
  16409. hash: modifiedIdsHash
  16410. } = annotationStorage.modifiedIds;
  16411. const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];
  16412. return {
  16413. renderingIntent,
  16414. cacheKey: cacheKeyBuf.join("_"),
  16415. annotationStorageSerializable,
  16416. modifiedIds
  16417. };
  16418. }
  16419. destroy() {
  16420. if (this.destroyCapability) {
  16421. return this.destroyCapability.promise;
  16422. }
  16423. this.destroyed = true;
  16424. this.destroyCapability = Promise.withResolvers();
  16425. this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
  16426. const waitOn = [];
  16427. for (const page of this.#pageCache.values()) {
  16428. waitOn.push(page._destroy());
  16429. }
  16430. this.#pageCache.clear();
  16431. this.#pagePromises.clear();
  16432. this.#pageRefCache.clear();
  16433. if (this.hasOwnProperty("annotationStorage")) {
  16434. this.annotationStorage.resetModified();
  16435. }
  16436. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  16437. waitOn.push(terminated);
  16438. Promise.all(waitOn).then(() => {
  16439. this.commonObjs.clear();
  16440. this.fontLoader.clear();
  16441. this.#methodPromises.clear();
  16442. this.filterFactory.destroy();
  16443. TextLayer.cleanup();
  16444. this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
  16445. this.messageHandler?.destroy();
  16446. this.messageHandler = null;
  16447. this.destroyCapability.resolve();
  16448. }, this.destroyCapability.reject);
  16449. return this.destroyCapability.promise;
  16450. }
  16451. setupMessageHandler() {
  16452. const {
  16453. messageHandler,
  16454. loadingTask
  16455. } = this;
  16456. messageHandler.on("GetReader", (data, sink) => {
  16457. assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  16458. this._fullReader = this._networkStream.getFullReader();
  16459. this._fullReader.onProgress = evt => {
  16460. this._lastProgress = {
  16461. loaded: evt.loaded,
  16462. total: evt.total
  16463. };
  16464. };
  16465. sink.onPull = () => {
  16466. this._fullReader.read().then(function ({
  16467. value,
  16468. done
  16469. }) {
  16470. if (done) {
  16471. sink.close();
  16472. return;
  16473. }
  16474. assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
  16475. sink.enqueue(new Uint8Array(value), 1, [value]);
  16476. }).catch(reason => {
  16477. sink.error(reason);
  16478. });
  16479. };
  16480. sink.onCancel = reason => {
  16481. this._fullReader.cancel(reason);
  16482. sink.ready.catch(readyReason => {
  16483. if (this.destroyed) {
  16484. return;
  16485. }
  16486. throw readyReason;
  16487. });
  16488. };
  16489. });
  16490. messageHandler.on("ReaderHeadersReady", async data => {
  16491. await this._fullReader.headersReady;
  16492. const {
  16493. isStreamingSupported,
  16494. isRangeSupported,
  16495. contentLength
  16496. } = this._fullReader;
  16497. if (!isStreamingSupported || !isRangeSupported) {
  16498. if (this._lastProgress) {
  16499. loadingTask.onProgress?.(this._lastProgress);
  16500. }
  16501. this._fullReader.onProgress = evt => {
  16502. loadingTask.onProgress?.({
  16503. loaded: evt.loaded,
  16504. total: evt.total
  16505. });
  16506. };
  16507. }
  16508. return {
  16509. isStreamingSupported,
  16510. isRangeSupported,
  16511. contentLength
  16512. };
  16513. });
  16514. messageHandler.on("GetRangeReader", (data, sink) => {
  16515. assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  16516. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  16517. if (!rangeReader) {
  16518. sink.close();
  16519. return;
  16520. }
  16521. sink.onPull = () => {
  16522. rangeReader.read().then(function ({
  16523. value,
  16524. done
  16525. }) {
  16526. if (done) {
  16527. sink.close();
  16528. return;
  16529. }
  16530. assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
  16531. sink.enqueue(new Uint8Array(value), 1, [value]);
  16532. }).catch(reason => {
  16533. sink.error(reason);
  16534. });
  16535. };
  16536. sink.onCancel = reason => {
  16537. rangeReader.cancel(reason);
  16538. sink.ready.catch(readyReason => {
  16539. if (this.destroyed) {
  16540. return;
  16541. }
  16542. throw readyReason;
  16543. });
  16544. };
  16545. });
  16546. messageHandler.on("GetDoc", ({
  16547. pdfInfo
  16548. }) => {
  16549. this._numPages = pdfInfo.numPages;
  16550. this._htmlForXfa = pdfInfo.htmlForXfa;
  16551. delete pdfInfo.htmlForXfa;
  16552. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  16553. });
  16554. messageHandler.on("DocException", ex => {
  16555. loadingTask._capability.reject(wrapReason(ex));
  16556. });
  16557. messageHandler.on("PasswordRequest", ex => {
  16558. this.#passwordCapability = Promise.withResolvers();
  16559. try {
  16560. if (!loadingTask.onPassword) {
  16561. throw wrapReason(ex);
  16562. }
  16563. const updatePassword = password => {
  16564. if (password instanceof Error) {
  16565. this.#passwordCapability.reject(password);
  16566. } else {
  16567. this.#passwordCapability.resolve({
  16568. password
  16569. });
  16570. }
  16571. };
  16572. loadingTask.onPassword(updatePassword, ex.code);
  16573. } catch (err) {
  16574. this.#passwordCapability.reject(err);
  16575. }
  16576. return this.#passwordCapability.promise;
  16577. });
  16578. messageHandler.on("DataLoaded", data => {
  16579. loadingTask.onProgress?.({
  16580. loaded: data.length,
  16581. total: data.length
  16582. });
  16583. this.downloadInfoCapability.resolve(data);
  16584. });
  16585. messageHandler.on("StartRenderPage", data => {
  16586. if (this.destroyed) {
  16587. return;
  16588. }
  16589. const page = this.#pageCache.get(data.pageIndex);
  16590. page._startRenderPage(data.transparency, data.cacheKey);
  16591. });
  16592. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  16593. if (this.destroyed) {
  16594. return null;
  16595. }
  16596. if (this.commonObjs.has(id)) {
  16597. return null;
  16598. }
  16599. switch (type) {
  16600. case "Font":
  16601. if ("error" in exportedData) {
  16602. const exportedError = exportedData.error;
  16603. warn(`Error during font loading: ${exportedError}`);
  16604. this.commonObjs.resolve(id, exportedError);
  16605. break;
  16606. }
  16607. const inspectFont = this._params.pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
  16608. const font = new FontFaceObject(exportedData, inspectFont);
  16609. this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
  16610. id
  16611. })).finally(() => {
  16612. if (!font.fontExtraProperties && font.data) {
  16613. font.data = null;
  16614. }
  16615. this.commonObjs.resolve(id, font);
  16616. });
  16617. break;
  16618. case "CopyLocalImage":
  16619. const {
  16620. imageRef
  16621. } = exportedData;
  16622. assert(imageRef, "The imageRef must be defined.");
  16623. for (const pageProxy of this.#pageCache.values()) {
  16624. for (const [, data] of pageProxy.objs) {
  16625. if (data?.ref !== imageRef) {
  16626. continue;
  16627. }
  16628. if (!data.dataLen) {
  16629. return null;
  16630. }
  16631. this.commonObjs.resolve(id, structuredClone(data));
  16632. return data.dataLen;
  16633. }
  16634. }
  16635. break;
  16636. case "FontPath":
  16637. case "Image":
  16638. case "Pattern":
  16639. this.commonObjs.resolve(id, exportedData);
  16640. break;
  16641. default:
  16642. throw new Error(`Got unknown common object type ${type}`);
  16643. }
  16644. return null;
  16645. });
  16646. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  16647. if (this.destroyed) {
  16648. return;
  16649. }
  16650. const pageProxy = this.#pageCache.get(pageIndex);
  16651. if (pageProxy.objs.has(id)) {
  16652. return;
  16653. }
  16654. if (pageProxy._intentStates.size === 0) {
  16655. imageData?.bitmap?.close();
  16656. return;
  16657. }
  16658. switch (type) {
  16659. case "Image":
  16660. case "Pattern":
  16661. pageProxy.objs.resolve(id, imageData);
  16662. break;
  16663. default:
  16664. throw new Error(`Got unknown object type ${type}`);
  16665. }
  16666. });
  16667. messageHandler.on("DocProgress", data => {
  16668. if (this.destroyed) {
  16669. return;
  16670. }
  16671. loadingTask.onProgress?.({
  16672. loaded: data.loaded,
  16673. total: data.total
  16674. });
  16675. });
  16676. messageHandler.on("FetchBinaryData", async data => {
  16677. if (this.destroyed) {
  16678. throw new Error("Worker was destroyed.");
  16679. }
  16680. const factory = this[data.type];
  16681. if (!factory) {
  16682. throw new Error(`${data.type} not initialized, see the \`useWorkerFetch\` parameter.`);
  16683. }
  16684. return factory.fetch(data);
  16685. });
  16686. }
  16687. getData() {
  16688. return this.messageHandler.sendWithPromise("GetData", null);
  16689. }
  16690. saveDocument() {
  16691. if (this.annotationStorage.size <= 0) {
  16692. warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  16693. }
  16694. const {
  16695. map,
  16696. transfer
  16697. } = this.annotationStorage.serializable;
  16698. return this.messageHandler.sendWithPromise("SaveDocument", {
  16699. isPureXfa: !!this._htmlForXfa,
  16700. numPages: this._numPages,
  16701. annotationStorage: map,
  16702. filename: this._fullReader?.filename ?? null
  16703. }, transfer).finally(() => {
  16704. this.annotationStorage.resetModified();
  16705. });
  16706. }
  16707. getPage(pageNumber) {
  16708. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  16709. return Promise.reject(new Error("Invalid page request."));
  16710. }
  16711. const pageIndex = pageNumber - 1,
  16712. cachedPromise = this.#pagePromises.get(pageIndex);
  16713. if (cachedPromise) {
  16714. return cachedPromise;
  16715. }
  16716. const promise = this.messageHandler.sendWithPromise("GetPage", {
  16717. pageIndex
  16718. }).then(pageInfo => {
  16719. if (this.destroyed) {
  16720. throw new Error("Transport destroyed");
  16721. }
  16722. if (pageInfo.refStr) {
  16723. this.#pageRefCache.set(pageInfo.refStr, pageNumber);
  16724. }
  16725. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
  16726. this.#pageCache.set(pageIndex, page);
  16727. return page;
  16728. });
  16729. this.#pagePromises.set(pageIndex, promise);
  16730. return promise;
  16731. }
  16732. getPageIndex(ref) {
  16733. if (!isRefProxy(ref)) {
  16734. return Promise.reject(new Error("Invalid pageIndex request."));
  16735. }
  16736. return this.messageHandler.sendWithPromise("GetPageIndex", {
  16737. num: ref.num,
  16738. gen: ref.gen
  16739. });
  16740. }
  16741. getAnnotations(pageIndex, intent) {
  16742. return this.messageHandler.sendWithPromise("GetAnnotations", {
  16743. pageIndex,
  16744. intent
  16745. });
  16746. }
  16747. getFieldObjects() {
  16748. return this.#cacheSimpleMethod("GetFieldObjects");
  16749. }
  16750. hasJSActions() {
  16751. return this.#cacheSimpleMethod("HasJSActions");
  16752. }
  16753. getCalculationOrderIds() {
  16754. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  16755. }
  16756. getDestinations() {
  16757. return this.messageHandler.sendWithPromise("GetDestinations", null);
  16758. }
  16759. getDestination(id) {
  16760. if (typeof id !== "string") {
  16761. return Promise.reject(new Error("Invalid destination request."));
  16762. }
  16763. return this.messageHandler.sendWithPromise("GetDestination", {
  16764. id
  16765. });
  16766. }
  16767. getPageLabels() {
  16768. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  16769. }
  16770. getPageLayout() {
  16771. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  16772. }
  16773. getPageMode() {
  16774. return this.messageHandler.sendWithPromise("GetPageMode", null);
  16775. }
  16776. getViewerPreferences() {
  16777. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  16778. }
  16779. getOpenAction() {
  16780. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  16781. }
  16782. getAttachments() {
  16783. return this.messageHandler.sendWithPromise("GetAttachments", null);
  16784. }
  16785. getDocJSActions() {
  16786. return this.#cacheSimpleMethod("GetDocJSActions");
  16787. }
  16788. getPageJSActions(pageIndex) {
  16789. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  16790. pageIndex
  16791. });
  16792. }
  16793. getStructTree(pageIndex) {
  16794. return this.messageHandler.sendWithPromise("GetStructTree", {
  16795. pageIndex
  16796. });
  16797. }
  16798. getOutline() {
  16799. return this.messageHandler.sendWithPromise("GetOutline", null);
  16800. }
  16801. getOptionalContentConfig(renderingIntent) {
  16802. return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent));
  16803. }
  16804. getPermissions() {
  16805. return this.messageHandler.sendWithPromise("GetPermissions", null);
  16806. }
  16807. getMetadata() {
  16808. const name = "GetMetadata",
  16809. cachedPromise = this.#methodPromises.get(name);
  16810. if (cachedPromise) {
  16811. return cachedPromise;
  16812. }
  16813. const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({
  16814. info: results[0],
  16815. metadata: results[1] ? new Metadata(results[1]) : null,
  16816. contentDispositionFilename: this._fullReader?.filename ?? null,
  16817. contentLength: this._fullReader?.contentLength ?? null
  16818. }));
  16819. this.#methodPromises.set(name, promise);
  16820. return promise;
  16821. }
  16822. getMarkInfo() {
  16823. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  16824. }
  16825. async startCleanup(keepLoadedFonts = false) {
  16826. if (this.destroyed) {
  16827. return;
  16828. }
  16829. await this.messageHandler.sendWithPromise("Cleanup", null);
  16830. for (const page of this.#pageCache.values()) {
  16831. const cleanupSuccessful = page.cleanup();
  16832. if (!cleanupSuccessful) {
  16833. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  16834. }
  16835. }
  16836. this.commonObjs.clear();
  16837. if (!keepLoadedFonts) {
  16838. this.fontLoader.clear();
  16839. }
  16840. this.#methodPromises.clear();
  16841. this.filterFactory.destroy(true);
  16842. TextLayer.cleanup();
  16843. }
  16844. cachedPageNumber(ref) {
  16845. if (!isRefProxy(ref)) {
  16846. return null;
  16847. }
  16848. const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
  16849. return this.#pageRefCache.get(refStr) ?? null;
  16850. }
  16851. }
  16852. class RenderTask {
  16853. #internalRenderTask = null;
  16854. onContinue = null;
  16855. onError = null;
  16856. constructor(internalRenderTask) {
  16857. this.#internalRenderTask = internalRenderTask;
  16858. }
  16859. get promise() {
  16860. return this.#internalRenderTask.capability.promise;
  16861. }
  16862. cancel(extraDelay = 0) {
  16863. this.#internalRenderTask.cancel(null, extraDelay);
  16864. }
  16865. get separateAnnots() {
  16866. const {
  16867. separateAnnots
  16868. } = this.#internalRenderTask.operatorList;
  16869. if (!separateAnnots) {
  16870. return false;
  16871. }
  16872. const {
  16873. annotationCanvasMap
  16874. } = this.#internalRenderTask;
  16875. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  16876. }
  16877. }
  16878. class InternalRenderTask {
  16879. #rAF = null;
  16880. static #canvasInUse = new WeakSet();
  16881. constructor({
  16882. callback,
  16883. params,
  16884. objs,
  16885. commonObjs,
  16886. annotationCanvasMap,
  16887. operatorList,
  16888. pageIndex,
  16889. canvasFactory,
  16890. filterFactory,
  16891. useRequestAnimationFrame = false,
  16892. pdfBug = false,
  16893. pageColors = null
  16894. }) {
  16895. this.callback = callback;
  16896. this.params = params;
  16897. this.objs = objs;
  16898. this.commonObjs = commonObjs;
  16899. this.annotationCanvasMap = annotationCanvasMap;
  16900. this.operatorListIdx = null;
  16901. this.operatorList = operatorList;
  16902. this._pageIndex = pageIndex;
  16903. this.canvasFactory = canvasFactory;
  16904. this.filterFactory = filterFactory;
  16905. this._pdfBug = pdfBug;
  16906. this.pageColors = pageColors;
  16907. this.running = false;
  16908. this.graphicsReadyCallback = null;
  16909. this.graphicsReady = false;
  16910. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  16911. this.cancelled = false;
  16912. this.capability = Promise.withResolvers();
  16913. this.task = new RenderTask(this);
  16914. this._cancelBound = this.cancel.bind(this);
  16915. this._continueBound = this._continue.bind(this);
  16916. this._scheduleNextBound = this._scheduleNext.bind(this);
  16917. this._nextBound = this._next.bind(this);
  16918. this._canvas = params.canvasContext.canvas;
  16919. }
  16920. get completed() {
  16921. return this.capability.promise.catch(function () {});
  16922. }
  16923. initializeGraphics({
  16924. transparency = false,
  16925. optionalContentConfig
  16926. }) {
  16927. if (this.cancelled) {
  16928. return;
  16929. }
  16930. if (this._canvas) {
  16931. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  16932. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  16933. }
  16934. InternalRenderTask.#canvasInUse.add(this._canvas);
  16935. }
  16936. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  16937. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  16938. this.stepper.init(this.operatorList);
  16939. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  16940. }
  16941. const {
  16942. canvasContext,
  16943. viewport,
  16944. transform,
  16945. background
  16946. } = this.params;
  16947. this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  16948. optionalContentConfig
  16949. }, this.annotationCanvasMap, this.pageColors);
  16950. this.gfx.beginDrawing({
  16951. transform,
  16952. viewport,
  16953. transparency,
  16954. background
  16955. });
  16956. this.operatorListIdx = 0;
  16957. this.graphicsReady = true;
  16958. this.graphicsReadyCallback?.();
  16959. }
  16960. cancel(error = null, extraDelay = 0) {
  16961. this.running = false;
  16962. this.cancelled = true;
  16963. this.gfx?.endDrawing();
  16964. if (this.#rAF) {
  16965. window.cancelAnimationFrame(this.#rAF);
  16966. this.#rAF = null;
  16967. }
  16968. InternalRenderTask.#canvasInUse.delete(this._canvas);
  16969. error ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay);
  16970. this.callback(error);
  16971. this.task.onError?.(error);
  16972. }
  16973. operatorListChanged() {
  16974. if (!this.graphicsReady) {
  16975. this.graphicsReadyCallback ||= this._continueBound;
  16976. return;
  16977. }
  16978. this.stepper?.updateOperatorList(this.operatorList);
  16979. if (this.running) {
  16980. return;
  16981. }
  16982. this._continue();
  16983. }
  16984. _continue() {
  16985. this.running = true;
  16986. if (this.cancelled) {
  16987. return;
  16988. }
  16989. if (this.task.onContinue) {
  16990. this.task.onContinue(this._scheduleNextBound);
  16991. } else {
  16992. this._scheduleNext();
  16993. }
  16994. }
  16995. _scheduleNext() {
  16996. if (this._useRequestAnimationFrame) {
  16997. this.#rAF = window.requestAnimationFrame(() => {
  16998. this.#rAF = null;
  16999. this._nextBound().catch(this._cancelBound);
  17000. });
  17001. } else {
  17002. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  17003. }
  17004. }
  17005. async _next() {
  17006. if (this.cancelled) {
  17007. return;
  17008. }
  17009. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  17010. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  17011. this.running = false;
  17012. if (this.operatorList.lastChunk) {
  17013. this.gfx.endDrawing();
  17014. InternalRenderTask.#canvasInUse.delete(this._canvas);
  17015. this.callback();
  17016. }
  17017. }
  17018. }
  17019. }
  17020. const version = "5.3.31";
  17021. const build = "47ad820d9";
  17022. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.flat-map.js
  17023. var es_iterator_flat_map = __webpack_require__(531);
  17024. ;// ./src/shared/scripting_utils.js
  17025. function makeColorComp(n) {
  17026. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  17027. }
  17028. function scaleAndClamp(x) {
  17029. return Math.max(0, Math.min(255, 255 * x));
  17030. }
  17031. class ColorConverters {
  17032. static CMYK_G([c, y, m, k]) {
  17033. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  17034. }
  17035. static G_CMYK([g]) {
  17036. return ["CMYK", 0, 0, 0, 1 - g];
  17037. }
  17038. static G_RGB([g]) {
  17039. return ["RGB", g, g, g];
  17040. }
  17041. static G_rgb([g]) {
  17042. g = scaleAndClamp(g);
  17043. return [g, g, g];
  17044. }
  17045. static G_HTML([g]) {
  17046. const G = makeColorComp(g);
  17047. return `#${G}${G}${G}`;
  17048. }
  17049. static RGB_G([r, g, b]) {
  17050. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  17051. }
  17052. static RGB_rgb(color) {
  17053. return color.map(scaleAndClamp);
  17054. }
  17055. static RGB_HTML(color) {
  17056. return `#${color.map(makeColorComp).join("")}`;
  17057. }
  17058. static T_HTML() {
  17059. return "#00000000";
  17060. }
  17061. static T_rgb() {
  17062. return [null];
  17063. }
  17064. static CMYK_RGB([c, y, m, k]) {
  17065. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  17066. }
  17067. static CMYK_rgb([c, y, m, k]) {
  17068. return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
  17069. }
  17070. static CMYK_HTML(components) {
  17071. const rgb = this.CMYK_RGB(components).slice(1);
  17072. return this.RGB_HTML(rgb);
  17073. }
  17074. static RGB_CMYK([r, g, b]) {
  17075. const c = 1 - r;
  17076. const m = 1 - g;
  17077. const y = 1 - b;
  17078. const k = Math.min(c, m, y);
  17079. return ["CMYK", c, m, y, k];
  17080. }
  17081. }
  17082. ;// ./src/display/svg_factory.js
  17083. class BaseSVGFactory {
  17084. create(width, height, skipDimensions = false) {
  17085. if (width <= 0 || height <= 0) {
  17086. throw new Error("Invalid SVG dimensions");
  17087. }
  17088. const svg = this._createSVG("svg:svg");
  17089. svg.setAttribute("version", "1.1");
  17090. if (!skipDimensions) {
  17091. svg.setAttribute("width", `${width}px`);
  17092. svg.setAttribute("height", `${height}px`);
  17093. }
  17094. svg.setAttribute("preserveAspectRatio", "none");
  17095. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  17096. return svg;
  17097. }
  17098. createElement(type) {
  17099. if (typeof type !== "string") {
  17100. throw new Error("Invalid SVG element type");
  17101. }
  17102. return this._createSVG(type);
  17103. }
  17104. _createSVG(type) {
  17105. unreachable("Abstract method `_createSVG` called.");
  17106. }
  17107. }
  17108. class DOMSVGFactory extends BaseSVGFactory {
  17109. _createSVG(type) {
  17110. return document.createElementNS(SVG_NS, type);
  17111. }
  17112. }
  17113. ;// ./src/display/xfa_layer.js
  17114. class XfaLayer {
  17115. static setupStorage(html, id, element, storage, intent) {
  17116. const storedData = storage.getValue(id, {
  17117. value: null
  17118. });
  17119. switch (element.name) {
  17120. case "textarea":
  17121. if (storedData.value !== null) {
  17122. html.textContent = storedData.value;
  17123. }
  17124. if (intent === "print") {
  17125. break;
  17126. }
  17127. html.addEventListener("input", event => {
  17128. storage.setValue(id, {
  17129. value: event.target.value
  17130. });
  17131. });
  17132. break;
  17133. case "input":
  17134. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  17135. if (storedData.value === element.attributes.xfaOn) {
  17136. html.setAttribute("checked", true);
  17137. } else if (storedData.value === element.attributes.xfaOff) {
  17138. html.removeAttribute("checked");
  17139. }
  17140. if (intent === "print") {
  17141. break;
  17142. }
  17143. html.addEventListener("change", event => {
  17144. storage.setValue(id, {
  17145. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  17146. });
  17147. });
  17148. } else {
  17149. if (storedData.value !== null) {
  17150. html.setAttribute("value", storedData.value);
  17151. }
  17152. if (intent === "print") {
  17153. break;
  17154. }
  17155. html.addEventListener("input", event => {
  17156. storage.setValue(id, {
  17157. value: event.target.value
  17158. });
  17159. });
  17160. }
  17161. break;
  17162. case "select":
  17163. if (storedData.value !== null) {
  17164. html.setAttribute("value", storedData.value);
  17165. for (const option of element.children) {
  17166. if (option.attributes.value === storedData.value) {
  17167. option.attributes.selected = true;
  17168. } else if (option.attributes.hasOwnProperty("selected")) {
  17169. delete option.attributes.selected;
  17170. }
  17171. }
  17172. }
  17173. html.addEventListener("input", event => {
  17174. const options = event.target.options;
  17175. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  17176. storage.setValue(id, {
  17177. value
  17178. });
  17179. });
  17180. break;
  17181. }
  17182. }
  17183. static setAttributes({
  17184. html,
  17185. element,
  17186. storage = null,
  17187. intent,
  17188. linkService
  17189. }) {
  17190. const {
  17191. attributes
  17192. } = element;
  17193. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  17194. if (attributes.type === "radio") {
  17195. attributes.name = `${attributes.name}-${intent}`;
  17196. }
  17197. for (const [key, value] of Object.entries(attributes)) {
  17198. if (value === null || value === undefined) {
  17199. continue;
  17200. }
  17201. switch (key) {
  17202. case "class":
  17203. if (value.length) {
  17204. html.setAttribute(key, value.join(" "));
  17205. }
  17206. break;
  17207. case "dataId":
  17208. break;
  17209. case "id":
  17210. html.setAttribute("data-element-id", value);
  17211. break;
  17212. case "style":
  17213. Object.assign(html.style, value);
  17214. break;
  17215. case "textContent":
  17216. html.textContent = value;
  17217. break;
  17218. default:
  17219. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  17220. html.setAttribute(key, value);
  17221. }
  17222. }
  17223. }
  17224. if (isHTMLAnchorElement) {
  17225. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  17226. }
  17227. if (storage && attributes.dataId) {
  17228. this.setupStorage(html, attributes.dataId, element, storage);
  17229. }
  17230. }
  17231. static render(parameters) {
  17232. const storage = parameters.annotationStorage;
  17233. const linkService = parameters.linkService;
  17234. const root = parameters.xfaHtml;
  17235. const intent = parameters.intent || "display";
  17236. const rootHtml = document.createElement(root.name);
  17237. if (root.attributes) {
  17238. this.setAttributes({
  17239. html: rootHtml,
  17240. element: root,
  17241. intent,
  17242. linkService
  17243. });
  17244. }
  17245. const isNotForRichText = intent !== "richText";
  17246. const rootDiv = parameters.div;
  17247. rootDiv.append(rootHtml);
  17248. if (parameters.viewport) {
  17249. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  17250. rootDiv.style.transform = transform;
  17251. }
  17252. if (isNotForRichText) {
  17253. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  17254. }
  17255. const textDivs = [];
  17256. if (root.children.length === 0) {
  17257. if (root.value) {
  17258. const node = document.createTextNode(root.value);
  17259. rootHtml.append(node);
  17260. if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
  17261. textDivs.push(node);
  17262. }
  17263. }
  17264. return {
  17265. textDivs
  17266. };
  17267. }
  17268. const stack = [[root, -1, rootHtml]];
  17269. while (stack.length > 0) {
  17270. const [parent, i, html] = stack.at(-1);
  17271. if (i + 1 === parent.children.length) {
  17272. stack.pop();
  17273. continue;
  17274. }
  17275. const child = parent.children[++stack.at(-1)[1]];
  17276. if (child === null) {
  17277. continue;
  17278. }
  17279. const {
  17280. name
  17281. } = child;
  17282. if (name === "#text") {
  17283. const node = document.createTextNode(child.value);
  17284. textDivs.push(node);
  17285. html.append(node);
  17286. continue;
  17287. }
  17288. const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
  17289. html.append(childHtml);
  17290. if (child.attributes) {
  17291. this.setAttributes({
  17292. html: childHtml,
  17293. element: child,
  17294. storage,
  17295. intent,
  17296. linkService
  17297. });
  17298. }
  17299. if (child.children?.length > 0) {
  17300. stack.push([child, -1, childHtml]);
  17301. } else if (child.value) {
  17302. const node = document.createTextNode(child.value);
  17303. if (isNotForRichText && XfaText.shouldBuildText(name)) {
  17304. textDivs.push(node);
  17305. }
  17306. childHtml.append(node);
  17307. }
  17308. }
  17309. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  17310. el.setAttribute("readOnly", true);
  17311. }
  17312. return {
  17313. textDivs
  17314. };
  17315. }
  17316. static update(parameters) {
  17317. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  17318. parameters.div.style.transform = transform;
  17319. parameters.div.hidden = false;
  17320. }
  17321. }
  17322. ;// ./src/display/annotation_layer.js
  17323. const DEFAULT_TAB_INDEX = 1000;
  17324. const annotation_layer_DEFAULT_FONT_SIZE = 9;
  17325. const GetElementsByNameSet = new WeakSet();
  17326. class AnnotationElementFactory {
  17327. static create(parameters) {
  17328. const subtype = parameters.data.annotationType;
  17329. switch (subtype) {
  17330. case AnnotationType.LINK:
  17331. return new LinkAnnotationElement(parameters);
  17332. case AnnotationType.TEXT:
  17333. return new TextAnnotationElement(parameters);
  17334. case AnnotationType.WIDGET:
  17335. const fieldType = parameters.data.fieldType;
  17336. switch (fieldType) {
  17337. case "Tx":
  17338. return new TextWidgetAnnotationElement(parameters);
  17339. case "Btn":
  17340. if (parameters.data.radioButton) {
  17341. return new RadioButtonWidgetAnnotationElement(parameters);
  17342. } else if (parameters.data.checkBox) {
  17343. return new CheckboxWidgetAnnotationElement(parameters);
  17344. }
  17345. return new PushButtonWidgetAnnotationElement(parameters);
  17346. case "Ch":
  17347. return new ChoiceWidgetAnnotationElement(parameters);
  17348. case "Sig":
  17349. return new SignatureWidgetAnnotationElement(parameters);
  17350. }
  17351. return new WidgetAnnotationElement(parameters);
  17352. case AnnotationType.POPUP:
  17353. return new PopupAnnotationElement(parameters);
  17354. case AnnotationType.FREETEXT:
  17355. return new FreeTextAnnotationElement(parameters);
  17356. case AnnotationType.LINE:
  17357. return new LineAnnotationElement(parameters);
  17358. case AnnotationType.SQUARE:
  17359. return new SquareAnnotationElement(parameters);
  17360. case AnnotationType.CIRCLE:
  17361. return new CircleAnnotationElement(parameters);
  17362. case AnnotationType.POLYLINE:
  17363. return new PolylineAnnotationElement(parameters);
  17364. case AnnotationType.CARET:
  17365. return new CaretAnnotationElement(parameters);
  17366. case AnnotationType.INK:
  17367. return new InkAnnotationElement(parameters);
  17368. case AnnotationType.POLYGON:
  17369. return new PolygonAnnotationElement(parameters);
  17370. case AnnotationType.HIGHLIGHT:
  17371. return new HighlightAnnotationElement(parameters);
  17372. case AnnotationType.UNDERLINE:
  17373. return new UnderlineAnnotationElement(parameters);
  17374. case AnnotationType.SQUIGGLY:
  17375. return new SquigglyAnnotationElement(parameters);
  17376. case AnnotationType.STRIKEOUT:
  17377. return new StrikeOutAnnotationElement(parameters);
  17378. case AnnotationType.STAMP:
  17379. return new StampAnnotationElement(parameters);
  17380. case AnnotationType.FILEATTACHMENT:
  17381. return new FileAttachmentAnnotationElement(parameters);
  17382. default:
  17383. return new AnnotationElement(parameters);
  17384. }
  17385. }
  17386. }
  17387. class AnnotationElement {
  17388. #updates = null;
  17389. #hasBorder = false;
  17390. #popupElement = null;
  17391. constructor(parameters, {
  17392. isRenderable = false,
  17393. ignoreBorder = false,
  17394. createQuadrilaterals = false
  17395. } = {}) {
  17396. this.isRenderable = isRenderable;
  17397. this.data = parameters.data;
  17398. this.layer = parameters.layer;
  17399. this.linkService = parameters.linkService;
  17400. this.downloadManager = parameters.downloadManager;
  17401. this.imageResourcesPath = parameters.imageResourcesPath;
  17402. this.renderForms = parameters.renderForms;
  17403. this.svgFactory = parameters.svgFactory;
  17404. this.annotationStorage = parameters.annotationStorage;
  17405. this.enableScripting = parameters.enableScripting;
  17406. this.hasJSActions = parameters.hasJSActions;
  17407. this._fieldObjects = parameters.fieldObjects;
  17408. this.parent = parameters.parent;
  17409. if (isRenderable) {
  17410. this.container = this._createContainer(ignoreBorder);
  17411. }
  17412. if (createQuadrilaterals) {
  17413. this._createQuadrilaterals();
  17414. }
  17415. }
  17416. static _hasPopupData({
  17417. titleObj,
  17418. contentsObj,
  17419. richText
  17420. }) {
  17421. return !!(titleObj?.str || contentsObj?.str || richText?.str);
  17422. }
  17423. get _isEditable() {
  17424. return this.data.isEditable;
  17425. }
  17426. get hasPopupData() {
  17427. return AnnotationElement._hasPopupData(this.data);
  17428. }
  17429. updateEdited(params) {
  17430. if (!this.container) {
  17431. return;
  17432. }
  17433. this.#updates ||= {
  17434. rect: this.data.rect.slice(0)
  17435. };
  17436. const {
  17437. rect
  17438. } = params;
  17439. if (rect) {
  17440. this.#setRectEdited(rect);
  17441. }
  17442. this.#popupElement?.popup.updateEdited(params);
  17443. }
  17444. resetEdited() {
  17445. if (!this.#updates) {
  17446. return;
  17447. }
  17448. this.#setRectEdited(this.#updates.rect);
  17449. this.#popupElement?.popup.resetEdited();
  17450. this.#updates = null;
  17451. }
  17452. #setRectEdited(rect) {
  17453. const {
  17454. container: {
  17455. style
  17456. },
  17457. data: {
  17458. rect: currentRect,
  17459. rotation
  17460. },
  17461. parent: {
  17462. viewport: {
  17463. rawDims: {
  17464. pageWidth,
  17465. pageHeight,
  17466. pageX,
  17467. pageY
  17468. }
  17469. }
  17470. }
  17471. } = this;
  17472. currentRect?.splice(0, 4, ...rect);
  17473. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  17474. style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
  17475. if (rotation === 0) {
  17476. style.width = `${100 * (rect[2] - rect[0]) / pageWidth}%`;
  17477. style.height = `${100 * (rect[3] - rect[1]) / pageHeight}%`;
  17478. } else {
  17479. this.setRotation(rotation);
  17480. }
  17481. }
  17482. _createContainer(ignoreBorder) {
  17483. const {
  17484. data,
  17485. parent: {
  17486. page,
  17487. viewport
  17488. }
  17489. } = this;
  17490. const container = document.createElement("section");
  17491. container.setAttribute("data-annotation-id", data.id);
  17492. if (!(this instanceof WidgetAnnotationElement)) {
  17493. container.tabIndex = DEFAULT_TAB_INDEX;
  17494. }
  17495. const {
  17496. style
  17497. } = container;
  17498. style.zIndex = this.parent.zIndex++;
  17499. if (data.alternativeText) {
  17500. container.title = data.alternativeText;
  17501. }
  17502. if (data.noRotate) {
  17503. container.classList.add("norotate");
  17504. }
  17505. if (!data.rect || this instanceof PopupAnnotationElement) {
  17506. const {
  17507. rotation
  17508. } = data;
  17509. if (!data.hasOwnCanvas && rotation !== 0) {
  17510. this.setRotation(rotation, container);
  17511. }
  17512. return container;
  17513. }
  17514. const {
  17515. width,
  17516. height
  17517. } = this;
  17518. if (!ignoreBorder && data.borderStyle.width > 0) {
  17519. style.borderWidth = `${data.borderStyle.width}px`;
  17520. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  17521. const verticalRadius = data.borderStyle.verticalCornerRadius;
  17522. if (horizontalRadius > 0 || verticalRadius > 0) {
  17523. const radius = `calc(${horizontalRadius}px * var(--total-scale-factor)) / calc(${verticalRadius}px * var(--total-scale-factor))`;
  17524. style.borderRadius = radius;
  17525. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  17526. const radius = `calc(${width}px * var(--total-scale-factor)) / calc(${height}px * var(--total-scale-factor))`;
  17527. style.borderRadius = radius;
  17528. }
  17529. switch (data.borderStyle.style) {
  17530. case AnnotationBorderStyleType.SOLID:
  17531. style.borderStyle = "solid";
  17532. break;
  17533. case AnnotationBorderStyleType.DASHED:
  17534. style.borderStyle = "dashed";
  17535. break;
  17536. case AnnotationBorderStyleType.BEVELED:
  17537. warn("Unimplemented border style: beveled");
  17538. break;
  17539. case AnnotationBorderStyleType.INSET:
  17540. warn("Unimplemented border style: inset");
  17541. break;
  17542. case AnnotationBorderStyleType.UNDERLINE:
  17543. style.borderBottomStyle = "solid";
  17544. break;
  17545. default:
  17546. break;
  17547. }
  17548. const borderColor = data.borderColor || null;
  17549. if (borderColor) {
  17550. this.#hasBorder = true;
  17551. style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  17552. } else {
  17553. style.borderWidth = 0;
  17554. }
  17555. }
  17556. const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
  17557. const {
  17558. pageWidth,
  17559. pageHeight,
  17560. pageX,
  17561. pageY
  17562. } = viewport.rawDims;
  17563. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  17564. style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
  17565. const {
  17566. rotation
  17567. } = data;
  17568. if (data.hasOwnCanvas || rotation === 0) {
  17569. style.width = `${100 * width / pageWidth}%`;
  17570. style.height = `${100 * height / pageHeight}%`;
  17571. } else {
  17572. this.setRotation(rotation, container);
  17573. }
  17574. return container;
  17575. }
  17576. setRotation(angle, container = this.container) {
  17577. if (!this.data.rect) {
  17578. return;
  17579. }
  17580. const {
  17581. pageWidth,
  17582. pageHeight
  17583. } = this.parent.viewport.rawDims;
  17584. let {
  17585. width,
  17586. height
  17587. } = this;
  17588. if (angle % 180 !== 0) {
  17589. [width, height] = [height, width];
  17590. }
  17591. container.style.width = `${100 * width / pageWidth}%`;
  17592. container.style.height = `${100 * height / pageHeight}%`;
  17593. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  17594. }
  17595. get _commonActions() {
  17596. const setColor = (jsName, styleName, event) => {
  17597. const color = event.detail[jsName];
  17598. const colorType = color[0];
  17599. const colorArray = color.slice(1);
  17600. event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
  17601. this.annotationStorage.setValue(this.data.id, {
  17602. [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
  17603. });
  17604. };
  17605. return shadow(this, "_commonActions", {
  17606. display: event => {
  17607. const {
  17608. display
  17609. } = event.detail;
  17610. const hidden = display % 2 === 1;
  17611. this.container.style.visibility = hidden ? "hidden" : "visible";
  17612. this.annotationStorage.setValue(this.data.id, {
  17613. noView: hidden,
  17614. noPrint: display === 1 || display === 2
  17615. });
  17616. },
  17617. print: event => {
  17618. this.annotationStorage.setValue(this.data.id, {
  17619. noPrint: !event.detail.print
  17620. });
  17621. },
  17622. hidden: event => {
  17623. const {
  17624. hidden
  17625. } = event.detail;
  17626. this.container.style.visibility = hidden ? "hidden" : "visible";
  17627. this.annotationStorage.setValue(this.data.id, {
  17628. noPrint: hidden,
  17629. noView: hidden
  17630. });
  17631. },
  17632. focus: event => {
  17633. setTimeout(() => event.target.focus({
  17634. preventScroll: false
  17635. }), 0);
  17636. },
  17637. userName: event => {
  17638. event.target.title = event.detail.userName;
  17639. },
  17640. readonly: event => {
  17641. event.target.disabled = event.detail.readonly;
  17642. },
  17643. required: event => {
  17644. this._setRequired(event.target, event.detail.required);
  17645. },
  17646. bgColor: event => {
  17647. setColor("bgColor", "backgroundColor", event);
  17648. },
  17649. fillColor: event => {
  17650. setColor("fillColor", "backgroundColor", event);
  17651. },
  17652. fgColor: event => {
  17653. setColor("fgColor", "color", event);
  17654. },
  17655. textColor: event => {
  17656. setColor("textColor", "color", event);
  17657. },
  17658. borderColor: event => {
  17659. setColor("borderColor", "borderColor", event);
  17660. },
  17661. strokeColor: event => {
  17662. setColor("strokeColor", "borderColor", event);
  17663. },
  17664. rotation: event => {
  17665. const angle = event.detail.rotation;
  17666. this.setRotation(angle);
  17667. this.annotationStorage.setValue(this.data.id, {
  17668. rotation: angle
  17669. });
  17670. }
  17671. });
  17672. }
  17673. _dispatchEventFromSandbox(actions, jsEvent) {
  17674. const commonActions = this._commonActions;
  17675. for (const name of Object.keys(jsEvent.detail)) {
  17676. const action = actions[name] || commonActions[name];
  17677. action?.(jsEvent);
  17678. }
  17679. }
  17680. _setDefaultPropertiesFromJS(element) {
  17681. if (!this.enableScripting) {
  17682. return;
  17683. }
  17684. const storedData = this.annotationStorage.getRawValue(this.data.id);
  17685. if (!storedData) {
  17686. return;
  17687. }
  17688. const commonActions = this._commonActions;
  17689. for (const [actionName, detail] of Object.entries(storedData)) {
  17690. const action = commonActions[actionName];
  17691. if (action) {
  17692. const eventProxy = {
  17693. detail: {
  17694. [actionName]: detail
  17695. },
  17696. target: element
  17697. };
  17698. action(eventProxy);
  17699. delete storedData[actionName];
  17700. }
  17701. }
  17702. }
  17703. _createQuadrilaterals() {
  17704. if (!this.container) {
  17705. return;
  17706. }
  17707. const {
  17708. quadPoints
  17709. } = this.data;
  17710. if (!quadPoints) {
  17711. return;
  17712. }
  17713. const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x));
  17714. if (quadPoints.length === 8) {
  17715. const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);
  17716. if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
  17717. return;
  17718. }
  17719. }
  17720. const {
  17721. style
  17722. } = this.container;
  17723. let svgBuffer;
  17724. if (this.#hasBorder) {
  17725. const {
  17726. borderColor,
  17727. borderWidth
  17728. } = style;
  17729. style.borderWidth = 0;
  17730. svgBuffer = ["url('data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`];
  17731. this.container.classList.add("hasBorder");
  17732. }
  17733. const width = rectTrX - rectBlX;
  17734. const height = rectTrY - rectBlY;
  17735. const {
  17736. svgFactory
  17737. } = this;
  17738. const svg = svgFactory.createElement("svg");
  17739. svg.classList.add("quadrilateralsContainer");
  17740. svg.setAttribute("width", 0);
  17741. svg.setAttribute("height", 0);
  17742. const defs = svgFactory.createElement("defs");
  17743. svg.append(defs);
  17744. const clipPath = svgFactory.createElement("clipPath");
  17745. const id = `clippath_${this.data.id}`;
  17746. clipPath.setAttribute("id", id);
  17747. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  17748. defs.append(clipPath);
  17749. for (let i = 2, ii = quadPoints.length; i < ii; i += 8) {
  17750. const trX = quadPoints[i];
  17751. const trY = quadPoints[i + 1];
  17752. const blX = quadPoints[i + 2];
  17753. const blY = quadPoints[i + 3];
  17754. const rect = svgFactory.createElement("rect");
  17755. const x = (blX - rectBlX) / width;
  17756. const y = (rectTrY - trY) / height;
  17757. const rectWidth = (trX - blX) / width;
  17758. const rectHeight = (trY - blY) / height;
  17759. rect.setAttribute("x", x);
  17760. rect.setAttribute("y", y);
  17761. rect.setAttribute("width", rectWidth);
  17762. rect.setAttribute("height", rectHeight);
  17763. clipPath.append(rect);
  17764. svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);
  17765. }
  17766. if (this.#hasBorder) {
  17767. svgBuffer.push(`</g></svg>')`);
  17768. style.backgroundImage = svgBuffer.join("");
  17769. }
  17770. this.container.append(svg);
  17771. this.container.style.clipPath = `url(#${id})`;
  17772. }
  17773. _createPopup() {
  17774. const {
  17775. data
  17776. } = this;
  17777. const popup = this.#popupElement = new PopupAnnotationElement({
  17778. data: {
  17779. color: data.color,
  17780. titleObj: data.titleObj,
  17781. modificationDate: data.modificationDate,
  17782. contentsObj: data.contentsObj,
  17783. richText: data.richText,
  17784. parentRect: data.rect,
  17785. borderStyle: 0,
  17786. id: `popup_${data.id}`,
  17787. rotation: data.rotation
  17788. },
  17789. parent: this.parent,
  17790. elements: [this]
  17791. });
  17792. this.parent.div.append(popup.render());
  17793. }
  17794. render() {
  17795. unreachable("Abstract method `AnnotationElement.render` called");
  17796. }
  17797. _getElementsByName(name, skipId = null) {
  17798. const fields = [];
  17799. if (this._fieldObjects) {
  17800. const fieldObj = this._fieldObjects[name];
  17801. if (fieldObj) {
  17802. for (const {
  17803. page,
  17804. id,
  17805. exportValues
  17806. } of fieldObj) {
  17807. if (page === -1) {
  17808. continue;
  17809. }
  17810. if (id === skipId) {
  17811. continue;
  17812. }
  17813. const exportValue = typeof exportValues === "string" ? exportValues : null;
  17814. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  17815. if (domElement && !GetElementsByNameSet.has(domElement)) {
  17816. warn(`_getElementsByName - element not allowed: ${id}`);
  17817. continue;
  17818. }
  17819. fields.push({
  17820. id,
  17821. exportValue,
  17822. domElement
  17823. });
  17824. }
  17825. }
  17826. return fields;
  17827. }
  17828. for (const domElement of document.getElementsByName(name)) {
  17829. const {
  17830. exportValue
  17831. } = domElement;
  17832. const id = domElement.getAttribute("data-element-id");
  17833. if (id === skipId) {
  17834. continue;
  17835. }
  17836. if (!GetElementsByNameSet.has(domElement)) {
  17837. continue;
  17838. }
  17839. fields.push({
  17840. id,
  17841. exportValue,
  17842. domElement
  17843. });
  17844. }
  17845. return fields;
  17846. }
  17847. show() {
  17848. if (this.container) {
  17849. this.container.hidden = false;
  17850. }
  17851. this.popup?.maybeShow();
  17852. }
  17853. hide() {
  17854. if (this.container) {
  17855. this.container.hidden = true;
  17856. }
  17857. this.popup?.forceHide();
  17858. }
  17859. getElementsToTriggerPopup() {
  17860. return this.container;
  17861. }
  17862. addHighlightArea() {
  17863. const triggers = this.getElementsToTriggerPopup();
  17864. if (Array.isArray(triggers)) {
  17865. for (const element of triggers) {
  17866. element.classList.add("highlightArea");
  17867. }
  17868. } else {
  17869. triggers.classList.add("highlightArea");
  17870. }
  17871. }
  17872. _editOnDoubleClick() {
  17873. if (!this._isEditable) {
  17874. return;
  17875. }
  17876. const {
  17877. annotationEditorType: mode,
  17878. data: {
  17879. id: editId
  17880. }
  17881. } = this;
  17882. this.container.addEventListener("dblclick", () => {
  17883. this.linkService.eventBus?.dispatch("switchannotationeditormode", {
  17884. source: this,
  17885. mode,
  17886. editId
  17887. });
  17888. });
  17889. }
  17890. get width() {
  17891. return this.data.rect[2] - this.data.rect[0];
  17892. }
  17893. get height() {
  17894. return this.data.rect[3] - this.data.rect[1];
  17895. }
  17896. }
  17897. class LinkAnnotationElement extends AnnotationElement {
  17898. constructor(parameters, options = null) {
  17899. super(parameters, {
  17900. isRenderable: true,
  17901. ignoreBorder: !!options?.ignoreBorder,
  17902. createQuadrilaterals: true
  17903. });
  17904. this.isTooltipOnly = parameters.data.isTooltipOnly;
  17905. }
  17906. render() {
  17907. const {
  17908. data,
  17909. linkService
  17910. } = this;
  17911. const link = document.createElement("a");
  17912. link.setAttribute("data-element-id", data.id);
  17913. let isBound = false;
  17914. if (data.url) {
  17915. linkService.addLinkAttributes(link, data.url, data.newWindow);
  17916. isBound = true;
  17917. } else if (data.action) {
  17918. this._bindNamedAction(link, data.action);
  17919. isBound = true;
  17920. } else if (data.attachment) {
  17921. this.#bindAttachment(link, data.attachment, data.attachmentDest);
  17922. isBound = true;
  17923. } else if (data.setOCGState) {
  17924. this.#bindSetOCGState(link, data.setOCGState);
  17925. isBound = true;
  17926. } else if (data.dest) {
  17927. this._bindLink(link, data.dest);
  17928. isBound = true;
  17929. } else {
  17930. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  17931. this._bindJSAction(link, data);
  17932. isBound = true;
  17933. }
  17934. if (data.resetForm) {
  17935. this._bindResetFormAction(link, data.resetForm);
  17936. isBound = true;
  17937. } else if (this.isTooltipOnly && !isBound) {
  17938. this._bindLink(link, "");
  17939. isBound = true;
  17940. }
  17941. }
  17942. this.container.classList.add("linkAnnotation");
  17943. if (isBound) {
  17944. this.container.append(link);
  17945. }
  17946. return this.container;
  17947. }
  17948. #setInternalLink() {
  17949. this.container.setAttribute("data-internal-link", "");
  17950. }
  17951. _bindLink(link, destination) {
  17952. link.href = this.linkService.getDestinationHash(destination);
  17953. link.onclick = () => {
  17954. if (destination) {
  17955. this.linkService.goToDestination(destination);
  17956. }
  17957. return false;
  17958. };
  17959. if (destination || destination === "") {
  17960. this.#setInternalLink();
  17961. }
  17962. }
  17963. _bindNamedAction(link, action) {
  17964. link.href = this.linkService.getAnchorUrl("");
  17965. link.onclick = () => {
  17966. this.linkService.executeNamedAction(action);
  17967. return false;
  17968. };
  17969. this.#setInternalLink();
  17970. }
  17971. #bindAttachment(link, attachment, dest = null) {
  17972. link.href = this.linkService.getAnchorUrl("");
  17973. if (attachment.description) {
  17974. link.title = attachment.description;
  17975. }
  17976. link.onclick = () => {
  17977. this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
  17978. return false;
  17979. };
  17980. this.#setInternalLink();
  17981. }
  17982. #bindSetOCGState(link, action) {
  17983. link.href = this.linkService.getAnchorUrl("");
  17984. link.onclick = () => {
  17985. this.linkService.executeSetOCGState(action);
  17986. return false;
  17987. };
  17988. this.#setInternalLink();
  17989. }
  17990. _bindJSAction(link, data) {
  17991. link.href = this.linkService.getAnchorUrl("");
  17992. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  17993. for (const name of Object.keys(data.actions)) {
  17994. const jsName = map.get(name);
  17995. if (!jsName) {
  17996. continue;
  17997. }
  17998. link[jsName] = () => {
  17999. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18000. source: this,
  18001. detail: {
  18002. id: data.id,
  18003. name
  18004. }
  18005. });
  18006. return false;
  18007. };
  18008. }
  18009. if (!link.onclick) {
  18010. link.onclick = () => false;
  18011. }
  18012. this.#setInternalLink();
  18013. }
  18014. _bindResetFormAction(link, resetForm) {
  18015. const otherClickAction = link.onclick;
  18016. if (!otherClickAction) {
  18017. link.href = this.linkService.getAnchorUrl("");
  18018. }
  18019. this.#setInternalLink();
  18020. if (!this._fieldObjects) {
  18021. warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  18022. if (!otherClickAction) {
  18023. link.onclick = () => false;
  18024. }
  18025. return;
  18026. }
  18027. link.onclick = () => {
  18028. otherClickAction?.();
  18029. const {
  18030. fields: resetFormFields,
  18031. refs: resetFormRefs,
  18032. include
  18033. } = resetForm;
  18034. const allFields = [];
  18035. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  18036. const fieldIds = new Set(resetFormRefs);
  18037. for (const fieldName of resetFormFields) {
  18038. const fields = this._fieldObjects[fieldName] || [];
  18039. for (const {
  18040. id
  18041. } of fields) {
  18042. fieldIds.add(id);
  18043. }
  18044. }
  18045. for (const fields of Object.values(this._fieldObjects)) {
  18046. for (const field of fields) {
  18047. if (fieldIds.has(field.id) === include) {
  18048. allFields.push(field);
  18049. }
  18050. }
  18051. }
  18052. } else {
  18053. for (const fields of Object.values(this._fieldObjects)) {
  18054. allFields.push(...fields);
  18055. }
  18056. }
  18057. const storage = this.annotationStorage;
  18058. const allIds = [];
  18059. for (const field of allFields) {
  18060. const {
  18061. id
  18062. } = field;
  18063. allIds.push(id);
  18064. switch (field.type) {
  18065. case "text":
  18066. {
  18067. const value = field.defaultValue || "";
  18068. storage.setValue(id, {
  18069. value
  18070. });
  18071. break;
  18072. }
  18073. case "checkbox":
  18074. case "radiobutton":
  18075. {
  18076. const value = field.defaultValue === field.exportValues;
  18077. storage.setValue(id, {
  18078. value
  18079. });
  18080. break;
  18081. }
  18082. case "combobox":
  18083. case "listbox":
  18084. {
  18085. const value = field.defaultValue || "";
  18086. storage.setValue(id, {
  18087. value
  18088. });
  18089. break;
  18090. }
  18091. default:
  18092. continue;
  18093. }
  18094. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  18095. if (!domElement) {
  18096. continue;
  18097. } else if (!GetElementsByNameSet.has(domElement)) {
  18098. warn(`_bindResetFormAction - element not allowed: ${id}`);
  18099. continue;
  18100. }
  18101. domElement.dispatchEvent(new Event("resetform"));
  18102. }
  18103. if (this.enableScripting) {
  18104. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18105. source: this,
  18106. detail: {
  18107. id: "app",
  18108. ids: allIds,
  18109. name: "ResetForm"
  18110. }
  18111. });
  18112. }
  18113. return false;
  18114. };
  18115. }
  18116. }
  18117. class TextAnnotationElement extends AnnotationElement {
  18118. constructor(parameters) {
  18119. super(parameters, {
  18120. isRenderable: true
  18121. });
  18122. }
  18123. render() {
  18124. this.container.classList.add("textAnnotation");
  18125. const image = document.createElement("img");
  18126. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  18127. image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
  18128. image.setAttribute("data-l10n-args", JSON.stringify({
  18129. type: this.data.name
  18130. }));
  18131. if (!this.data.popupRef && this.hasPopupData) {
  18132. this._createPopup();
  18133. }
  18134. this.container.append(image);
  18135. return this.container;
  18136. }
  18137. }
  18138. class WidgetAnnotationElement extends AnnotationElement {
  18139. render() {
  18140. return this.container;
  18141. }
  18142. showElementAndHideCanvas(element) {
  18143. if (this.data.hasOwnCanvas) {
  18144. if (element.previousSibling?.nodeName === "CANVAS") {
  18145. element.previousSibling.hidden = true;
  18146. }
  18147. element.hidden = false;
  18148. }
  18149. }
  18150. _getKeyModifier(event) {
  18151. return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
  18152. }
  18153. _setEventListener(element, elementData, baseName, eventName, valueGetter) {
  18154. if (baseName.includes("mouse")) {
  18155. element.addEventListener(baseName, event => {
  18156. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18157. source: this,
  18158. detail: {
  18159. id: this.data.id,
  18160. name: eventName,
  18161. value: valueGetter(event),
  18162. shift: event.shiftKey,
  18163. modifier: this._getKeyModifier(event)
  18164. }
  18165. });
  18166. });
  18167. } else {
  18168. element.addEventListener(baseName, event => {
  18169. if (baseName === "blur") {
  18170. if (!elementData.focused || !event.relatedTarget) {
  18171. return;
  18172. }
  18173. elementData.focused = false;
  18174. } else if (baseName === "focus") {
  18175. if (elementData.focused) {
  18176. return;
  18177. }
  18178. elementData.focused = true;
  18179. }
  18180. if (!valueGetter) {
  18181. return;
  18182. }
  18183. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18184. source: this,
  18185. detail: {
  18186. id: this.data.id,
  18187. name: eventName,
  18188. value: valueGetter(event)
  18189. }
  18190. });
  18191. });
  18192. }
  18193. }
  18194. _setEventListeners(element, elementData, names, getter) {
  18195. for (const [baseName, eventName] of names) {
  18196. if (eventName === "Action" || this.data.actions?.[eventName]) {
  18197. if (eventName === "Focus" || eventName === "Blur") {
  18198. elementData ||= {
  18199. focused: false
  18200. };
  18201. }
  18202. this._setEventListener(element, elementData, baseName, eventName, getter);
  18203. if (eventName === "Focus" && !this.data.actions?.Blur) {
  18204. this._setEventListener(element, elementData, "blur", "Blur", null);
  18205. } else if (eventName === "Blur" && !this.data.actions?.Focus) {
  18206. this._setEventListener(element, elementData, "focus", "Focus", null);
  18207. }
  18208. }
  18209. }
  18210. }
  18211. _setBackgroundColor(element) {
  18212. const color = this.data.backgroundColor || null;
  18213. element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);
  18214. }
  18215. _setTextStyle(element) {
  18216. const TEXT_ALIGNMENT = ["left", "center", "right"];
  18217. const {
  18218. fontColor
  18219. } = this.data.defaultAppearanceData;
  18220. const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
  18221. const style = element.style;
  18222. let computedFontSize;
  18223. const BORDER_SIZE = 2;
  18224. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  18225. if (this.data.multiLine) {
  18226. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  18227. const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
  18228. const lineHeight = height / numberOfLines;
  18229. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
  18230. } else {
  18231. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  18232. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
  18233. }
  18234. style.fontSize = `calc(${computedFontSize}px * var(--total-scale-factor))`;
  18235. style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  18236. if (this.data.textAlignment !== null) {
  18237. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  18238. }
  18239. }
  18240. _setRequired(element, isRequired) {
  18241. if (isRequired) {
  18242. element.setAttribute("required", true);
  18243. } else {
  18244. element.removeAttribute("required");
  18245. }
  18246. element.setAttribute("aria-required", isRequired);
  18247. }
  18248. }
  18249. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  18250. constructor(parameters) {
  18251. const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  18252. super(parameters, {
  18253. isRenderable
  18254. });
  18255. }
  18256. setPropertyOnSiblings(base, key, value, keyInStorage) {
  18257. const storage = this.annotationStorage;
  18258. for (const element of this._getElementsByName(base.name, base.id)) {
  18259. if (element.domElement) {
  18260. element.domElement[key] = value;
  18261. }
  18262. storage.setValue(element.id, {
  18263. [keyInStorage]: value
  18264. });
  18265. }
  18266. }
  18267. render() {
  18268. const storage = this.annotationStorage;
  18269. const id = this.data.id;
  18270. this.container.classList.add("textWidgetAnnotation");
  18271. let element = null;
  18272. if (this.renderForms) {
  18273. const storedData = storage.getValue(id, {
  18274. value: this.data.fieldValue
  18275. });
  18276. let textContent = storedData.value || "";
  18277. const maxLen = storage.getValue(id, {
  18278. charLimit: this.data.maxLen
  18279. }).charLimit;
  18280. if (maxLen && textContent.length > maxLen) {
  18281. textContent = textContent.slice(0, maxLen);
  18282. }
  18283. let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
  18284. if (fieldFormattedValues && this.data.comb) {
  18285. fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
  18286. }
  18287. const elementData = {
  18288. userValue: textContent,
  18289. formattedValue: fieldFormattedValues,
  18290. lastCommittedValue: null,
  18291. commitKey: 1,
  18292. focused: false
  18293. };
  18294. if (this.data.multiLine) {
  18295. element = document.createElement("textarea");
  18296. element.textContent = fieldFormattedValues ?? textContent;
  18297. if (this.data.doNotScroll) {
  18298. element.style.overflowY = "hidden";
  18299. }
  18300. } else {
  18301. element = document.createElement("input");
  18302. element.type = this.data.password ? "password" : "text";
  18303. element.setAttribute("value", fieldFormattedValues ?? textContent);
  18304. if (this.data.doNotScroll) {
  18305. element.style.overflowX = "hidden";
  18306. }
  18307. }
  18308. if (this.data.hasOwnCanvas) {
  18309. element.hidden = true;
  18310. }
  18311. GetElementsByNameSet.add(element);
  18312. element.setAttribute("data-element-id", id);
  18313. element.disabled = this.data.readOnly;
  18314. element.name = this.data.fieldName;
  18315. element.tabIndex = DEFAULT_TAB_INDEX;
  18316. this._setRequired(element, this.data.required);
  18317. if (maxLen) {
  18318. element.maxLength = maxLen;
  18319. }
  18320. element.addEventListener("input", event => {
  18321. storage.setValue(id, {
  18322. value: event.target.value
  18323. });
  18324. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  18325. elementData.formattedValue = null;
  18326. });
  18327. element.addEventListener("resetform", event => {
  18328. const defaultValue = this.data.defaultFieldValue ?? "";
  18329. element.value = elementData.userValue = defaultValue;
  18330. elementData.formattedValue = null;
  18331. });
  18332. let blurListener = event => {
  18333. const {
  18334. formattedValue
  18335. } = elementData;
  18336. if (formattedValue !== null && formattedValue !== undefined) {
  18337. event.target.value = formattedValue;
  18338. }
  18339. event.target.scrollLeft = 0;
  18340. };
  18341. if (this.enableScripting && this.hasJSActions) {
  18342. element.addEventListener("focus", event => {
  18343. if (elementData.focused) {
  18344. return;
  18345. }
  18346. const {
  18347. target
  18348. } = event;
  18349. if (elementData.userValue) {
  18350. target.value = elementData.userValue;
  18351. }
  18352. elementData.lastCommittedValue = target.value;
  18353. elementData.commitKey = 1;
  18354. if (!this.data.actions?.Focus) {
  18355. elementData.focused = true;
  18356. }
  18357. });
  18358. element.addEventListener("updatefromsandbox", jsEvent => {
  18359. this.showElementAndHideCanvas(jsEvent.target);
  18360. const actions = {
  18361. value(event) {
  18362. elementData.userValue = event.detail.value ?? "";
  18363. storage.setValue(id, {
  18364. value: elementData.userValue.toString()
  18365. });
  18366. event.target.value = elementData.userValue;
  18367. },
  18368. formattedValue(event) {
  18369. const {
  18370. formattedValue
  18371. } = event.detail;
  18372. elementData.formattedValue = formattedValue;
  18373. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  18374. event.target.value = formattedValue;
  18375. }
  18376. storage.setValue(id, {
  18377. formattedValue
  18378. });
  18379. },
  18380. selRange(event) {
  18381. event.target.setSelectionRange(...event.detail.selRange);
  18382. },
  18383. charLimit: event => {
  18384. const {
  18385. charLimit
  18386. } = event.detail;
  18387. const {
  18388. target
  18389. } = event;
  18390. if (charLimit === 0) {
  18391. target.removeAttribute("maxLength");
  18392. return;
  18393. }
  18394. target.setAttribute("maxLength", charLimit);
  18395. let value = elementData.userValue;
  18396. if (!value || value.length <= charLimit) {
  18397. return;
  18398. }
  18399. value = value.slice(0, charLimit);
  18400. target.value = elementData.userValue = value;
  18401. storage.setValue(id, {
  18402. value
  18403. });
  18404. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18405. source: this,
  18406. detail: {
  18407. id,
  18408. name: "Keystroke",
  18409. value,
  18410. willCommit: true,
  18411. commitKey: 1,
  18412. selStart: target.selectionStart,
  18413. selEnd: target.selectionEnd
  18414. }
  18415. });
  18416. }
  18417. };
  18418. this._dispatchEventFromSandbox(actions, jsEvent);
  18419. });
  18420. element.addEventListener("keydown", event => {
  18421. elementData.commitKey = 1;
  18422. let commitKey = -1;
  18423. if (event.key === "Escape") {
  18424. commitKey = 0;
  18425. } else if (event.key === "Enter" && !this.data.multiLine) {
  18426. commitKey = 2;
  18427. } else if (event.key === "Tab") {
  18428. elementData.commitKey = 3;
  18429. }
  18430. if (commitKey === -1) {
  18431. return;
  18432. }
  18433. const {
  18434. value
  18435. } = event.target;
  18436. if (elementData.lastCommittedValue === value) {
  18437. return;
  18438. }
  18439. elementData.lastCommittedValue = value;
  18440. elementData.userValue = value;
  18441. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18442. source: this,
  18443. detail: {
  18444. id,
  18445. name: "Keystroke",
  18446. value,
  18447. willCommit: true,
  18448. commitKey,
  18449. selStart: event.target.selectionStart,
  18450. selEnd: event.target.selectionEnd
  18451. }
  18452. });
  18453. });
  18454. const _blurListener = blurListener;
  18455. blurListener = null;
  18456. element.addEventListener("blur", event => {
  18457. if (!elementData.focused || !event.relatedTarget) {
  18458. return;
  18459. }
  18460. if (!this.data.actions?.Blur) {
  18461. elementData.focused = false;
  18462. }
  18463. const {
  18464. value
  18465. } = event.target;
  18466. elementData.userValue = value;
  18467. if (elementData.lastCommittedValue !== value) {
  18468. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18469. source: this,
  18470. detail: {
  18471. id,
  18472. name: "Keystroke",
  18473. value,
  18474. willCommit: true,
  18475. commitKey: elementData.commitKey,
  18476. selStart: event.target.selectionStart,
  18477. selEnd: event.target.selectionEnd
  18478. }
  18479. });
  18480. }
  18481. _blurListener(event);
  18482. });
  18483. if (this.data.actions?.Keystroke) {
  18484. element.addEventListener("beforeinput", event => {
  18485. elementData.lastCommittedValue = null;
  18486. const {
  18487. data,
  18488. target
  18489. } = event;
  18490. const {
  18491. value,
  18492. selectionStart,
  18493. selectionEnd
  18494. } = target;
  18495. let selStart = selectionStart,
  18496. selEnd = selectionEnd;
  18497. switch (event.inputType) {
  18498. case "deleteWordBackward":
  18499. {
  18500. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  18501. if (match) {
  18502. selStart -= match[0].length;
  18503. }
  18504. break;
  18505. }
  18506. case "deleteWordForward":
  18507. {
  18508. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  18509. if (match) {
  18510. selEnd += match[0].length;
  18511. }
  18512. break;
  18513. }
  18514. case "deleteContentBackward":
  18515. if (selectionStart === selectionEnd) {
  18516. selStart -= 1;
  18517. }
  18518. break;
  18519. case "deleteContentForward":
  18520. if (selectionStart === selectionEnd) {
  18521. selEnd += 1;
  18522. }
  18523. break;
  18524. }
  18525. event.preventDefault();
  18526. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18527. source: this,
  18528. detail: {
  18529. id,
  18530. name: "Keystroke",
  18531. value,
  18532. change: data || "",
  18533. willCommit: false,
  18534. selStart,
  18535. selEnd
  18536. }
  18537. });
  18538. });
  18539. }
  18540. this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  18541. }
  18542. if (blurListener) {
  18543. element.addEventListener("blur", blurListener);
  18544. }
  18545. if (this.data.comb) {
  18546. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  18547. const combWidth = fieldWidth / maxLen;
  18548. element.classList.add("comb");
  18549. element.style.letterSpacing = `calc(${combWidth}px * var(--total-scale-factor) - 1ch)`;
  18550. }
  18551. } else {
  18552. element = document.createElement("div");
  18553. element.textContent = this.data.fieldValue;
  18554. element.style.verticalAlign = "middle";
  18555. element.style.display = "table-cell";
  18556. if (this.data.hasOwnCanvas) {
  18557. element.hidden = true;
  18558. }
  18559. }
  18560. this._setTextStyle(element);
  18561. this._setBackgroundColor(element);
  18562. this._setDefaultPropertiesFromJS(element);
  18563. this.container.append(element);
  18564. return this.container;
  18565. }
  18566. }
  18567. class SignatureWidgetAnnotationElement extends WidgetAnnotationElement {
  18568. constructor(parameters) {
  18569. super(parameters, {
  18570. isRenderable: !!parameters.data.hasOwnCanvas
  18571. });
  18572. }
  18573. }
  18574. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  18575. constructor(parameters) {
  18576. super(parameters, {
  18577. isRenderable: parameters.renderForms
  18578. });
  18579. }
  18580. render() {
  18581. const storage = this.annotationStorage;
  18582. const data = this.data;
  18583. const id = data.id;
  18584. let value = storage.getValue(id, {
  18585. value: data.exportValue === data.fieldValue
  18586. }).value;
  18587. if (typeof value === "string") {
  18588. value = value !== "Off";
  18589. storage.setValue(id, {
  18590. value
  18591. });
  18592. }
  18593. this.container.classList.add("buttonWidgetAnnotation", "checkBox");
  18594. const element = document.createElement("input");
  18595. GetElementsByNameSet.add(element);
  18596. element.setAttribute("data-element-id", id);
  18597. element.disabled = data.readOnly;
  18598. this._setRequired(element, this.data.required);
  18599. element.type = "checkbox";
  18600. element.name = data.fieldName;
  18601. if (value) {
  18602. element.setAttribute("checked", true);
  18603. }
  18604. element.setAttribute("exportValue", data.exportValue);
  18605. element.tabIndex = DEFAULT_TAB_INDEX;
  18606. element.addEventListener("change", event => {
  18607. const {
  18608. name,
  18609. checked
  18610. } = event.target;
  18611. for (const checkbox of this._getElementsByName(name, id)) {
  18612. const curChecked = checked && checkbox.exportValue === data.exportValue;
  18613. if (checkbox.domElement) {
  18614. checkbox.domElement.checked = curChecked;
  18615. }
  18616. storage.setValue(checkbox.id, {
  18617. value: curChecked
  18618. });
  18619. }
  18620. storage.setValue(id, {
  18621. value: checked
  18622. });
  18623. });
  18624. element.addEventListener("resetform", event => {
  18625. const defaultValue = data.defaultFieldValue || "Off";
  18626. event.target.checked = defaultValue === data.exportValue;
  18627. });
  18628. if (this.enableScripting && this.hasJSActions) {
  18629. element.addEventListener("updatefromsandbox", jsEvent => {
  18630. const actions = {
  18631. value(event) {
  18632. event.target.checked = event.detail.value !== "Off";
  18633. storage.setValue(id, {
  18634. value: event.target.checked
  18635. });
  18636. }
  18637. };
  18638. this._dispatchEventFromSandbox(actions, jsEvent);
  18639. });
  18640. this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
  18641. }
  18642. this._setBackgroundColor(element);
  18643. this._setDefaultPropertiesFromJS(element);
  18644. this.container.append(element);
  18645. return this.container;
  18646. }
  18647. }
  18648. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  18649. constructor(parameters) {
  18650. super(parameters, {
  18651. isRenderable: parameters.renderForms
  18652. });
  18653. }
  18654. render() {
  18655. this.container.classList.add("buttonWidgetAnnotation", "radioButton");
  18656. const storage = this.annotationStorage;
  18657. const data = this.data;
  18658. const id = data.id;
  18659. let value = storage.getValue(id, {
  18660. value: data.fieldValue === data.buttonValue
  18661. }).value;
  18662. if (typeof value === "string") {
  18663. value = value !== data.buttonValue;
  18664. storage.setValue(id, {
  18665. value
  18666. });
  18667. }
  18668. if (value) {
  18669. for (const radio of this._getElementsByName(data.fieldName, id)) {
  18670. storage.setValue(radio.id, {
  18671. value: false
  18672. });
  18673. }
  18674. }
  18675. const element = document.createElement("input");
  18676. GetElementsByNameSet.add(element);
  18677. element.setAttribute("data-element-id", id);
  18678. element.disabled = data.readOnly;
  18679. this._setRequired(element, this.data.required);
  18680. element.type = "radio";
  18681. element.name = data.fieldName;
  18682. if (value) {
  18683. element.setAttribute("checked", true);
  18684. }
  18685. element.tabIndex = DEFAULT_TAB_INDEX;
  18686. element.addEventListener("change", event => {
  18687. const {
  18688. name,
  18689. checked
  18690. } = event.target;
  18691. for (const radio of this._getElementsByName(name, id)) {
  18692. storage.setValue(radio.id, {
  18693. value: false
  18694. });
  18695. }
  18696. storage.setValue(id, {
  18697. value: checked
  18698. });
  18699. });
  18700. element.addEventListener("resetform", event => {
  18701. const defaultValue = data.defaultFieldValue;
  18702. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  18703. });
  18704. if (this.enableScripting && this.hasJSActions) {
  18705. const pdfButtonValue = data.buttonValue;
  18706. element.addEventListener("updatefromsandbox", jsEvent => {
  18707. const actions = {
  18708. value: event => {
  18709. const checked = pdfButtonValue === event.detail.value;
  18710. for (const radio of this._getElementsByName(event.target.name)) {
  18711. const curChecked = checked && radio.id === id;
  18712. if (radio.domElement) {
  18713. radio.domElement.checked = curChecked;
  18714. }
  18715. storage.setValue(radio.id, {
  18716. value: curChecked
  18717. });
  18718. }
  18719. }
  18720. };
  18721. this._dispatchEventFromSandbox(actions, jsEvent);
  18722. });
  18723. this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
  18724. }
  18725. this._setBackgroundColor(element);
  18726. this._setDefaultPropertiesFromJS(element);
  18727. this.container.append(element);
  18728. return this.container;
  18729. }
  18730. }
  18731. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  18732. constructor(parameters) {
  18733. super(parameters, {
  18734. ignoreBorder: parameters.data.hasAppearance
  18735. });
  18736. }
  18737. render() {
  18738. const container = super.render();
  18739. container.classList.add("buttonWidgetAnnotation", "pushButton");
  18740. const linkElement = container.lastChild;
  18741. if (this.enableScripting && this.hasJSActions && linkElement) {
  18742. this._setDefaultPropertiesFromJS(linkElement);
  18743. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  18744. this._dispatchEventFromSandbox({}, jsEvent);
  18745. });
  18746. }
  18747. return container;
  18748. }
  18749. }
  18750. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  18751. constructor(parameters) {
  18752. super(parameters, {
  18753. isRenderable: parameters.renderForms
  18754. });
  18755. }
  18756. render() {
  18757. this.container.classList.add("choiceWidgetAnnotation");
  18758. const storage = this.annotationStorage;
  18759. const id = this.data.id;
  18760. const storedData = storage.getValue(id, {
  18761. value: this.data.fieldValue
  18762. });
  18763. const selectElement = document.createElement("select");
  18764. GetElementsByNameSet.add(selectElement);
  18765. selectElement.setAttribute("data-element-id", id);
  18766. selectElement.disabled = this.data.readOnly;
  18767. this._setRequired(selectElement, this.data.required);
  18768. selectElement.name = this.data.fieldName;
  18769. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  18770. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  18771. if (!this.data.combo) {
  18772. selectElement.size = this.data.options.length;
  18773. if (this.data.multiSelect) {
  18774. selectElement.multiple = true;
  18775. }
  18776. }
  18777. selectElement.addEventListener("resetform", event => {
  18778. const defaultValue = this.data.defaultFieldValue;
  18779. for (const option of selectElement.options) {
  18780. option.selected = option.value === defaultValue;
  18781. }
  18782. });
  18783. for (const option of this.data.options) {
  18784. const optionElement = document.createElement("option");
  18785. optionElement.textContent = option.displayValue;
  18786. optionElement.value = option.exportValue;
  18787. if (storedData.value.includes(option.exportValue)) {
  18788. optionElement.setAttribute("selected", true);
  18789. addAnEmptyEntry = false;
  18790. }
  18791. selectElement.append(optionElement);
  18792. }
  18793. let removeEmptyEntry = null;
  18794. if (addAnEmptyEntry) {
  18795. const noneOptionElement = document.createElement("option");
  18796. noneOptionElement.value = " ";
  18797. noneOptionElement.setAttribute("hidden", true);
  18798. noneOptionElement.setAttribute("selected", true);
  18799. selectElement.prepend(noneOptionElement);
  18800. removeEmptyEntry = () => {
  18801. noneOptionElement.remove();
  18802. selectElement.removeEventListener("input", removeEmptyEntry);
  18803. removeEmptyEntry = null;
  18804. };
  18805. selectElement.addEventListener("input", removeEmptyEntry);
  18806. }
  18807. const getValue = isExport => {
  18808. const name = isExport ? "value" : "textContent";
  18809. const {
  18810. options,
  18811. multiple
  18812. } = selectElement;
  18813. if (!multiple) {
  18814. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  18815. }
  18816. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  18817. };
  18818. let selectedValues = getValue(false);
  18819. const getItems = event => {
  18820. const options = event.target.options;
  18821. return Array.prototype.map.call(options, option => ({
  18822. displayValue: option.textContent,
  18823. exportValue: option.value
  18824. }));
  18825. };
  18826. if (this.enableScripting && this.hasJSActions) {
  18827. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  18828. const actions = {
  18829. value(event) {
  18830. removeEmptyEntry?.();
  18831. const value = event.detail.value;
  18832. const values = new Set(Array.isArray(value) ? value : [value]);
  18833. for (const option of selectElement.options) {
  18834. option.selected = values.has(option.value);
  18835. }
  18836. storage.setValue(id, {
  18837. value: getValue(true)
  18838. });
  18839. selectedValues = getValue(false);
  18840. },
  18841. multipleSelection(event) {
  18842. selectElement.multiple = true;
  18843. },
  18844. remove(event) {
  18845. const options = selectElement.options;
  18846. const index = event.detail.remove;
  18847. options[index].selected = false;
  18848. selectElement.remove(index);
  18849. if (options.length > 0) {
  18850. const i = Array.prototype.findIndex.call(options, option => option.selected);
  18851. if (i === -1) {
  18852. options[0].selected = true;
  18853. }
  18854. }
  18855. storage.setValue(id, {
  18856. value: getValue(true),
  18857. items: getItems(event)
  18858. });
  18859. selectedValues = getValue(false);
  18860. },
  18861. clear(event) {
  18862. while (selectElement.length !== 0) {
  18863. selectElement.remove(0);
  18864. }
  18865. storage.setValue(id, {
  18866. value: null,
  18867. items: []
  18868. });
  18869. selectedValues = getValue(false);
  18870. },
  18871. insert(event) {
  18872. const {
  18873. index,
  18874. displayValue,
  18875. exportValue
  18876. } = event.detail.insert;
  18877. const selectChild = selectElement.children[index];
  18878. const optionElement = document.createElement("option");
  18879. optionElement.textContent = displayValue;
  18880. optionElement.value = exportValue;
  18881. if (selectChild) {
  18882. selectChild.before(optionElement);
  18883. } else {
  18884. selectElement.append(optionElement);
  18885. }
  18886. storage.setValue(id, {
  18887. value: getValue(true),
  18888. items: getItems(event)
  18889. });
  18890. selectedValues = getValue(false);
  18891. },
  18892. items(event) {
  18893. const {
  18894. items
  18895. } = event.detail;
  18896. while (selectElement.length !== 0) {
  18897. selectElement.remove(0);
  18898. }
  18899. for (const item of items) {
  18900. const {
  18901. displayValue,
  18902. exportValue
  18903. } = item;
  18904. const optionElement = document.createElement("option");
  18905. optionElement.textContent = displayValue;
  18906. optionElement.value = exportValue;
  18907. selectElement.append(optionElement);
  18908. }
  18909. if (selectElement.options.length > 0) {
  18910. selectElement.options[0].selected = true;
  18911. }
  18912. storage.setValue(id, {
  18913. value: getValue(true),
  18914. items: getItems(event)
  18915. });
  18916. selectedValues = getValue(false);
  18917. },
  18918. indices(event) {
  18919. const indices = new Set(event.detail.indices);
  18920. for (const option of event.target.options) {
  18921. option.selected = indices.has(option.index);
  18922. }
  18923. storage.setValue(id, {
  18924. value: getValue(true)
  18925. });
  18926. selectedValues = getValue(false);
  18927. },
  18928. editable(event) {
  18929. event.target.disabled = !event.detail.editable;
  18930. }
  18931. };
  18932. this._dispatchEventFromSandbox(actions, jsEvent);
  18933. });
  18934. selectElement.addEventListener("input", event => {
  18935. const exportValue = getValue(true);
  18936. const change = getValue(false);
  18937. storage.setValue(id, {
  18938. value: exportValue
  18939. });
  18940. event.preventDefault();
  18941. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18942. source: this,
  18943. detail: {
  18944. id,
  18945. name: "Keystroke",
  18946. value: selectedValues,
  18947. change,
  18948. changeEx: exportValue,
  18949. willCommit: false,
  18950. commitKey: 1,
  18951. keyDown: false
  18952. }
  18953. });
  18954. });
  18955. this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);
  18956. } else {
  18957. selectElement.addEventListener("input", function (event) {
  18958. storage.setValue(id, {
  18959. value: getValue(true)
  18960. });
  18961. });
  18962. }
  18963. if (this.data.combo) {
  18964. this._setTextStyle(selectElement);
  18965. } else {}
  18966. this._setBackgroundColor(selectElement);
  18967. this._setDefaultPropertiesFromJS(selectElement);
  18968. this.container.append(selectElement);
  18969. return this.container;
  18970. }
  18971. }
  18972. class PopupAnnotationElement extends AnnotationElement {
  18973. constructor(parameters) {
  18974. const {
  18975. data,
  18976. elements
  18977. } = parameters;
  18978. super(parameters, {
  18979. isRenderable: AnnotationElement._hasPopupData(data)
  18980. });
  18981. this.elements = elements;
  18982. this.popup = null;
  18983. }
  18984. render() {
  18985. this.container.classList.add("popupAnnotation");
  18986. const popup = this.popup = new PopupElement({
  18987. container: this.container,
  18988. color: this.data.color,
  18989. titleObj: this.data.titleObj,
  18990. modificationDate: this.data.modificationDate,
  18991. contentsObj: this.data.contentsObj,
  18992. richText: this.data.richText,
  18993. rect: this.data.rect,
  18994. parentRect: this.data.parentRect || null,
  18995. parent: this.parent,
  18996. elements: this.elements,
  18997. open: this.data.open
  18998. });
  18999. const elementIds = [];
  19000. for (const element of this.elements) {
  19001. element.popup = popup;
  19002. element.container.ariaHasPopup = "dialog";
  19003. elementIds.push(element.data.id);
  19004. element.addHighlightArea();
  19005. }
  19006. this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(","));
  19007. return this.container;
  19008. }
  19009. }
  19010. class PopupElement {
  19011. #boundKeyDown = this.#keyDown.bind(this);
  19012. #boundHide = this.#hide.bind(this);
  19013. #boundShow = this.#show.bind(this);
  19014. #boundToggle = this.#toggle.bind(this);
  19015. #color = null;
  19016. #container = null;
  19017. #contentsObj = null;
  19018. #dateObj = null;
  19019. #elements = null;
  19020. #parent = null;
  19021. #parentRect = null;
  19022. #pinned = false;
  19023. #popup = null;
  19024. #position = null;
  19025. #rect = null;
  19026. #richText = null;
  19027. #titleObj = null;
  19028. #updates = null;
  19029. #wasVisible = false;
  19030. constructor({
  19031. container,
  19032. color,
  19033. elements,
  19034. titleObj,
  19035. modificationDate,
  19036. contentsObj,
  19037. richText,
  19038. parent,
  19039. rect,
  19040. parentRect,
  19041. open
  19042. }) {
  19043. this.#container = container;
  19044. this.#titleObj = titleObj;
  19045. this.#contentsObj = contentsObj;
  19046. this.#richText = richText;
  19047. this.#parent = parent;
  19048. this.#color = color;
  19049. this.#rect = rect;
  19050. this.#parentRect = parentRect;
  19051. this.#elements = elements;
  19052. this.#dateObj = PDFDateString.toDateObject(modificationDate);
  19053. this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());
  19054. for (const element of this.trigger) {
  19055. element.addEventListener("click", this.#boundToggle);
  19056. element.addEventListener("mouseenter", this.#boundShow);
  19057. element.addEventListener("mouseleave", this.#boundHide);
  19058. element.classList.add("popupTriggerArea");
  19059. }
  19060. for (const element of elements) {
  19061. element.container?.addEventListener("keydown", this.#boundKeyDown);
  19062. }
  19063. this.#container.hidden = true;
  19064. if (open) {
  19065. this.#toggle();
  19066. }
  19067. }
  19068. render() {
  19069. if (this.#popup) {
  19070. return;
  19071. }
  19072. const popup = this.#popup = document.createElement("div");
  19073. popup.className = "popup";
  19074. if (this.#color) {
  19075. const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
  19076. popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
  19077. }
  19078. const header = document.createElement("span");
  19079. header.className = "header";
  19080. const title = document.createElement("h1");
  19081. header.append(title);
  19082. ({
  19083. dir: title.dir,
  19084. str: title.textContent
  19085. } = this.#titleObj);
  19086. popup.append(header);
  19087. if (this.#dateObj) {
  19088. const modificationDate = document.createElement("span");
  19089. modificationDate.classList.add("popupDate");
  19090. modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");
  19091. modificationDate.setAttribute("data-l10n-args", JSON.stringify({
  19092. dateObj: this.#dateObj.valueOf()
  19093. }));
  19094. header.append(modificationDate);
  19095. }
  19096. const html = this.#html;
  19097. if (html) {
  19098. XfaLayer.render({
  19099. xfaHtml: html,
  19100. intent: "richText",
  19101. div: popup
  19102. });
  19103. popup.lastChild.classList.add("richText", "popupContent");
  19104. } else {
  19105. const contents = this._formatContents(this.#contentsObj);
  19106. popup.append(contents);
  19107. }
  19108. this.#container.append(popup);
  19109. }
  19110. get #html() {
  19111. const richText = this.#richText;
  19112. const contentsObj = this.#contentsObj;
  19113. if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
  19114. return this.#richText.html || null;
  19115. }
  19116. return null;
  19117. }
  19118. get #fontSize() {
  19119. return this.#html?.attributes?.style?.fontSize || 0;
  19120. }
  19121. get #fontColor() {
  19122. return this.#html?.attributes?.style?.color || null;
  19123. }
  19124. #makePopupContent(text) {
  19125. const popupLines = [];
  19126. const popupContent = {
  19127. str: text,
  19128. html: {
  19129. name: "div",
  19130. attributes: {
  19131. dir: "auto"
  19132. },
  19133. children: [{
  19134. name: "p",
  19135. children: popupLines
  19136. }]
  19137. }
  19138. };
  19139. const lineAttributes = {
  19140. style: {
  19141. color: this.#fontColor,
  19142. fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--total-scale-factor))` : ""
  19143. }
  19144. };
  19145. for (const line of text.split("\n")) {
  19146. popupLines.push({
  19147. name: "span",
  19148. value: line,
  19149. attributes: lineAttributes
  19150. });
  19151. }
  19152. return popupContent;
  19153. }
  19154. _formatContents({
  19155. str,
  19156. dir
  19157. }) {
  19158. const p = document.createElement("p");
  19159. p.classList.add("popupContent");
  19160. p.dir = dir;
  19161. const lines = str.split(/(?:\r\n?|\n)/);
  19162. for (let i = 0, ii = lines.length; i < ii; ++i) {
  19163. const line = lines[i];
  19164. p.append(document.createTextNode(line));
  19165. if (i < ii - 1) {
  19166. p.append(document.createElement("br"));
  19167. }
  19168. }
  19169. return p;
  19170. }
  19171. #keyDown(event) {
  19172. if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
  19173. return;
  19174. }
  19175. if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
  19176. this.#toggle();
  19177. }
  19178. }
  19179. updateEdited({
  19180. rect,
  19181. popupContent
  19182. }) {
  19183. this.#updates ||= {
  19184. contentsObj: this.#contentsObj,
  19185. richText: this.#richText
  19186. };
  19187. if (rect) {
  19188. this.#position = null;
  19189. }
  19190. if (popupContent) {
  19191. this.#richText = this.#makePopupContent(popupContent);
  19192. this.#contentsObj = null;
  19193. }
  19194. this.#popup?.remove();
  19195. this.#popup = null;
  19196. }
  19197. resetEdited() {
  19198. if (!this.#updates) {
  19199. return;
  19200. }
  19201. ({
  19202. contentsObj: this.#contentsObj,
  19203. richText: this.#richText
  19204. } = this.#updates);
  19205. this.#updates = null;
  19206. this.#popup?.remove();
  19207. this.#popup = null;
  19208. this.#position = null;
  19209. }
  19210. #setPosition() {
  19211. if (this.#position !== null) {
  19212. return;
  19213. }
  19214. const {
  19215. page: {
  19216. view
  19217. },
  19218. viewport: {
  19219. rawDims: {
  19220. pageWidth,
  19221. pageHeight,
  19222. pageX,
  19223. pageY
  19224. }
  19225. }
  19226. } = this.#parent;
  19227. let useParentRect = !!this.#parentRect;
  19228. let rect = useParentRect ? this.#parentRect : this.#rect;
  19229. for (const element of this.#elements) {
  19230. if (!rect || Util.intersect(element.data.rect, rect) !== null) {
  19231. rect = element.data.rect;
  19232. useParentRect = true;
  19233. break;
  19234. }
  19235. }
  19236. const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
  19237. const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
  19238. const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
  19239. const popupLeft = normalizedRect[0] + parentWidth;
  19240. const popupTop = normalizedRect[1];
  19241. this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
  19242. const {
  19243. style
  19244. } = this.#container;
  19245. style.left = `${this.#position[0]}%`;
  19246. style.top = `${this.#position[1]}%`;
  19247. }
  19248. #toggle() {
  19249. this.#pinned = !this.#pinned;
  19250. if (this.#pinned) {
  19251. this.#show();
  19252. this.#container.addEventListener("click", this.#boundToggle);
  19253. this.#container.addEventListener("keydown", this.#boundKeyDown);
  19254. } else {
  19255. this.#hide();
  19256. this.#container.removeEventListener("click", this.#boundToggle);
  19257. this.#container.removeEventListener("keydown", this.#boundKeyDown);
  19258. }
  19259. }
  19260. #show() {
  19261. if (!this.#popup) {
  19262. this.render();
  19263. }
  19264. if (!this.isVisible) {
  19265. this.#setPosition();
  19266. this.#container.hidden = false;
  19267. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;
  19268. } else if (this.#pinned) {
  19269. this.#container.classList.add("focused");
  19270. }
  19271. }
  19272. #hide() {
  19273. this.#container.classList.remove("focused");
  19274. if (this.#pinned || !this.isVisible) {
  19275. return;
  19276. }
  19277. this.#container.hidden = true;
  19278. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;
  19279. }
  19280. forceHide() {
  19281. this.#wasVisible = this.isVisible;
  19282. if (!this.#wasVisible) {
  19283. return;
  19284. }
  19285. this.#container.hidden = true;
  19286. }
  19287. maybeShow() {
  19288. if (!this.#wasVisible) {
  19289. return;
  19290. }
  19291. if (!this.#popup) {
  19292. this.#show();
  19293. }
  19294. this.#wasVisible = false;
  19295. this.#container.hidden = false;
  19296. }
  19297. get isVisible() {
  19298. return this.#container.hidden === false;
  19299. }
  19300. }
  19301. class FreeTextAnnotationElement extends AnnotationElement {
  19302. constructor(parameters) {
  19303. super(parameters, {
  19304. isRenderable: true,
  19305. ignoreBorder: true
  19306. });
  19307. this.textContent = parameters.data.textContent;
  19308. this.textPosition = parameters.data.textPosition;
  19309. this.annotationEditorType = AnnotationEditorType.FREETEXT;
  19310. }
  19311. render() {
  19312. this.container.classList.add("freeTextAnnotation");
  19313. if (this.textContent) {
  19314. const content = document.createElement("div");
  19315. content.classList.add("annotationTextContent");
  19316. content.setAttribute("role", "comment");
  19317. for (const line of this.textContent) {
  19318. const lineSpan = document.createElement("span");
  19319. lineSpan.textContent = line;
  19320. content.append(lineSpan);
  19321. }
  19322. this.container.append(content);
  19323. }
  19324. if (!this.data.popupRef && this.hasPopupData) {
  19325. this._createPopup();
  19326. }
  19327. this._editOnDoubleClick();
  19328. return this.container;
  19329. }
  19330. }
  19331. class LineAnnotationElement extends AnnotationElement {
  19332. #line = null;
  19333. constructor(parameters) {
  19334. super(parameters, {
  19335. isRenderable: true,
  19336. ignoreBorder: true
  19337. });
  19338. }
  19339. render() {
  19340. this.container.classList.add("lineAnnotation");
  19341. const {
  19342. data,
  19343. width,
  19344. height
  19345. } = this;
  19346. const svg = this.svgFactory.create(width, height, true);
  19347. const line = this.#line = this.svgFactory.createElement("svg:line");
  19348. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  19349. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  19350. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  19351. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  19352. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  19353. line.setAttribute("stroke", "transparent");
  19354. line.setAttribute("fill", "transparent");
  19355. svg.append(line);
  19356. this.container.append(svg);
  19357. if (!data.popupRef && this.hasPopupData) {
  19358. this._createPopup();
  19359. }
  19360. return this.container;
  19361. }
  19362. getElementsToTriggerPopup() {
  19363. return this.#line;
  19364. }
  19365. addHighlightArea() {
  19366. this.container.classList.add("highlightArea");
  19367. }
  19368. }
  19369. class SquareAnnotationElement extends AnnotationElement {
  19370. #square = null;
  19371. constructor(parameters) {
  19372. super(parameters, {
  19373. isRenderable: true,
  19374. ignoreBorder: true
  19375. });
  19376. }
  19377. render() {
  19378. this.container.classList.add("squareAnnotation");
  19379. const {
  19380. data,
  19381. width,
  19382. height
  19383. } = this;
  19384. const svg = this.svgFactory.create(width, height, true);
  19385. const borderWidth = data.borderStyle.width;
  19386. const square = this.#square = this.svgFactory.createElement("svg:rect");
  19387. square.setAttribute("x", borderWidth / 2);
  19388. square.setAttribute("y", borderWidth / 2);
  19389. square.setAttribute("width", width - borderWidth);
  19390. square.setAttribute("height", height - borderWidth);
  19391. square.setAttribute("stroke-width", borderWidth || 1);
  19392. square.setAttribute("stroke", "transparent");
  19393. square.setAttribute("fill", "transparent");
  19394. svg.append(square);
  19395. this.container.append(svg);
  19396. if (!data.popupRef && this.hasPopupData) {
  19397. this._createPopup();
  19398. }
  19399. return this.container;
  19400. }
  19401. getElementsToTriggerPopup() {
  19402. return this.#square;
  19403. }
  19404. addHighlightArea() {
  19405. this.container.classList.add("highlightArea");
  19406. }
  19407. }
  19408. class CircleAnnotationElement extends AnnotationElement {
  19409. #circle = null;
  19410. constructor(parameters) {
  19411. super(parameters, {
  19412. isRenderable: true,
  19413. ignoreBorder: true
  19414. });
  19415. }
  19416. render() {
  19417. this.container.classList.add("circleAnnotation");
  19418. const {
  19419. data,
  19420. width,
  19421. height
  19422. } = this;
  19423. const svg = this.svgFactory.create(width, height, true);
  19424. const borderWidth = data.borderStyle.width;
  19425. const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
  19426. circle.setAttribute("cx", width / 2);
  19427. circle.setAttribute("cy", height / 2);
  19428. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  19429. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  19430. circle.setAttribute("stroke-width", borderWidth || 1);
  19431. circle.setAttribute("stroke", "transparent");
  19432. circle.setAttribute("fill", "transparent");
  19433. svg.append(circle);
  19434. this.container.append(svg);
  19435. if (!data.popupRef && this.hasPopupData) {
  19436. this._createPopup();
  19437. }
  19438. return this.container;
  19439. }
  19440. getElementsToTriggerPopup() {
  19441. return this.#circle;
  19442. }
  19443. addHighlightArea() {
  19444. this.container.classList.add("highlightArea");
  19445. }
  19446. }
  19447. class PolylineAnnotationElement extends AnnotationElement {
  19448. #polyline = null;
  19449. constructor(parameters) {
  19450. super(parameters, {
  19451. isRenderable: true,
  19452. ignoreBorder: true
  19453. });
  19454. this.containerClassName = "polylineAnnotation";
  19455. this.svgElementName = "svg:polyline";
  19456. }
  19457. render() {
  19458. this.container.classList.add(this.containerClassName);
  19459. const {
  19460. data: {
  19461. rect,
  19462. vertices,
  19463. borderStyle,
  19464. popupRef
  19465. },
  19466. width,
  19467. height
  19468. } = this;
  19469. if (!vertices) {
  19470. return this.container;
  19471. }
  19472. const svg = this.svgFactory.create(width, height, true);
  19473. let points = [];
  19474. for (let i = 0, ii = vertices.length; i < ii; i += 2) {
  19475. const x = vertices[i] - rect[0];
  19476. const y = rect[3] - vertices[i + 1];
  19477. points.push(`${x},${y}`);
  19478. }
  19479. points = points.join(" ");
  19480. const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
  19481. polyline.setAttribute("points", points);
  19482. polyline.setAttribute("stroke-width", borderStyle.width || 1);
  19483. polyline.setAttribute("stroke", "transparent");
  19484. polyline.setAttribute("fill", "transparent");
  19485. svg.append(polyline);
  19486. this.container.append(svg);
  19487. if (!popupRef && this.hasPopupData) {
  19488. this._createPopup();
  19489. }
  19490. return this.container;
  19491. }
  19492. getElementsToTriggerPopup() {
  19493. return this.#polyline;
  19494. }
  19495. addHighlightArea() {
  19496. this.container.classList.add("highlightArea");
  19497. }
  19498. }
  19499. class PolygonAnnotationElement extends PolylineAnnotationElement {
  19500. constructor(parameters) {
  19501. super(parameters);
  19502. this.containerClassName = "polygonAnnotation";
  19503. this.svgElementName = "svg:polygon";
  19504. }
  19505. }
  19506. class CaretAnnotationElement extends AnnotationElement {
  19507. constructor(parameters) {
  19508. super(parameters, {
  19509. isRenderable: true,
  19510. ignoreBorder: true
  19511. });
  19512. }
  19513. render() {
  19514. this.container.classList.add("caretAnnotation");
  19515. if (!this.data.popupRef && this.hasPopupData) {
  19516. this._createPopup();
  19517. }
  19518. return this.container;
  19519. }
  19520. }
  19521. class InkAnnotationElement extends AnnotationElement {
  19522. #polylinesGroupElement = null;
  19523. #polylines = [];
  19524. constructor(parameters) {
  19525. super(parameters, {
  19526. isRenderable: true,
  19527. ignoreBorder: true
  19528. });
  19529. this.containerClassName = "inkAnnotation";
  19530. this.svgElementName = "svg:polyline";
  19531. this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;
  19532. }
  19533. #getTransform(rotation, rect) {
  19534. switch (rotation) {
  19535. case 90:
  19536. return {
  19537. transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`,
  19538. width: rect[3] - rect[1],
  19539. height: rect[2] - rect[0]
  19540. };
  19541. case 180:
  19542. return {
  19543. transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`,
  19544. width: rect[2] - rect[0],
  19545. height: rect[3] - rect[1]
  19546. };
  19547. case 270:
  19548. return {
  19549. transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`,
  19550. width: rect[3] - rect[1],
  19551. height: rect[2] - rect[0]
  19552. };
  19553. default:
  19554. return {
  19555. transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`,
  19556. width: rect[2] - rect[0],
  19557. height: rect[3] - rect[1]
  19558. };
  19559. }
  19560. }
  19561. render() {
  19562. this.container.classList.add(this.containerClassName);
  19563. const {
  19564. data: {
  19565. rect,
  19566. rotation,
  19567. inkLists,
  19568. borderStyle,
  19569. popupRef
  19570. }
  19571. } = this;
  19572. const {
  19573. transform,
  19574. width,
  19575. height
  19576. } = this.#getTransform(rotation, rect);
  19577. const svg = this.svgFactory.create(width, height, true);
  19578. const g = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g");
  19579. svg.append(g);
  19580. g.setAttribute("stroke-width", borderStyle.width || 1);
  19581. g.setAttribute("stroke-linecap", "round");
  19582. g.setAttribute("stroke-linejoin", "round");
  19583. g.setAttribute("stroke-miterlimit", 10);
  19584. g.setAttribute("stroke", "transparent");
  19585. g.setAttribute("fill", "transparent");
  19586. g.setAttribute("transform", transform);
  19587. for (let i = 0, ii = inkLists.length; i < ii; i++) {
  19588. const polyline = this.svgFactory.createElement(this.svgElementName);
  19589. this.#polylines.push(polyline);
  19590. polyline.setAttribute("points", inkLists[i].join(","));
  19591. g.append(polyline);
  19592. }
  19593. if (!popupRef && this.hasPopupData) {
  19594. this._createPopup();
  19595. }
  19596. this.container.append(svg);
  19597. this._editOnDoubleClick();
  19598. return this.container;
  19599. }
  19600. updateEdited(params) {
  19601. super.updateEdited(params);
  19602. const {
  19603. thickness,
  19604. points,
  19605. rect
  19606. } = params;
  19607. const g = this.#polylinesGroupElement;
  19608. if (thickness >= 0) {
  19609. g.setAttribute("stroke-width", thickness || 1);
  19610. }
  19611. if (points) {
  19612. for (let i = 0, ii = this.#polylines.length; i < ii; i++) {
  19613. this.#polylines[i].setAttribute("points", points[i].join(","));
  19614. }
  19615. }
  19616. if (rect) {
  19617. const {
  19618. transform,
  19619. width,
  19620. height
  19621. } = this.#getTransform(this.data.rotation, rect);
  19622. const root = g.parentElement;
  19623. root.setAttribute("viewBox", `0 0 ${width} ${height}`);
  19624. g.setAttribute("transform", transform);
  19625. }
  19626. }
  19627. getElementsToTriggerPopup() {
  19628. return this.#polylines;
  19629. }
  19630. addHighlightArea() {
  19631. this.container.classList.add("highlightArea");
  19632. }
  19633. }
  19634. class HighlightAnnotationElement extends AnnotationElement {
  19635. constructor(parameters) {
  19636. super(parameters, {
  19637. isRenderable: true,
  19638. ignoreBorder: true,
  19639. createQuadrilaterals: true
  19640. });
  19641. this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;
  19642. }
  19643. render() {
  19644. if (!this.data.popupRef && this.hasPopupData) {
  19645. this._createPopup();
  19646. }
  19647. this.container.classList.add("highlightAnnotation");
  19648. this._editOnDoubleClick();
  19649. return this.container;
  19650. }
  19651. }
  19652. class UnderlineAnnotationElement extends AnnotationElement {
  19653. constructor(parameters) {
  19654. super(parameters, {
  19655. isRenderable: true,
  19656. ignoreBorder: true,
  19657. createQuadrilaterals: true
  19658. });
  19659. }
  19660. render() {
  19661. if (!this.data.popupRef && this.hasPopupData) {
  19662. this._createPopup();
  19663. }
  19664. this.container.classList.add("underlineAnnotation");
  19665. return this.container;
  19666. }
  19667. }
  19668. class SquigglyAnnotationElement extends AnnotationElement {
  19669. constructor(parameters) {
  19670. super(parameters, {
  19671. isRenderable: true,
  19672. ignoreBorder: true,
  19673. createQuadrilaterals: true
  19674. });
  19675. }
  19676. render() {
  19677. if (!this.data.popupRef && this.hasPopupData) {
  19678. this._createPopup();
  19679. }
  19680. this.container.classList.add("squigglyAnnotation");
  19681. return this.container;
  19682. }
  19683. }
  19684. class StrikeOutAnnotationElement extends AnnotationElement {
  19685. constructor(parameters) {
  19686. super(parameters, {
  19687. isRenderable: true,
  19688. ignoreBorder: true,
  19689. createQuadrilaterals: true
  19690. });
  19691. }
  19692. render() {
  19693. if (!this.data.popupRef && this.hasPopupData) {
  19694. this._createPopup();
  19695. }
  19696. this.container.classList.add("strikeoutAnnotation");
  19697. return this.container;
  19698. }
  19699. }
  19700. class StampAnnotationElement extends AnnotationElement {
  19701. constructor(parameters) {
  19702. super(parameters, {
  19703. isRenderable: true,
  19704. ignoreBorder: true
  19705. });
  19706. this.annotationEditorType = AnnotationEditorType.STAMP;
  19707. }
  19708. render() {
  19709. this.container.classList.add("stampAnnotation");
  19710. this.container.setAttribute("role", "img");
  19711. if (!this.data.popupRef && this.hasPopupData) {
  19712. this._createPopup();
  19713. }
  19714. this._editOnDoubleClick();
  19715. return this.container;
  19716. }
  19717. }
  19718. class FileAttachmentAnnotationElement extends AnnotationElement {
  19719. #trigger = null;
  19720. constructor(parameters) {
  19721. super(parameters, {
  19722. isRenderable: true
  19723. });
  19724. const {
  19725. file
  19726. } = this.data;
  19727. this.filename = file.filename;
  19728. this.content = file.content;
  19729. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  19730. source: this,
  19731. ...file
  19732. });
  19733. }
  19734. render() {
  19735. this.container.classList.add("fileAttachmentAnnotation");
  19736. const {
  19737. container,
  19738. data
  19739. } = this;
  19740. let trigger;
  19741. if (data.hasAppearance || data.fillAlpha === 0) {
  19742. trigger = document.createElement("div");
  19743. } else {
  19744. trigger = document.createElement("img");
  19745. trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
  19746. if (data.fillAlpha && data.fillAlpha < 1) {
  19747. trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
  19748. }
  19749. }
  19750. trigger.addEventListener("dblclick", this.#download.bind(this));
  19751. this.#trigger = trigger;
  19752. const {
  19753. isMac
  19754. } = util_FeatureTest.platform;
  19755. container.addEventListener("keydown", evt => {
  19756. if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
  19757. this.#download();
  19758. }
  19759. });
  19760. if (!data.popupRef && this.hasPopupData) {
  19761. this._createPopup();
  19762. } else {
  19763. trigger.classList.add("popupTriggerArea");
  19764. }
  19765. container.append(trigger);
  19766. return container;
  19767. }
  19768. getElementsToTriggerPopup() {
  19769. return this.#trigger;
  19770. }
  19771. addHighlightArea() {
  19772. this.container.classList.add("highlightArea");
  19773. }
  19774. #download() {
  19775. this.downloadManager?.openOrDownloadData(this.content, this.filename);
  19776. }
  19777. }
  19778. class AnnotationLayer {
  19779. #accessibilityManager = null;
  19780. #annotationCanvasMap = null;
  19781. #editableAnnotations = new Map();
  19782. #structTreeLayer = null;
  19783. constructor({
  19784. div,
  19785. accessibilityManager,
  19786. annotationCanvasMap,
  19787. annotationEditorUIManager,
  19788. page,
  19789. viewport,
  19790. structTreeLayer
  19791. }) {
  19792. this.div = div;
  19793. this.#accessibilityManager = accessibilityManager;
  19794. this.#annotationCanvasMap = annotationCanvasMap;
  19795. this.#structTreeLayer = structTreeLayer || null;
  19796. this.page = page;
  19797. this.viewport = viewport;
  19798. this.zIndex = 0;
  19799. this._annotationEditorUIManager = annotationEditorUIManager;
  19800. }
  19801. hasEditableAnnotations() {
  19802. return this.#editableAnnotations.size > 0;
  19803. }
  19804. async #appendElement(element, id) {
  19805. const contentElement = element.firstChild || element;
  19806. const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;
  19807. const ariaAttributes = await this.#structTreeLayer?.getAriaAttributes(annotationId);
  19808. if (ariaAttributes) {
  19809. for (const [key, value] of ariaAttributes) {
  19810. contentElement.setAttribute(key, value);
  19811. }
  19812. }
  19813. this.div.append(element);
  19814. this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false);
  19815. }
  19816. async render(params) {
  19817. const {
  19818. annotations
  19819. } = params;
  19820. const layer = this.div;
  19821. setLayerDimensions(layer, this.viewport);
  19822. const popupToElements = new Map();
  19823. const elementParams = {
  19824. data: null,
  19825. layer,
  19826. linkService: params.linkService,
  19827. downloadManager: params.downloadManager,
  19828. imageResourcesPath: params.imageResourcesPath || "",
  19829. renderForms: params.renderForms !== false,
  19830. svgFactory: new DOMSVGFactory(),
  19831. annotationStorage: params.annotationStorage || new AnnotationStorage(),
  19832. enableScripting: params.enableScripting === true,
  19833. hasJSActions: params.hasJSActions,
  19834. fieldObjects: params.fieldObjects,
  19835. parent: this,
  19836. elements: null
  19837. };
  19838. for (const data of annotations) {
  19839. if (data.noHTML) {
  19840. continue;
  19841. }
  19842. const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
  19843. if (!isPopupAnnotation) {
  19844. if (data.rect[2] === data.rect[0] || data.rect[3] === data.rect[1]) {
  19845. continue;
  19846. }
  19847. } else {
  19848. const elements = popupToElements.get(data.id);
  19849. if (!elements) {
  19850. continue;
  19851. }
  19852. elementParams.elements = elements;
  19853. }
  19854. elementParams.data = data;
  19855. const element = AnnotationElementFactory.create(elementParams);
  19856. if (!element.isRenderable) {
  19857. continue;
  19858. }
  19859. if (!isPopupAnnotation && data.popupRef) {
  19860. const elements = popupToElements.get(data.popupRef);
  19861. if (!elements) {
  19862. popupToElements.set(data.popupRef, [element]);
  19863. } else {
  19864. elements.push(element);
  19865. }
  19866. }
  19867. const rendered = element.render();
  19868. if (data.hidden) {
  19869. rendered.style.visibility = "hidden";
  19870. }
  19871. await this.#appendElement(rendered, data.id);
  19872. if (element._isEditable) {
  19873. this.#editableAnnotations.set(element.data.id, element);
  19874. this._annotationEditorUIManager?.renderAnnotationElement(element);
  19875. }
  19876. }
  19877. this.#setAnnotationCanvasMap();
  19878. }
  19879. async addLinkAnnotations(annotations, linkService) {
  19880. const elementParams = {
  19881. data: null,
  19882. layer: this.div,
  19883. linkService,
  19884. svgFactory: new DOMSVGFactory(),
  19885. parent: this
  19886. };
  19887. for (const data of annotations) {
  19888. data.borderStyle ||= AnnotationLayer._defaultBorderStyle;
  19889. elementParams.data = data;
  19890. const element = AnnotationElementFactory.create(elementParams);
  19891. if (!element.isRenderable) {
  19892. continue;
  19893. }
  19894. const rendered = element.render();
  19895. await this.#appendElement(rendered, data.id);
  19896. }
  19897. }
  19898. update({
  19899. viewport
  19900. }) {
  19901. const layer = this.div;
  19902. this.viewport = viewport;
  19903. setLayerDimensions(layer, {
  19904. rotation: viewport.rotation
  19905. });
  19906. this.#setAnnotationCanvasMap();
  19907. layer.hidden = false;
  19908. }
  19909. #setAnnotationCanvasMap() {
  19910. if (!this.#annotationCanvasMap) {
  19911. return;
  19912. }
  19913. const layer = this.div;
  19914. for (const [id, canvas] of this.#annotationCanvasMap) {
  19915. const element = layer.querySelector(`[data-annotation-id="${id}"]`);
  19916. if (!element) {
  19917. continue;
  19918. }
  19919. canvas.className = "annotationContent";
  19920. const {
  19921. firstChild
  19922. } = element;
  19923. if (!firstChild) {
  19924. element.append(canvas);
  19925. } else if (firstChild.nodeName === "CANVAS") {
  19926. firstChild.replaceWith(canvas);
  19927. } else if (!firstChild.classList.contains("annotationContent")) {
  19928. firstChild.before(canvas);
  19929. } else {
  19930. firstChild.after(canvas);
  19931. }
  19932. const editableAnnotation = this.#editableAnnotations.get(id);
  19933. if (!editableAnnotation) {
  19934. continue;
  19935. }
  19936. if (editableAnnotation._hasNoCanvas) {
  19937. this._annotationEditorUIManager?.setMissingCanvas(id, element.id, canvas);
  19938. editableAnnotation._hasNoCanvas = false;
  19939. } else {
  19940. editableAnnotation.canvas = canvas;
  19941. }
  19942. }
  19943. this.#annotationCanvasMap.clear();
  19944. }
  19945. getEditableAnnotations() {
  19946. return Array.from(this.#editableAnnotations.values());
  19947. }
  19948. getEditableAnnotation(id) {
  19949. return this.#editableAnnotations.get(id);
  19950. }
  19951. static get _defaultBorderStyle() {
  19952. return shadow(this, "_defaultBorderStyle", Object.freeze({
  19953. width: 1,
  19954. rawWidth: 1,
  19955. style: AnnotationBorderStyleType.SOLID,
  19956. dashArray: [3],
  19957. horizontalCornerRadius: 0,
  19958. verticalCornerRadius: 0
  19959. }));
  19960. }
  19961. }
  19962. ;// ./src/display/editor/freetext.js
  19963. const EOL_PATTERN = /\r\n?|\n/g;
  19964. class FreeTextEditor extends AnnotationEditor {
  19965. #color;
  19966. #content = "";
  19967. #editorDivId = `${this.id}-editor`;
  19968. #editModeAC = null;
  19969. #fontSize;
  19970. static _freeTextDefaultContent = "";
  19971. static _internalPadding = 0;
  19972. static _defaultColor = null;
  19973. static _defaultFontSize = 10;
  19974. static get _keyboardManager() {
  19975. const proto = FreeTextEditor.prototype;
  19976. const arrowChecker = self => self.isEmpty();
  19977. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  19978. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  19979. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
  19980. bubbles: true
  19981. }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
  19982. args: [-small, 0],
  19983. checker: arrowChecker
  19984. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
  19985. args: [-big, 0],
  19986. checker: arrowChecker
  19987. }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
  19988. args: [small, 0],
  19989. checker: arrowChecker
  19990. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
  19991. args: [big, 0],
  19992. checker: arrowChecker
  19993. }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
  19994. args: [0, -small],
  19995. checker: arrowChecker
  19996. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
  19997. args: [0, -big],
  19998. checker: arrowChecker
  19999. }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
  20000. args: [0, small],
  20001. checker: arrowChecker
  20002. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
  20003. args: [0, big],
  20004. checker: arrowChecker
  20005. }]]));
  20006. }
  20007. static _type = "freetext";
  20008. static _editorType = AnnotationEditorType.FREETEXT;
  20009. constructor(params) {
  20010. super({
  20011. ...params,
  20012. name: "freeTextEditor"
  20013. });
  20014. this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
  20015. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  20016. }
  20017. static initialize(l10n, uiManager) {
  20018. AnnotationEditor.initialize(l10n, uiManager);
  20019. const style = getComputedStyle(document.documentElement);
  20020. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  20021. }
  20022. static updateDefaultParams(type, value) {
  20023. switch (type) {
  20024. case AnnotationEditorParamsType.FREETEXT_SIZE:
  20025. FreeTextEditor._defaultFontSize = value;
  20026. break;
  20027. case AnnotationEditorParamsType.FREETEXT_COLOR:
  20028. FreeTextEditor._defaultColor = value;
  20029. break;
  20030. }
  20031. }
  20032. updateParams(type, value) {
  20033. switch (type) {
  20034. case AnnotationEditorParamsType.FREETEXT_SIZE:
  20035. this.#updateFontSize(value);
  20036. break;
  20037. case AnnotationEditorParamsType.FREETEXT_COLOR:
  20038. this.#updateColor(value);
  20039. break;
  20040. }
  20041. }
  20042. static get defaultPropertiesToUpdate() {
  20043. return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
  20044. }
  20045. get propertiesToUpdate() {
  20046. return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  20047. }
  20048. #updateFontSize(fontSize) {
  20049. const setFontsize = size => {
  20050. this.editorDiv.style.fontSize = `calc(${size}px * var(--total-scale-factor))`;
  20051. this.translate(0, -(size - this.#fontSize) * this.parentScale);
  20052. this.#fontSize = size;
  20053. this.#setEditorDimensions();
  20054. };
  20055. const savedFontsize = this.#fontSize;
  20056. this.addCommands({
  20057. cmd: setFontsize.bind(this, fontSize),
  20058. undo: setFontsize.bind(this, savedFontsize),
  20059. post: this._uiManager.updateUI.bind(this._uiManager, this),
  20060. mustExec: true,
  20061. type: AnnotationEditorParamsType.FREETEXT_SIZE,
  20062. overwriteIfSameType: true,
  20063. keepUndo: true
  20064. });
  20065. }
  20066. #updateColor(color) {
  20067. const setColor = col => {
  20068. this.#color = this.editorDiv.style.color = col;
  20069. };
  20070. const savedColor = this.#color;
  20071. this.addCommands({
  20072. cmd: setColor.bind(this, color),
  20073. undo: setColor.bind(this, savedColor),
  20074. post: this._uiManager.updateUI.bind(this._uiManager, this),
  20075. mustExec: true,
  20076. type: AnnotationEditorParamsType.FREETEXT_COLOR,
  20077. overwriteIfSameType: true,
  20078. keepUndo: true
  20079. });
  20080. }
  20081. _translateEmpty(x, y) {
  20082. this._uiManager.translateSelectedEditors(x, y, true);
  20083. }
  20084. getInitialTranslation() {
  20085. const scale = this.parentScale;
  20086. return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  20087. }
  20088. rebuild() {
  20089. if (!this.parent) {
  20090. return;
  20091. }
  20092. super.rebuild();
  20093. if (this.div === null) {
  20094. return;
  20095. }
  20096. if (!this.isAttachedToDOM) {
  20097. this.parent.add(this);
  20098. }
  20099. }
  20100. enableEditMode() {
  20101. if (!super.enableEditMode()) {
  20102. return false;
  20103. }
  20104. this.overlayDiv.classList.remove("enabled");
  20105. this.editorDiv.contentEditable = true;
  20106. this._isDraggable = false;
  20107. this.div.removeAttribute("aria-activedescendant");
  20108. this.#editModeAC = new AbortController();
  20109. const signal = this._uiManager.combinedSignal(this.#editModeAC);
  20110. this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {
  20111. signal
  20112. });
  20113. this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {
  20114. signal
  20115. });
  20116. this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {
  20117. signal
  20118. });
  20119. this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {
  20120. signal
  20121. });
  20122. this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {
  20123. signal
  20124. });
  20125. return true;
  20126. }
  20127. disableEditMode() {
  20128. if (!super.disableEditMode()) {
  20129. return false;
  20130. }
  20131. this.overlayDiv.classList.add("enabled");
  20132. this.editorDiv.contentEditable = false;
  20133. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  20134. this._isDraggable = true;
  20135. this.#editModeAC?.abort();
  20136. this.#editModeAC = null;
  20137. this.div.focus({
  20138. preventScroll: true
  20139. });
  20140. this.isEditing = false;
  20141. this.parent.div.classList.add("freetextEditing");
  20142. return true;
  20143. }
  20144. focusin(event) {
  20145. if (!this._focusEventsAllowed) {
  20146. return;
  20147. }
  20148. super.focusin(event);
  20149. if (event.target !== this.editorDiv) {
  20150. this.editorDiv.focus();
  20151. }
  20152. }
  20153. onceAdded(focus) {
  20154. if (this.width) {
  20155. return;
  20156. }
  20157. this.enableEditMode();
  20158. if (focus) {
  20159. this.editorDiv.focus();
  20160. }
  20161. if (this._initialOptions?.isCentered) {
  20162. this.center();
  20163. }
  20164. this._initialOptions = null;
  20165. }
  20166. isEmpty() {
  20167. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  20168. }
  20169. remove() {
  20170. this.isEditing = false;
  20171. if (this.parent) {
  20172. this.parent.setEditingState(true);
  20173. this.parent.div.classList.add("freetextEditing");
  20174. }
  20175. super.remove();
  20176. }
  20177. #extractText() {
  20178. const buffer = [];
  20179. this.editorDiv.normalize();
  20180. let prevChild = null;
  20181. for (const child of this.editorDiv.childNodes) {
  20182. if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {
  20183. continue;
  20184. }
  20185. buffer.push(FreeTextEditor.#getNodeContent(child));
  20186. prevChild = child;
  20187. }
  20188. return buffer.join("\n");
  20189. }
  20190. #setEditorDimensions() {
  20191. const [parentWidth, parentHeight] = this.parentDimensions;
  20192. let rect;
  20193. if (this.isAttachedToDOM) {
  20194. rect = this.div.getBoundingClientRect();
  20195. } else {
  20196. const {
  20197. currentLayer,
  20198. div
  20199. } = this;
  20200. const savedDisplay = div.style.display;
  20201. const savedVisibility = div.classList.contains("hidden");
  20202. div.classList.remove("hidden");
  20203. div.style.display = "hidden";
  20204. currentLayer.div.append(this.div);
  20205. rect = div.getBoundingClientRect();
  20206. div.remove();
  20207. div.style.display = savedDisplay;
  20208. div.classList.toggle("hidden", savedVisibility);
  20209. }
  20210. if (this.rotation % 180 === this.parentRotation % 180) {
  20211. this.width = rect.width / parentWidth;
  20212. this.height = rect.height / parentHeight;
  20213. } else {
  20214. this.width = rect.height / parentWidth;
  20215. this.height = rect.width / parentHeight;
  20216. }
  20217. this.fixAndSetPosition();
  20218. }
  20219. commit() {
  20220. if (!this.isInEditMode()) {
  20221. return;
  20222. }
  20223. super.commit();
  20224. this.disableEditMode();
  20225. const savedText = this.#content;
  20226. const newText = this.#content = this.#extractText().trimEnd();
  20227. if (savedText === newText) {
  20228. return;
  20229. }
  20230. const setText = text => {
  20231. this.#content = text;
  20232. if (!text) {
  20233. this.remove();
  20234. return;
  20235. }
  20236. this.#setContent();
  20237. this._uiManager.rebuild(this);
  20238. this.#setEditorDimensions();
  20239. };
  20240. this.addCommands({
  20241. cmd: () => {
  20242. setText(newText);
  20243. },
  20244. undo: () => {
  20245. setText(savedText);
  20246. },
  20247. mustExec: false
  20248. });
  20249. this.#setEditorDimensions();
  20250. }
  20251. shouldGetKeyboardEvents() {
  20252. return this.isInEditMode();
  20253. }
  20254. enterInEditMode() {
  20255. this.enableEditMode();
  20256. this.editorDiv.focus();
  20257. }
  20258. keydown(event) {
  20259. if (event.target === this.div && event.key === "Enter") {
  20260. this.enterInEditMode();
  20261. event.preventDefault();
  20262. }
  20263. }
  20264. editorDivKeydown(event) {
  20265. FreeTextEditor._keyboardManager.exec(this, event);
  20266. }
  20267. editorDivFocus(event) {
  20268. this.isEditing = true;
  20269. }
  20270. editorDivBlur(event) {
  20271. this.isEditing = false;
  20272. }
  20273. editorDivInput(event) {
  20274. this.parent.div.classList.toggle("freetextEditing", this.isEmpty());
  20275. }
  20276. disableEditing() {
  20277. this.editorDiv.setAttribute("role", "comment");
  20278. this.editorDiv.removeAttribute("aria-multiline");
  20279. }
  20280. enableEditing() {
  20281. this.editorDiv.setAttribute("role", "textbox");
  20282. this.editorDiv.setAttribute("aria-multiline", true);
  20283. }
  20284. get canChangeContent() {
  20285. return true;
  20286. }
  20287. render() {
  20288. if (this.div) {
  20289. return this.div;
  20290. }
  20291. let baseX, baseY;
  20292. if (this._isCopy || this.annotationElementId) {
  20293. baseX = this.x;
  20294. baseY = this.y;
  20295. }
  20296. super.render();
  20297. this.editorDiv = document.createElement("div");
  20298. this.editorDiv.className = "internal";
  20299. this.editorDiv.setAttribute("id", this.#editorDivId);
  20300. this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2");
  20301. this.editorDiv.setAttribute("data-l10n-attrs", "default-content");
  20302. this.enableEditing();
  20303. this.editorDiv.contentEditable = true;
  20304. const {
  20305. style
  20306. } = this.editorDiv;
  20307. style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;
  20308. style.color = this.#color;
  20309. this.div.append(this.editorDiv);
  20310. this.overlayDiv = document.createElement("div");
  20311. this.overlayDiv.classList.add("overlay", "enabled");
  20312. this.div.append(this.overlayDiv);
  20313. if (this._isCopy || this.annotationElementId) {
  20314. const [parentWidth, parentHeight] = this.parentDimensions;
  20315. if (this.annotationElementId) {
  20316. const {
  20317. position
  20318. } = this._initialData;
  20319. let [tx, ty] = this.getInitialTranslation();
  20320. [tx, ty] = this.pageTranslationToScreen(tx, ty);
  20321. const [pageWidth, pageHeight] = this.pageDimensions;
  20322. const [pageX, pageY] = this.pageTranslation;
  20323. let posX, posY;
  20324. switch (this.rotation) {
  20325. case 0:
  20326. posX = baseX + (position[0] - pageX) / pageWidth;
  20327. posY = baseY + this.height - (position[1] - pageY) / pageHeight;
  20328. break;
  20329. case 90:
  20330. posX = baseX + (position[0] - pageX) / pageWidth;
  20331. posY = baseY - (position[1] - pageY) / pageHeight;
  20332. [tx, ty] = [ty, -tx];
  20333. break;
  20334. case 180:
  20335. posX = baseX - this.width + (position[0] - pageX) / pageWidth;
  20336. posY = baseY - (position[1] - pageY) / pageHeight;
  20337. [tx, ty] = [-tx, -ty];
  20338. break;
  20339. case 270:
  20340. posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
  20341. posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
  20342. [tx, ty] = [-ty, tx];
  20343. break;
  20344. }
  20345. this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
  20346. } else {
  20347. this._moveAfterPaste(baseX, baseY);
  20348. }
  20349. this.#setContent();
  20350. this._isDraggable = true;
  20351. this.editorDiv.contentEditable = false;
  20352. } else {
  20353. this._isDraggable = false;
  20354. this.editorDiv.contentEditable = true;
  20355. }
  20356. return this.div;
  20357. }
  20358. static #getNodeContent(node) {
  20359. return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
  20360. }
  20361. editorDivPaste(event) {
  20362. const clipboardData = event.clipboardData || window.clipboardData;
  20363. const {
  20364. types
  20365. } = clipboardData;
  20366. if (types.length === 1 && types[0] === "text/plain") {
  20367. return;
  20368. }
  20369. event.preventDefault();
  20370. const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
  20371. if (!paste) {
  20372. return;
  20373. }
  20374. const selection = window.getSelection();
  20375. if (!selection.rangeCount) {
  20376. return;
  20377. }
  20378. this.editorDiv.normalize();
  20379. selection.deleteFromDocument();
  20380. const range = selection.getRangeAt(0);
  20381. if (!paste.includes("\n")) {
  20382. range.insertNode(document.createTextNode(paste));
  20383. this.editorDiv.normalize();
  20384. selection.collapseToStart();
  20385. return;
  20386. }
  20387. const {
  20388. startContainer,
  20389. startOffset
  20390. } = range;
  20391. const bufferBefore = [];
  20392. const bufferAfter = [];
  20393. if (startContainer.nodeType === Node.TEXT_NODE) {
  20394. const parent = startContainer.parentElement;
  20395. bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
  20396. if (parent !== this.editorDiv) {
  20397. let buffer = bufferBefore;
  20398. for (const child of this.editorDiv.childNodes) {
  20399. if (child === parent) {
  20400. buffer = bufferAfter;
  20401. continue;
  20402. }
  20403. buffer.push(FreeTextEditor.#getNodeContent(child));
  20404. }
  20405. }
  20406. bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
  20407. } else if (startContainer === this.editorDiv) {
  20408. let buffer = bufferBefore;
  20409. let i = 0;
  20410. for (const child of this.editorDiv.childNodes) {
  20411. if (i++ === startOffset) {
  20412. buffer = bufferAfter;
  20413. }
  20414. buffer.push(FreeTextEditor.#getNodeContent(child));
  20415. }
  20416. }
  20417. this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
  20418. this.#setContent();
  20419. const newRange = new Range();
  20420. let beforeLength = Math.sumPrecise(bufferBefore.map(line => line.length));
  20421. for (const {
  20422. firstChild
  20423. } of this.editorDiv.childNodes) {
  20424. if (firstChild.nodeType === Node.TEXT_NODE) {
  20425. const length = firstChild.nodeValue.length;
  20426. if (beforeLength <= length) {
  20427. newRange.setStart(firstChild, beforeLength);
  20428. newRange.setEnd(firstChild, beforeLength);
  20429. break;
  20430. }
  20431. beforeLength -= length;
  20432. }
  20433. }
  20434. selection.removeAllRanges();
  20435. selection.addRange(newRange);
  20436. }
  20437. #setContent() {
  20438. this.editorDiv.replaceChildren();
  20439. if (!this.#content) {
  20440. return;
  20441. }
  20442. for (const line of this.#content.split("\n")) {
  20443. const div = document.createElement("div");
  20444. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  20445. this.editorDiv.append(div);
  20446. }
  20447. }
  20448. #serializeContent() {
  20449. return this.#content.replaceAll("\xa0", " ");
  20450. }
  20451. static #deserializeContent(content) {
  20452. return content.replaceAll(" ", "\xa0");
  20453. }
  20454. get contentDiv() {
  20455. return this.editorDiv;
  20456. }
  20457. static async deserialize(data, parent, uiManager) {
  20458. let initialData = null;
  20459. if (data instanceof FreeTextAnnotationElement) {
  20460. const {
  20461. data: {
  20462. defaultAppearanceData: {
  20463. fontSize,
  20464. fontColor
  20465. },
  20466. rect,
  20467. rotation,
  20468. id,
  20469. popupRef
  20470. },
  20471. textContent,
  20472. textPosition,
  20473. parent: {
  20474. page: {
  20475. pageNumber
  20476. }
  20477. }
  20478. } = data;
  20479. if (!textContent || textContent.length === 0) {
  20480. return null;
  20481. }
  20482. initialData = data = {
  20483. annotationType: AnnotationEditorType.FREETEXT,
  20484. color: Array.from(fontColor),
  20485. fontSize,
  20486. value: textContent.join("\n"),
  20487. position: textPosition,
  20488. pageIndex: pageNumber - 1,
  20489. rect: rect.slice(0),
  20490. rotation,
  20491. id,
  20492. deleted: false,
  20493. popupRef
  20494. };
  20495. }
  20496. const editor = await super.deserialize(data, parent, uiManager);
  20497. editor.#fontSize = data.fontSize;
  20498. editor.#color = Util.makeHexColor(...data.color);
  20499. editor.#content = FreeTextEditor.#deserializeContent(data.value);
  20500. editor.annotationElementId = data.id || null;
  20501. editor._initialData = initialData;
  20502. return editor;
  20503. }
  20504. serialize(isForCopying = false) {
  20505. if (this.isEmpty()) {
  20506. return null;
  20507. }
  20508. if (this.deleted) {
  20509. return this.serializeDeleted();
  20510. }
  20511. const padding = FreeTextEditor._internalPadding * this.parentScale;
  20512. const rect = this.getRect(padding, padding);
  20513. const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
  20514. const serialized = {
  20515. annotationType: AnnotationEditorType.FREETEXT,
  20516. color,
  20517. fontSize: this.#fontSize,
  20518. value: this.#serializeContent(),
  20519. pageIndex: this.pageIndex,
  20520. rect,
  20521. rotation: this.rotation,
  20522. structTreeParentId: this._structTreeParentId
  20523. };
  20524. if (isForCopying) {
  20525. serialized.isCopy = true;
  20526. return serialized;
  20527. }
  20528. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  20529. return null;
  20530. }
  20531. serialized.id = this.annotationElementId;
  20532. return serialized;
  20533. }
  20534. #hasElementChanged(serialized) {
  20535. const {
  20536. value,
  20537. fontSize,
  20538. color,
  20539. pageIndex
  20540. } = this._initialData;
  20541. return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;
  20542. }
  20543. renderAnnotationElement(annotation) {
  20544. const content = super.renderAnnotationElement(annotation);
  20545. if (this.deleted) {
  20546. return content;
  20547. }
  20548. const {
  20549. style
  20550. } = content;
  20551. style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;
  20552. style.color = this.#color;
  20553. content.replaceChildren();
  20554. for (const line of this.#content.split("\n")) {
  20555. const div = document.createElement("div");
  20556. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  20557. content.append(div);
  20558. }
  20559. const padding = FreeTextEditor._internalPadding * this.parentScale;
  20560. annotation.updateEdited({
  20561. rect: this.getRect(padding, padding),
  20562. popupContent: this.#content
  20563. });
  20564. return content;
  20565. }
  20566. resetAnnotationElement(annotation) {
  20567. super.resetAnnotationElement(annotation);
  20568. annotation.resetEdited();
  20569. }
  20570. }
  20571. ;// ./src/display/editor/drawers/outline.js
  20572. class Outline {
  20573. static PRECISION = 1e-4;
  20574. toSVGPath() {
  20575. unreachable("Abstract method `toSVGPath` must be implemented.");
  20576. }
  20577. get box() {
  20578. unreachable("Abstract getter `box` must be implemented.");
  20579. }
  20580. serialize(_bbox, _rotation) {
  20581. unreachable("Abstract method `serialize` must be implemented.");
  20582. }
  20583. static _rescale(src, tx, ty, sx, sy, dest) {
  20584. dest ||= new Float32Array(src.length);
  20585. for (let i = 0, ii = src.length; i < ii; i += 2) {
  20586. dest[i] = tx + src[i] * sx;
  20587. dest[i + 1] = ty + src[i + 1] * sy;
  20588. }
  20589. return dest;
  20590. }
  20591. static _rescaleAndSwap(src, tx, ty, sx, sy, dest) {
  20592. dest ||= new Float32Array(src.length);
  20593. for (let i = 0, ii = src.length; i < ii; i += 2) {
  20594. dest[i] = tx + src[i + 1] * sx;
  20595. dest[i + 1] = ty + src[i] * sy;
  20596. }
  20597. return dest;
  20598. }
  20599. static _translate(src, tx, ty, dest) {
  20600. dest ||= new Float32Array(src.length);
  20601. for (let i = 0, ii = src.length; i < ii; i += 2) {
  20602. dest[i] = tx + src[i];
  20603. dest[i + 1] = ty + src[i + 1];
  20604. }
  20605. return dest;
  20606. }
  20607. static svgRound(x) {
  20608. return Math.round(x * 10000);
  20609. }
  20610. static _normalizePoint(x, y, parentWidth, parentHeight, rotation) {
  20611. switch (rotation) {
  20612. case 90:
  20613. return [1 - y / parentWidth, x / parentHeight];
  20614. case 180:
  20615. return [1 - x / parentWidth, 1 - y / parentHeight];
  20616. case 270:
  20617. return [y / parentWidth, 1 - x / parentHeight];
  20618. default:
  20619. return [x / parentWidth, y / parentHeight];
  20620. }
  20621. }
  20622. static _normalizePagePoint(x, y, rotation) {
  20623. switch (rotation) {
  20624. case 90:
  20625. return [1 - y, x];
  20626. case 180:
  20627. return [1 - x, 1 - y];
  20628. case 270:
  20629. return [y, 1 - x];
  20630. default:
  20631. return [x, y];
  20632. }
  20633. }
  20634. static createBezierPoints(x1, y1, x2, y2, x3, y3) {
  20635. return [(x1 + 5 * x2) / 6, (y1 + 5 * y2) / 6, (5 * x2 + x3) / 6, (5 * y2 + y3) / 6, (x2 + x3) / 2, (y2 + y3) / 2];
  20636. }
  20637. }
  20638. ;// ./src/display/editor/drawers/freedraw.js
  20639. class FreeDrawOutliner {
  20640. #box;
  20641. #bottom = [];
  20642. #innerMargin;
  20643. #isLTR;
  20644. #top = [];
  20645. #last = new Float32Array(18);
  20646. #lastX;
  20647. #lastY;
  20648. #min;
  20649. #min_dist;
  20650. #scaleFactor;
  20651. #thickness;
  20652. #points = [];
  20653. static #MIN_DIST = 8;
  20654. static #MIN_DIFF = 2;
  20655. static #MIN = FreeDrawOutliner.#MIN_DIST + FreeDrawOutliner.#MIN_DIFF;
  20656. constructor({
  20657. x,
  20658. y
  20659. }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  20660. this.#box = box;
  20661. this.#thickness = thickness * scaleFactor;
  20662. this.#isLTR = isLTR;
  20663. this.#last.set([NaN, NaN, NaN, NaN, x, y], 6);
  20664. this.#innerMargin = innerMargin;
  20665. this.#min_dist = FreeDrawOutliner.#MIN_DIST * scaleFactor;
  20666. this.#min = FreeDrawOutliner.#MIN * scaleFactor;
  20667. this.#scaleFactor = scaleFactor;
  20668. this.#points.push(x, y);
  20669. }
  20670. isEmpty() {
  20671. return isNaN(this.#last[8]);
  20672. }
  20673. #getLastCoords() {
  20674. const lastTop = this.#last.subarray(4, 6);
  20675. const lastBottom = this.#last.subarray(16, 18);
  20676. const [x, y, width, height] = this.#box;
  20677. return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y) / height];
  20678. }
  20679. add({
  20680. x,
  20681. y
  20682. }) {
  20683. this.#lastX = x;
  20684. this.#lastY = y;
  20685. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20686. let [x1, y1, x2, y2] = this.#last.subarray(8, 12);
  20687. const diffX = x - x2;
  20688. const diffY = y - y2;
  20689. const d = Math.hypot(diffX, diffY);
  20690. if (d < this.#min) {
  20691. return false;
  20692. }
  20693. const diffD = d - this.#min_dist;
  20694. const K = diffD / d;
  20695. const shiftX = K * diffX;
  20696. const shiftY = K * diffY;
  20697. let x0 = x1;
  20698. let y0 = y1;
  20699. x1 = x2;
  20700. y1 = y2;
  20701. x2 += shiftX;
  20702. y2 += shiftY;
  20703. this.#points?.push(x, y);
  20704. const nX = -shiftY / diffD;
  20705. const nY = shiftX / diffD;
  20706. const thX = nX * this.#thickness;
  20707. const thY = nY * this.#thickness;
  20708. this.#last.set(this.#last.subarray(2, 8), 0);
  20709. this.#last.set([x2 + thX, y2 + thY], 4);
  20710. this.#last.set(this.#last.subarray(14, 18), 12);
  20711. this.#last.set([x2 - thX, y2 - thY], 16);
  20712. if (isNaN(this.#last[6])) {
  20713. if (this.#top.length === 0) {
  20714. this.#last.set([x1 + thX, y1 + thY], 2);
  20715. this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
  20716. this.#last.set([x1 - thX, y1 - thY], 14);
  20717. this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
  20718. }
  20719. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  20720. return !this.isEmpty();
  20721. }
  20722. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  20723. const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
  20724. if (angle < Math.PI / 2) {
  20725. [x1, y1, x2, y2] = this.#last.subarray(2, 6);
  20726. this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  20727. [x1, y1, x0, y0] = this.#last.subarray(14, 18);
  20728. this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
  20729. return true;
  20730. }
  20731. [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6);
  20732. this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  20733. [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18);
  20734. this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  20735. return true;
  20736. }
  20737. toSVGPath() {
  20738. if (this.isEmpty()) {
  20739. return "";
  20740. }
  20741. const top = this.#top;
  20742. const bottom = this.#bottom;
  20743. if (isNaN(this.#last[6]) && !this.isEmpty()) {
  20744. return this.#toSVGPathTwoPoints();
  20745. }
  20746. const buffer = [];
  20747. buffer.push(`M${top[4]} ${top[5]}`);
  20748. for (let i = 6; i < top.length; i += 6) {
  20749. if (isNaN(top[i])) {
  20750. buffer.push(`L${top[i + 4]} ${top[i + 5]}`);
  20751. } else {
  20752. buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`);
  20753. }
  20754. }
  20755. this.#toSVGPathEnd(buffer);
  20756. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  20757. if (isNaN(bottom[i])) {
  20758. buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`);
  20759. } else {
  20760. buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`);
  20761. }
  20762. }
  20763. this.#toSVGPathStart(buffer);
  20764. return buffer.join(" ");
  20765. }
  20766. #toSVGPathTwoPoints() {
  20767. const [x, y, width, height] = this.#box;
  20768. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  20769. return `M${(this.#last[2] - x) / width} ${(this.#last[3] - y) / height} L${(this.#last[4] - x) / width} ${(this.#last[5] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x) / width} ${(this.#last[17] - y) / height} L${(this.#last[14] - x) / width} ${(this.#last[15] - y) / height} Z`;
  20770. }
  20771. #toSVGPathStart(buffer) {
  20772. const bottom = this.#bottom;
  20773. buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
  20774. }
  20775. #toSVGPathEnd(buffer) {
  20776. const [x, y, width, height] = this.#box;
  20777. const lastTop = this.#last.subarray(4, 6);
  20778. const lastBottom = this.#last.subarray(16, 18);
  20779. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  20780. buffer.push(`L${(lastTop[0] - x) / width} ${(lastTop[1] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x) / width} ${(lastBottom[1] - y) / height}`);
  20781. }
  20782. newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
  20783. return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  20784. }
  20785. getOutlines() {
  20786. const top = this.#top;
  20787. const bottom = this.#bottom;
  20788. const last = this.#last;
  20789. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20790. const points = new Float32Array((this.#points?.length ?? 0) + 2);
  20791. for (let i = 0, ii = points.length - 2; i < ii; i += 2) {
  20792. points[i] = (this.#points[i] - layerX) / layerWidth;
  20793. points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight;
  20794. }
  20795. points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
  20796. points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
  20797. if (isNaN(last[6]) && !this.isEmpty()) {
  20798. return this.#getOutlineTwoPoints(points);
  20799. }
  20800. const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length);
  20801. let N = top.length;
  20802. for (let i = 0; i < N; i += 2) {
  20803. if (isNaN(top[i])) {
  20804. outline[i] = outline[i + 1] = NaN;
  20805. continue;
  20806. }
  20807. outline[i] = top[i];
  20808. outline[i + 1] = top[i + 1];
  20809. }
  20810. N = this.#getOutlineEnd(outline, N);
  20811. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  20812. for (let j = 0; j < 6; j += 2) {
  20813. if (isNaN(bottom[i + j])) {
  20814. outline[N] = outline[N + 1] = NaN;
  20815. N += 2;
  20816. continue;
  20817. }
  20818. outline[N] = bottom[i + j];
  20819. outline[N + 1] = bottom[i + j + 1];
  20820. N += 2;
  20821. }
  20822. }
  20823. this.#getOutlineStart(outline, N);
  20824. return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  20825. }
  20826. #getOutlineTwoPoints(points) {
  20827. const last = this.#last;
  20828. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20829. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  20830. const outline = new Float32Array(36);
  20831. outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0);
  20832. return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  20833. }
  20834. #getOutlineStart(outline, pos) {
  20835. const bottom = this.#bottom;
  20836. outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos);
  20837. return pos += 6;
  20838. }
  20839. #getOutlineEnd(outline, pos) {
  20840. const lastTop = this.#last.subarray(4, 6);
  20841. const lastBottom = this.#last.subarray(16, 18);
  20842. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20843. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  20844. outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos);
  20845. return pos += 24;
  20846. }
  20847. }
  20848. class FreeDrawOutline extends Outline {
  20849. #box;
  20850. #bbox = new Float32Array(4);
  20851. #innerMargin;
  20852. #isLTR;
  20853. #points;
  20854. #scaleFactor;
  20855. #outline;
  20856. constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
  20857. super();
  20858. this.#outline = outline;
  20859. this.#points = points;
  20860. this.#box = box;
  20861. this.#scaleFactor = scaleFactor;
  20862. this.#innerMargin = innerMargin;
  20863. this.#isLTR = isLTR;
  20864. this.lastPoint = [NaN, NaN];
  20865. this.#computeMinMax(isLTR);
  20866. const [x, y, width, height] = this.#bbox;
  20867. for (let i = 0, ii = outline.length; i < ii; i += 2) {
  20868. outline[i] = (outline[i] - x) / width;
  20869. outline[i + 1] = (outline[i + 1] - y) / height;
  20870. }
  20871. for (let i = 0, ii = points.length; i < ii; i += 2) {
  20872. points[i] = (points[i] - x) / width;
  20873. points[i + 1] = (points[i + 1] - y) / height;
  20874. }
  20875. }
  20876. toSVGPath() {
  20877. const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
  20878. for (let i = 6, ii = this.#outline.length; i < ii; i += 6) {
  20879. if (isNaN(this.#outline[i])) {
  20880. buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
  20881. continue;
  20882. }
  20883. buffer.push(`C${this.#outline[i]} ${this.#outline[i + 1]} ${this.#outline[i + 2]} ${this.#outline[i + 3]} ${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
  20884. }
  20885. buffer.push("Z");
  20886. return buffer.join(" ");
  20887. }
  20888. serialize([blX, blY, trX, trY], rotation) {
  20889. const width = trX - blX;
  20890. const height = trY - blY;
  20891. let outline;
  20892. let points;
  20893. switch (rotation) {
  20894. case 0:
  20895. outline = Outline._rescale(this.#outline, blX, trY, width, -height);
  20896. points = Outline._rescale(this.#points, blX, trY, width, -height);
  20897. break;
  20898. case 90:
  20899. outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height);
  20900. points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height);
  20901. break;
  20902. case 180:
  20903. outline = Outline._rescale(this.#outline, trX, blY, -width, height);
  20904. points = Outline._rescale(this.#points, trX, blY, -width, height);
  20905. break;
  20906. case 270:
  20907. outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height);
  20908. points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height);
  20909. break;
  20910. }
  20911. return {
  20912. outline: Array.from(outline),
  20913. points: [Array.from(points)]
  20914. };
  20915. }
  20916. #computeMinMax(isLTR) {
  20917. const outline = this.#outline;
  20918. let lastX = outline[4];
  20919. let lastY = outline[5];
  20920. const minMax = [lastX, lastY, lastX, lastY];
  20921. let lastPointX = lastX;
  20922. let lastPointY = lastY;
  20923. const ltrCallback = isLTR ? Math.max : Math.min;
  20924. for (let i = 6, ii = outline.length; i < ii; i += 6) {
  20925. const x = outline[i + 4],
  20926. y = outline[i + 5];
  20927. if (isNaN(outline[i])) {
  20928. Util.pointBoundingBox(x, y, minMax);
  20929. if (lastPointY < y) {
  20930. lastPointX = x;
  20931. lastPointY = y;
  20932. } else if (lastPointY === y) {
  20933. lastPointX = ltrCallback(lastPointX, x);
  20934. }
  20935. } else {
  20936. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  20937. Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6), bbox);
  20938. Util.rectBoundingBox(...bbox, minMax);
  20939. if (lastPointY < bbox[3]) {
  20940. lastPointX = bbox[2];
  20941. lastPointY = bbox[3];
  20942. } else if (lastPointY === bbox[3]) {
  20943. lastPointX = ltrCallback(lastPointX, bbox[2]);
  20944. }
  20945. }
  20946. lastX = x;
  20947. lastY = y;
  20948. }
  20949. const bbox = this.#bbox;
  20950. bbox[0] = minMax[0] - this.#innerMargin;
  20951. bbox[1] = minMax[1] - this.#innerMargin;
  20952. bbox[2] = minMax[2] - minMax[0] + 2 * this.#innerMargin;
  20953. bbox[3] = minMax[3] - minMax[1] + 2 * this.#innerMargin;
  20954. this.lastPoint = [lastPointX, lastPointY];
  20955. }
  20956. get box() {
  20957. return this.#bbox;
  20958. }
  20959. newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  20960. return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  20961. }
  20962. getNewOutline(thickness, innerMargin) {
  20963. const [x, y, width, height] = this.#bbox;
  20964. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20965. const sx = width * layerWidth;
  20966. const sy = height * layerHeight;
  20967. const tx = x * layerWidth + layerX;
  20968. const ty = y * layerHeight + layerY;
  20969. const outliner = this.newOutliner({
  20970. x: this.#points[0] * sx + tx,
  20971. y: this.#points[1] * sy + ty
  20972. }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
  20973. for (let i = 2; i < this.#points.length; i += 2) {
  20974. outliner.add({
  20975. x: this.#points[i] * sx + tx,
  20976. y: this.#points[i + 1] * sy + ty
  20977. });
  20978. }
  20979. return outliner.getOutlines();
  20980. }
  20981. }
  20982. ;// ./src/display/editor/drawers/highlight.js
  20983. class HighlightOutliner {
  20984. #box;
  20985. #lastPoint;
  20986. #verticalEdges = [];
  20987. #intervals = [];
  20988. constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
  20989. const minMax = [Infinity, Infinity, -Infinity, -Infinity];
  20990. const NUMBER_OF_DIGITS = 4;
  20991. const EPSILON = 10 ** -NUMBER_OF_DIGITS;
  20992. for (const {
  20993. x,
  20994. y,
  20995. width,
  20996. height
  20997. } of boxes) {
  20998. const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON;
  20999. const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON;
  21000. const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON;
  21001. const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON;
  21002. const left = [x1, y1, y2, true];
  21003. const right = [x2, y1, y2, false];
  21004. this.#verticalEdges.push(left, right);
  21005. Util.rectBoundingBox(x1, y1, x2, y2, minMax);
  21006. }
  21007. const bboxWidth = minMax[2] - minMax[0] + 2 * innerMargin;
  21008. const bboxHeight = minMax[3] - minMax[1] + 2 * innerMargin;
  21009. const shiftedMinX = minMax[0] - innerMargin;
  21010. const shiftedMinY = minMax[1] - innerMargin;
  21011. const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
  21012. const lastPoint = [lastEdge[0], lastEdge[2]];
  21013. for (const edge of this.#verticalEdges) {
  21014. const [x, y1, y2] = edge;
  21015. edge[0] = (x - shiftedMinX) / bboxWidth;
  21016. edge[1] = (y1 - shiftedMinY) / bboxHeight;
  21017. edge[2] = (y2 - shiftedMinY) / bboxHeight;
  21018. }
  21019. this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]);
  21020. this.#lastPoint = lastPoint;
  21021. }
  21022. getOutlines() {
  21023. this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
  21024. const outlineVerticalEdges = [];
  21025. for (const edge of this.#verticalEdges) {
  21026. if (edge[3]) {
  21027. outlineVerticalEdges.push(...this.#breakEdge(edge));
  21028. this.#insert(edge);
  21029. } else {
  21030. this.#remove(edge);
  21031. outlineVerticalEdges.push(...this.#breakEdge(edge));
  21032. }
  21033. }
  21034. return this.#getOutlines(outlineVerticalEdges);
  21035. }
  21036. #getOutlines(outlineVerticalEdges) {
  21037. const edges = [];
  21038. const allEdges = new Set();
  21039. for (const edge of outlineVerticalEdges) {
  21040. const [x, y1, y2] = edge;
  21041. edges.push([x, y1, edge], [x, y2, edge]);
  21042. }
  21043. edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
  21044. for (let i = 0, ii = edges.length; i < ii; i += 2) {
  21045. const edge1 = edges[i][2];
  21046. const edge2 = edges[i + 1][2];
  21047. edge1.push(edge2);
  21048. edge2.push(edge1);
  21049. allEdges.add(edge1);
  21050. allEdges.add(edge2);
  21051. }
  21052. const outlines = [];
  21053. let outline;
  21054. while (allEdges.size > 0) {
  21055. const edge = allEdges.values().next().value;
  21056. let [x, y1, y2, edge1, edge2] = edge;
  21057. allEdges.delete(edge);
  21058. let lastPointX = x;
  21059. let lastPointY = y1;
  21060. outline = [x, y2];
  21061. outlines.push(outline);
  21062. while (true) {
  21063. let e;
  21064. if (allEdges.has(edge1)) {
  21065. e = edge1;
  21066. } else if (allEdges.has(edge2)) {
  21067. e = edge2;
  21068. } else {
  21069. break;
  21070. }
  21071. allEdges.delete(e);
  21072. [x, y1, y2, edge1, edge2] = e;
  21073. if (lastPointX !== x) {
  21074. outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2);
  21075. lastPointX = x;
  21076. }
  21077. lastPointY = lastPointY === y1 ? y2 : y1;
  21078. }
  21079. outline.push(lastPointX, lastPointY);
  21080. }
  21081. return new HighlightOutline(outlines, this.#box, this.#lastPoint);
  21082. }
  21083. #binarySearch(y) {
  21084. const array = this.#intervals;
  21085. let start = 0;
  21086. let end = array.length - 1;
  21087. while (start <= end) {
  21088. const middle = start + end >> 1;
  21089. const y1 = array[middle][0];
  21090. if (y1 === y) {
  21091. return middle;
  21092. }
  21093. if (y1 < y) {
  21094. start = middle + 1;
  21095. } else {
  21096. end = middle - 1;
  21097. }
  21098. }
  21099. return end + 1;
  21100. }
  21101. #insert([, y1, y2]) {
  21102. const index = this.#binarySearch(y1);
  21103. this.#intervals.splice(index, 0, [y1, y2]);
  21104. }
  21105. #remove([, y1, y2]) {
  21106. const index = this.#binarySearch(y1);
  21107. for (let i = index; i < this.#intervals.length; i++) {
  21108. const [start, end] = this.#intervals[i];
  21109. if (start !== y1) {
  21110. break;
  21111. }
  21112. if (start === y1 && end === y2) {
  21113. this.#intervals.splice(i, 1);
  21114. return;
  21115. }
  21116. }
  21117. for (let i = index - 1; i >= 0; i--) {
  21118. const [start, end] = this.#intervals[i];
  21119. if (start !== y1) {
  21120. break;
  21121. }
  21122. if (start === y1 && end === y2) {
  21123. this.#intervals.splice(i, 1);
  21124. return;
  21125. }
  21126. }
  21127. }
  21128. #breakEdge(edge) {
  21129. const [x, y1, y2] = edge;
  21130. const results = [[x, y1, y2]];
  21131. const index = this.#binarySearch(y2);
  21132. for (let i = 0; i < index; i++) {
  21133. const [start, end] = this.#intervals[i];
  21134. for (let j = 0, jj = results.length; j < jj; j++) {
  21135. const [, y3, y4] = results[j];
  21136. if (end <= y3 || y4 <= start) {
  21137. continue;
  21138. }
  21139. if (y3 >= start) {
  21140. if (y4 > end) {
  21141. results[j][1] = end;
  21142. } else {
  21143. if (jj === 1) {
  21144. return [];
  21145. }
  21146. results.splice(j, 1);
  21147. j--;
  21148. jj--;
  21149. }
  21150. continue;
  21151. }
  21152. results[j][2] = start;
  21153. if (y4 > end) {
  21154. results.push([x, end, y4]);
  21155. }
  21156. }
  21157. }
  21158. return results;
  21159. }
  21160. }
  21161. class HighlightOutline extends Outline {
  21162. #box;
  21163. #outlines;
  21164. constructor(outlines, box, lastPoint) {
  21165. super();
  21166. this.#outlines = outlines;
  21167. this.#box = box;
  21168. this.lastPoint = lastPoint;
  21169. }
  21170. toSVGPath() {
  21171. const buffer = [];
  21172. for (const polygon of this.#outlines) {
  21173. let [prevX, prevY] = polygon;
  21174. buffer.push(`M${prevX} ${prevY}`);
  21175. for (let i = 2; i < polygon.length; i += 2) {
  21176. const x = polygon[i];
  21177. const y = polygon[i + 1];
  21178. if (x === prevX) {
  21179. buffer.push(`V${y}`);
  21180. prevY = y;
  21181. } else if (y === prevY) {
  21182. buffer.push(`H${x}`);
  21183. prevX = x;
  21184. }
  21185. }
  21186. buffer.push("Z");
  21187. }
  21188. return buffer.join(" ");
  21189. }
  21190. serialize([blX, blY, trX, trY], _rotation) {
  21191. const outlines = [];
  21192. const width = trX - blX;
  21193. const height = trY - blY;
  21194. for (const outline of this.#outlines) {
  21195. const points = new Array(outline.length);
  21196. for (let i = 0; i < outline.length; i += 2) {
  21197. points[i] = blX + outline[i] * width;
  21198. points[i + 1] = trY - outline[i + 1] * height;
  21199. }
  21200. outlines.push(points);
  21201. }
  21202. return outlines;
  21203. }
  21204. get box() {
  21205. return this.#box;
  21206. }
  21207. get classNamesForOutlining() {
  21208. return ["highlightOutline"];
  21209. }
  21210. }
  21211. class FreeHighlightOutliner extends FreeDrawOutliner {
  21212. newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
  21213. return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  21214. }
  21215. }
  21216. class FreeHighlightOutline extends FreeDrawOutline {
  21217. newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  21218. return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  21219. }
  21220. }
  21221. ;// ./src/display/editor/color_picker.js
  21222. class ColorPicker {
  21223. #button = null;
  21224. #buttonSwatch = null;
  21225. #defaultColor;
  21226. #dropdown = null;
  21227. #dropdownWasFromKeyboard = false;
  21228. #isMainColorPicker = false;
  21229. #editor = null;
  21230. #eventBus;
  21231. #openDropdownAC = null;
  21232. #uiManager = null;
  21233. #type;
  21234. static #l10nColor = null;
  21235. static get _keyboardManager() {
  21236. return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], ColorPicker.prototype._moveToEnd]]));
  21237. }
  21238. constructor({
  21239. editor = null,
  21240. uiManager = null
  21241. }) {
  21242. if (editor) {
  21243. this.#isMainColorPicker = false;
  21244. this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR;
  21245. this.#editor = editor;
  21246. } else {
  21247. this.#isMainColorPicker = true;
  21248. this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR;
  21249. }
  21250. this.#uiManager = editor?._uiManager || uiManager;
  21251. this.#eventBus = this.#uiManager._eventBus;
  21252. this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
  21253. ColorPicker.#l10nColor ||= Object.freeze({
  21254. blue: "pdfjs-editor-colorpicker-blue",
  21255. green: "pdfjs-editor-colorpicker-green",
  21256. pink: "pdfjs-editor-colorpicker-pink",
  21257. red: "pdfjs-editor-colorpicker-red",
  21258. yellow: "pdfjs-editor-colorpicker-yellow"
  21259. });
  21260. }
  21261. renderButton() {
  21262. const button = this.#button = document.createElement("button");
  21263. button.className = "colorPicker";
  21264. button.tabIndex = "0";
  21265. button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
  21266. button.setAttribute("aria-haspopup", true);
  21267. const signal = this.#uiManager._signal;
  21268. button.addEventListener("click", this.#openDropdown.bind(this), {
  21269. signal
  21270. });
  21271. button.addEventListener("keydown", this.#keyDown.bind(this), {
  21272. signal
  21273. });
  21274. const swatch = this.#buttonSwatch = document.createElement("span");
  21275. swatch.className = "swatch";
  21276. swatch.setAttribute("aria-hidden", true);
  21277. swatch.style.backgroundColor = this.#defaultColor;
  21278. button.append(swatch);
  21279. return button;
  21280. }
  21281. renderMainDropdown() {
  21282. const dropdown = this.#dropdown = this.#getDropdownRoot();
  21283. dropdown.setAttribute("aria-orientation", "horizontal");
  21284. dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel");
  21285. return dropdown;
  21286. }
  21287. #getDropdownRoot() {
  21288. const div = document.createElement("div");
  21289. const signal = this.#uiManager._signal;
  21290. div.addEventListener("contextmenu", noContextMenu, {
  21291. signal
  21292. });
  21293. div.className = "dropdown";
  21294. div.role = "listbox";
  21295. div.setAttribute("aria-multiselectable", false);
  21296. div.setAttribute("aria-orientation", "vertical");
  21297. div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
  21298. for (const [name, color] of this.#uiManager.highlightColors) {
  21299. const button = document.createElement("button");
  21300. button.tabIndex = "0";
  21301. button.role = "option";
  21302. button.setAttribute("data-color", color);
  21303. button.title = name;
  21304. button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]);
  21305. const swatch = document.createElement("span");
  21306. button.append(swatch);
  21307. swatch.className = "swatch";
  21308. swatch.style.backgroundColor = color;
  21309. button.setAttribute("aria-selected", color === this.#defaultColor);
  21310. button.addEventListener("click", this.#colorSelect.bind(this, color), {
  21311. signal
  21312. });
  21313. div.append(button);
  21314. }
  21315. div.addEventListener("keydown", this.#keyDown.bind(this), {
  21316. signal
  21317. });
  21318. return div;
  21319. }
  21320. #colorSelect(color, event) {
  21321. event.stopPropagation();
  21322. this.#eventBus.dispatch("switchannotationeditorparams", {
  21323. source: this,
  21324. type: this.#type,
  21325. value: color
  21326. });
  21327. }
  21328. _colorSelectFromKeyboard(event) {
  21329. if (event.target === this.#button) {
  21330. this.#openDropdown(event);
  21331. return;
  21332. }
  21333. const color = event.target.getAttribute("data-color");
  21334. if (!color) {
  21335. return;
  21336. }
  21337. this.#colorSelect(color, event);
  21338. }
  21339. _moveToNext(event) {
  21340. if (!this.#isDropdownVisible) {
  21341. this.#openDropdown(event);
  21342. return;
  21343. }
  21344. if (event.target === this.#button) {
  21345. this.#dropdown.firstChild?.focus();
  21346. return;
  21347. }
  21348. event.target.nextSibling?.focus();
  21349. }
  21350. _moveToPrevious(event) {
  21351. if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
  21352. if (this.#isDropdownVisible) {
  21353. this._hideDropdownFromKeyboard();
  21354. }
  21355. return;
  21356. }
  21357. if (!this.#isDropdownVisible) {
  21358. this.#openDropdown(event);
  21359. }
  21360. event.target.previousSibling?.focus();
  21361. }
  21362. _moveToBeginning(event) {
  21363. if (!this.#isDropdownVisible) {
  21364. this.#openDropdown(event);
  21365. return;
  21366. }
  21367. this.#dropdown.firstChild?.focus();
  21368. }
  21369. _moveToEnd(event) {
  21370. if (!this.#isDropdownVisible) {
  21371. this.#openDropdown(event);
  21372. return;
  21373. }
  21374. this.#dropdown.lastChild?.focus();
  21375. }
  21376. #keyDown(event) {
  21377. ColorPicker._keyboardManager.exec(this, event);
  21378. }
  21379. #openDropdown(event) {
  21380. if (this.#isDropdownVisible) {
  21381. this.hideDropdown();
  21382. return;
  21383. }
  21384. this.#dropdownWasFromKeyboard = event.detail === 0;
  21385. if (!this.#openDropdownAC) {
  21386. this.#openDropdownAC = new AbortController();
  21387. window.addEventListener("pointerdown", this.#pointerDown.bind(this), {
  21388. signal: this.#uiManager.combinedSignal(this.#openDropdownAC)
  21389. });
  21390. }
  21391. if (this.#dropdown) {
  21392. this.#dropdown.classList.remove("hidden");
  21393. return;
  21394. }
  21395. const root = this.#dropdown = this.#getDropdownRoot();
  21396. this.#button.append(root);
  21397. }
  21398. #pointerDown(event) {
  21399. if (this.#dropdown?.contains(event.target)) {
  21400. return;
  21401. }
  21402. this.hideDropdown();
  21403. }
  21404. hideDropdown() {
  21405. this.#dropdown?.classList.add("hidden");
  21406. this.#openDropdownAC?.abort();
  21407. this.#openDropdownAC = null;
  21408. }
  21409. get #isDropdownVisible() {
  21410. return this.#dropdown && !this.#dropdown.classList.contains("hidden");
  21411. }
  21412. _hideDropdownFromKeyboard() {
  21413. if (this.#isMainColorPicker) {
  21414. return;
  21415. }
  21416. if (!this.#isDropdownVisible) {
  21417. this.#editor?.unselect();
  21418. return;
  21419. }
  21420. this.hideDropdown();
  21421. this.#button.focus({
  21422. preventScroll: true,
  21423. focusVisible: this.#dropdownWasFromKeyboard
  21424. });
  21425. }
  21426. updateColor(color) {
  21427. if (this.#buttonSwatch) {
  21428. this.#buttonSwatch.style.backgroundColor = color;
  21429. }
  21430. if (!this.#dropdown) {
  21431. return;
  21432. }
  21433. const i = this.#uiManager.highlightColors.values();
  21434. for (const child of this.#dropdown.children) {
  21435. child.setAttribute("aria-selected", i.next().value === color);
  21436. }
  21437. }
  21438. destroy() {
  21439. this.#button?.remove();
  21440. this.#button = null;
  21441. this.#buttonSwatch = null;
  21442. this.#dropdown?.remove();
  21443. this.#dropdown = null;
  21444. }
  21445. }
  21446. ;// ./src/display/editor/highlight.js
  21447. class HighlightEditor extends AnnotationEditor {
  21448. #anchorNode = null;
  21449. #anchorOffset = 0;
  21450. #boxes;
  21451. #clipPathId = null;
  21452. #colorPicker = null;
  21453. #focusOutlines = null;
  21454. #focusNode = null;
  21455. #focusOffset = 0;
  21456. #highlightDiv = null;
  21457. #highlightOutlines = null;
  21458. #id = null;
  21459. #isFreeHighlight = false;
  21460. #lastPoint = null;
  21461. #opacity;
  21462. #outlineId = null;
  21463. #text = "";
  21464. #thickness;
  21465. #methodOfCreation = "";
  21466. static _defaultColor = null;
  21467. static _defaultOpacity = 1;
  21468. static _defaultThickness = 12;
  21469. static _type = "highlight";
  21470. static _editorType = AnnotationEditorType.HIGHLIGHT;
  21471. static _freeHighlightId = -1;
  21472. static _freeHighlight = null;
  21473. static _freeHighlightClipId = "";
  21474. static get _keyboardManager() {
  21475. const proto = HighlightEditor.prototype;
  21476. return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
  21477. args: [0]
  21478. }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
  21479. args: [1]
  21480. }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
  21481. args: [2]
  21482. }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
  21483. args: [3]
  21484. }]]));
  21485. }
  21486. constructor(params) {
  21487. super({
  21488. ...params,
  21489. name: "highlightEditor"
  21490. });
  21491. this.color = params.color || HighlightEditor._defaultColor;
  21492. this.#thickness = params.thickness || HighlightEditor._defaultThickness;
  21493. this.#opacity = params.opacity || HighlightEditor._defaultOpacity;
  21494. this.#boxes = params.boxes || null;
  21495. this.#methodOfCreation = params.methodOfCreation || "";
  21496. this.#text = params.text || "";
  21497. this._isDraggable = false;
  21498. this.defaultL10nId = "pdfjs-editor-highlight-editor";
  21499. if (params.highlightId > -1) {
  21500. this.#isFreeHighlight = true;
  21501. this.#createFreeOutlines(params);
  21502. this.#addToDrawLayer();
  21503. } else if (this.#boxes) {
  21504. this.#anchorNode = params.anchorNode;
  21505. this.#anchorOffset = params.anchorOffset;
  21506. this.#focusNode = params.focusNode;
  21507. this.#focusOffset = params.focusOffset;
  21508. this.#createOutlines();
  21509. this.#addToDrawLayer();
  21510. this.rotate(this.rotation);
  21511. }
  21512. }
  21513. get telemetryInitialData() {
  21514. return {
  21515. action: "added",
  21516. type: this.#isFreeHighlight ? "free_highlight" : "highlight",
  21517. color: this._uiManager.highlightColorNames.get(this.color),
  21518. thickness: this.#thickness,
  21519. methodOfCreation: this.#methodOfCreation
  21520. };
  21521. }
  21522. get telemetryFinalData() {
  21523. return {
  21524. type: "highlight",
  21525. color: this._uiManager.highlightColorNames.get(this.color)
  21526. };
  21527. }
  21528. static computeTelemetryFinalData(data) {
  21529. return {
  21530. numberOfColors: data.get("color").size
  21531. };
  21532. }
  21533. #createOutlines() {
  21534. const outliner = new HighlightOutliner(this.#boxes, 0.001);
  21535. this.#highlightOutlines = outliner.getOutlines();
  21536. [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box;
  21537. const outlinerForOutline = new HighlightOutliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr");
  21538. this.#focusOutlines = outlinerForOutline.getOutlines();
  21539. const {
  21540. lastPoint
  21541. } = this.#focusOutlines;
  21542. this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
  21543. }
  21544. #createFreeOutlines({
  21545. highlightOutlines,
  21546. highlightId,
  21547. clipPathId
  21548. }) {
  21549. this.#highlightOutlines = highlightOutlines;
  21550. const extraThickness = 1.5;
  21551. this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025);
  21552. if (highlightId >= 0) {
  21553. this.#id = highlightId;
  21554. this.#clipPathId = clipPathId;
  21555. this.parent.drawLayer.finalizeDraw(highlightId, {
  21556. bbox: highlightOutlines.box,
  21557. path: {
  21558. d: highlightOutlines.toSVGPath()
  21559. }
  21560. });
  21561. this.#outlineId = this.parent.drawLayer.drawOutline({
  21562. rootClass: {
  21563. highlightOutline: true,
  21564. free: true
  21565. },
  21566. bbox: this.#focusOutlines.box,
  21567. path: {
  21568. d: this.#focusOutlines.toSVGPath()
  21569. }
  21570. }, true);
  21571. } else if (this.parent) {
  21572. const angle = this.parent.viewport.rotation;
  21573. this.parent.drawLayer.updateProperties(this.#id, {
  21574. bbox: HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360),
  21575. path: {
  21576. d: highlightOutlines.toSVGPath()
  21577. }
  21578. });
  21579. this.parent.drawLayer.updateProperties(this.#outlineId, {
  21580. bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
  21581. path: {
  21582. d: this.#focusOutlines.toSVGPath()
  21583. }
  21584. });
  21585. }
  21586. const [x, y, width, height] = highlightOutlines.box;
  21587. switch (this.rotation) {
  21588. case 0:
  21589. this.x = x;
  21590. this.y = y;
  21591. this.width = width;
  21592. this.height = height;
  21593. break;
  21594. case 90:
  21595. {
  21596. const [pageWidth, pageHeight] = this.parentDimensions;
  21597. this.x = y;
  21598. this.y = 1 - x;
  21599. this.width = width * pageHeight / pageWidth;
  21600. this.height = height * pageWidth / pageHeight;
  21601. break;
  21602. }
  21603. case 180:
  21604. this.x = 1 - x;
  21605. this.y = 1 - y;
  21606. this.width = width;
  21607. this.height = height;
  21608. break;
  21609. case 270:
  21610. {
  21611. const [pageWidth, pageHeight] = this.parentDimensions;
  21612. this.x = 1 - y;
  21613. this.y = x;
  21614. this.width = width * pageHeight / pageWidth;
  21615. this.height = height * pageWidth / pageHeight;
  21616. break;
  21617. }
  21618. }
  21619. const {
  21620. lastPoint
  21621. } = this.#focusOutlines;
  21622. this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height];
  21623. }
  21624. static initialize(l10n, uiManager) {
  21625. AnnotationEditor.initialize(l10n, uiManager);
  21626. HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
  21627. }
  21628. static updateDefaultParams(type, value) {
  21629. switch (type) {
  21630. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  21631. HighlightEditor._defaultColor = value;
  21632. break;
  21633. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  21634. HighlightEditor._defaultThickness = value;
  21635. break;
  21636. }
  21637. }
  21638. translateInPage(x, y) {}
  21639. get toolbarPosition() {
  21640. return this.#lastPoint;
  21641. }
  21642. updateParams(type, value) {
  21643. switch (type) {
  21644. case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
  21645. this.#updateColor(value);
  21646. break;
  21647. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  21648. this.#updateThickness(value);
  21649. break;
  21650. }
  21651. }
  21652. static get defaultPropertiesToUpdate() {
  21653. return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]];
  21654. }
  21655. get propertiesToUpdate() {
  21656. return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
  21657. }
  21658. #updateColor(color) {
  21659. const setColorAndOpacity = (col, opa) => {
  21660. this.color = col;
  21661. this.#opacity = opa;
  21662. this.parent?.drawLayer.updateProperties(this.#id, {
  21663. root: {
  21664. fill: col,
  21665. "fill-opacity": opa
  21666. }
  21667. });
  21668. this.#colorPicker?.updateColor(col);
  21669. };
  21670. const savedColor = this.color;
  21671. const savedOpacity = this.#opacity;
  21672. this.addCommands({
  21673. cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity),
  21674. undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),
  21675. post: this._uiManager.updateUI.bind(this._uiManager, this),
  21676. mustExec: true,
  21677. type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
  21678. overwriteIfSameType: true,
  21679. keepUndo: true
  21680. });
  21681. this._reportTelemetry({
  21682. action: "color_changed",
  21683. color: this._uiManager.highlightColorNames.get(color)
  21684. }, true);
  21685. }
  21686. #updateThickness(thickness) {
  21687. const savedThickness = this.#thickness;
  21688. const setThickness = th => {
  21689. this.#thickness = th;
  21690. this.#changeThickness(th);
  21691. };
  21692. this.addCommands({
  21693. cmd: setThickness.bind(this, thickness),
  21694. undo: setThickness.bind(this, savedThickness),
  21695. post: this._uiManager.updateUI.bind(this._uiManager, this),
  21696. mustExec: true,
  21697. type: AnnotationEditorParamsType.INK_THICKNESS,
  21698. overwriteIfSameType: true,
  21699. keepUndo: true
  21700. });
  21701. this._reportTelemetry({
  21702. action: "thickness_changed",
  21703. thickness
  21704. }, true);
  21705. }
  21706. async addEditToolbar() {
  21707. const toolbar = await super.addEditToolbar();
  21708. if (!toolbar) {
  21709. return null;
  21710. }
  21711. if (this._uiManager.highlightColors) {
  21712. this.#colorPicker = new ColorPicker({
  21713. editor: this
  21714. });
  21715. toolbar.addColorPicker(this.#colorPicker);
  21716. }
  21717. return toolbar;
  21718. }
  21719. disableEditing() {
  21720. super.disableEditing();
  21721. this.div.classList.toggle("disabled", true);
  21722. }
  21723. enableEditing() {
  21724. super.enableEditing();
  21725. this.div.classList.toggle("disabled", false);
  21726. }
  21727. fixAndSetPosition() {
  21728. return super.fixAndSetPosition(this.#getRotation());
  21729. }
  21730. getBaseTranslation() {
  21731. return [0, 0];
  21732. }
  21733. getRect(tx, ty) {
  21734. return super.getRect(tx, ty, this.#getRotation());
  21735. }
  21736. onceAdded(focus) {
  21737. if (!this.annotationElementId) {
  21738. this.parent.addUndoableEditor(this);
  21739. }
  21740. if (focus) {
  21741. this.div.focus();
  21742. }
  21743. }
  21744. remove() {
  21745. this.#cleanDrawLayer();
  21746. this._reportTelemetry({
  21747. action: "deleted"
  21748. });
  21749. super.remove();
  21750. }
  21751. rebuild() {
  21752. if (!this.parent) {
  21753. return;
  21754. }
  21755. super.rebuild();
  21756. if (this.div === null) {
  21757. return;
  21758. }
  21759. this.#addToDrawLayer();
  21760. if (!this.isAttachedToDOM) {
  21761. this.parent.add(this);
  21762. }
  21763. }
  21764. setParent(parent) {
  21765. let mustBeSelected = false;
  21766. if (this.parent && !parent) {
  21767. this.#cleanDrawLayer();
  21768. } else if (parent) {
  21769. this.#addToDrawLayer(parent);
  21770. mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
  21771. }
  21772. super.setParent(parent);
  21773. this.show(this._isVisible);
  21774. if (mustBeSelected) {
  21775. this.select();
  21776. }
  21777. }
  21778. #changeThickness(thickness) {
  21779. if (!this.#isFreeHighlight) {
  21780. return;
  21781. }
  21782. this.#createFreeOutlines({
  21783. highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
  21784. });
  21785. this.fixAndSetPosition();
  21786. const [parentWidth, parentHeight] = this.parentDimensions;
  21787. this.setDims(this.width * parentWidth, this.height * parentHeight);
  21788. }
  21789. #cleanDrawLayer() {
  21790. if (this.#id === null || !this.parent) {
  21791. return;
  21792. }
  21793. this.parent.drawLayer.remove(this.#id);
  21794. this.#id = null;
  21795. this.parent.drawLayer.remove(this.#outlineId);
  21796. this.#outlineId = null;
  21797. }
  21798. #addToDrawLayer(parent = this.parent) {
  21799. if (this.#id !== null) {
  21800. return;
  21801. }
  21802. ({
  21803. id: this.#id,
  21804. clipPathId: this.#clipPathId
  21805. } = parent.drawLayer.draw({
  21806. bbox: this.#highlightOutlines.box,
  21807. root: {
  21808. viewBox: "0 0 1 1",
  21809. fill: this.color,
  21810. "fill-opacity": this.#opacity
  21811. },
  21812. rootClass: {
  21813. highlight: true,
  21814. free: this.#isFreeHighlight
  21815. },
  21816. path: {
  21817. d: this.#highlightOutlines.toSVGPath()
  21818. }
  21819. }, false, true));
  21820. this.#outlineId = parent.drawLayer.drawOutline({
  21821. rootClass: {
  21822. highlightOutline: true,
  21823. free: this.#isFreeHighlight
  21824. },
  21825. bbox: this.#focusOutlines.box,
  21826. path: {
  21827. d: this.#focusOutlines.toSVGPath()
  21828. }
  21829. }, this.#isFreeHighlight);
  21830. if (this.#highlightDiv) {
  21831. this.#highlightDiv.style.clipPath = this.#clipPathId;
  21832. }
  21833. }
  21834. static #rotateBbox([x, y, width, height], angle) {
  21835. switch (angle) {
  21836. case 90:
  21837. return [1 - y - height, x, height, width];
  21838. case 180:
  21839. return [1 - x - width, 1 - y - height, width, height];
  21840. case 270:
  21841. return [y, 1 - x - width, height, width];
  21842. }
  21843. return [x, y, width, height];
  21844. }
  21845. rotate(angle) {
  21846. const {
  21847. drawLayer
  21848. } = this.parent;
  21849. let box;
  21850. if (this.#isFreeHighlight) {
  21851. angle = (angle - this.rotation + 360) % 360;
  21852. box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
  21853. } else {
  21854. box = HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle);
  21855. }
  21856. drawLayer.updateProperties(this.#id, {
  21857. bbox: box,
  21858. root: {
  21859. "data-main-rotation": angle
  21860. }
  21861. });
  21862. drawLayer.updateProperties(this.#outlineId, {
  21863. bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
  21864. root: {
  21865. "data-main-rotation": angle
  21866. }
  21867. });
  21868. }
  21869. render() {
  21870. if (this.div) {
  21871. return this.div;
  21872. }
  21873. const div = super.render();
  21874. if (this.#text) {
  21875. div.setAttribute("aria-label", this.#text);
  21876. div.setAttribute("role", "mark");
  21877. }
  21878. if (this.#isFreeHighlight) {
  21879. div.classList.add("free");
  21880. } else {
  21881. this.div.addEventListener("keydown", this.#keydown.bind(this), {
  21882. signal: this._uiManager._signal
  21883. });
  21884. }
  21885. const highlightDiv = this.#highlightDiv = document.createElement("div");
  21886. div.append(highlightDiv);
  21887. highlightDiv.setAttribute("aria-hidden", "true");
  21888. highlightDiv.className = "internal";
  21889. highlightDiv.style.clipPath = this.#clipPathId;
  21890. const [parentWidth, parentHeight] = this.parentDimensions;
  21891. this.setDims(this.width * parentWidth, this.height * parentHeight);
  21892. bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
  21893. this.enableEditing();
  21894. return div;
  21895. }
  21896. pointerover() {
  21897. if (!this.isSelected) {
  21898. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  21899. rootClass: {
  21900. hovered: true
  21901. }
  21902. });
  21903. }
  21904. }
  21905. pointerleave() {
  21906. if (!this.isSelected) {
  21907. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  21908. rootClass: {
  21909. hovered: false
  21910. }
  21911. });
  21912. }
  21913. }
  21914. #keydown(event) {
  21915. HighlightEditor._keyboardManager.exec(this, event);
  21916. }
  21917. _moveCaret(direction) {
  21918. this.parent.unselect(this);
  21919. switch (direction) {
  21920. case 0:
  21921. case 2:
  21922. this.#setCaret(true);
  21923. break;
  21924. case 1:
  21925. case 3:
  21926. this.#setCaret(false);
  21927. break;
  21928. }
  21929. }
  21930. #setCaret(start) {
  21931. if (!this.#anchorNode) {
  21932. return;
  21933. }
  21934. const selection = window.getSelection();
  21935. if (start) {
  21936. selection.setPosition(this.#anchorNode, this.#anchorOffset);
  21937. } else {
  21938. selection.setPosition(this.#focusNode, this.#focusOffset);
  21939. }
  21940. }
  21941. select() {
  21942. super.select();
  21943. if (!this.#outlineId) {
  21944. return;
  21945. }
  21946. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  21947. rootClass: {
  21948. hovered: false,
  21949. selected: true
  21950. }
  21951. });
  21952. }
  21953. unselect() {
  21954. super.unselect();
  21955. if (!this.#outlineId) {
  21956. return;
  21957. }
  21958. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  21959. rootClass: {
  21960. selected: false
  21961. }
  21962. });
  21963. if (!this.#isFreeHighlight) {
  21964. this.#setCaret(false);
  21965. }
  21966. }
  21967. get _mustFixPosition() {
  21968. return !this.#isFreeHighlight;
  21969. }
  21970. show(visible = this._isVisible) {
  21971. super.show(visible);
  21972. if (this.parent) {
  21973. this.parent.drawLayer.updateProperties(this.#id, {
  21974. rootClass: {
  21975. hidden: !visible
  21976. }
  21977. });
  21978. this.parent.drawLayer.updateProperties(this.#outlineId, {
  21979. rootClass: {
  21980. hidden: !visible
  21981. }
  21982. });
  21983. }
  21984. }
  21985. #getRotation() {
  21986. return this.#isFreeHighlight ? this.rotation : 0;
  21987. }
  21988. #serializeBoxes() {
  21989. if (this.#isFreeHighlight) {
  21990. return null;
  21991. }
  21992. const [pageWidth, pageHeight] = this.pageDimensions;
  21993. const [pageX, pageY] = this.pageTranslation;
  21994. const boxes = this.#boxes;
  21995. const quadPoints = new Float32Array(boxes.length * 8);
  21996. let i = 0;
  21997. for (const {
  21998. x,
  21999. y,
  22000. width,
  22001. height
  22002. } of boxes) {
  22003. const sx = x * pageWidth + pageX;
  22004. const sy = (1 - y) * pageHeight + pageY;
  22005. quadPoints[i] = quadPoints[i + 4] = sx;
  22006. quadPoints[i + 1] = quadPoints[i + 3] = sy;
  22007. quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth;
  22008. quadPoints[i + 5] = quadPoints[i + 7] = sy - height * pageHeight;
  22009. i += 8;
  22010. }
  22011. return quadPoints;
  22012. }
  22013. #serializeOutlines(rect) {
  22014. return this.#highlightOutlines.serialize(rect, this.#getRotation());
  22015. }
  22016. static startHighlighting(parent, isLTR, {
  22017. target: textLayer,
  22018. x,
  22019. y
  22020. }) {
  22021. const {
  22022. x: layerX,
  22023. y: layerY,
  22024. width: parentWidth,
  22025. height: parentHeight
  22026. } = textLayer.getBoundingClientRect();
  22027. const ac = new AbortController();
  22028. const signal = parent.combinedSignal(ac);
  22029. const pointerUpCallback = e => {
  22030. ac.abort();
  22031. this.#endHighlight(parent, e);
  22032. };
  22033. window.addEventListener("blur", pointerUpCallback, {
  22034. signal
  22035. });
  22036. window.addEventListener("pointerup", pointerUpCallback, {
  22037. signal
  22038. });
  22039. window.addEventListener("pointerdown", stopEvent, {
  22040. capture: true,
  22041. passive: false,
  22042. signal
  22043. });
  22044. window.addEventListener("contextmenu", noContextMenu, {
  22045. signal
  22046. });
  22047. textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {
  22048. signal
  22049. });
  22050. this._freeHighlight = new FreeHighlightOutliner({
  22051. x,
  22052. y
  22053. }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001);
  22054. ({
  22055. id: this._freeHighlightId,
  22056. clipPathId: this._freeHighlightClipId
  22057. } = parent.drawLayer.draw({
  22058. bbox: [0, 0, 1, 1],
  22059. root: {
  22060. viewBox: "0 0 1 1",
  22061. fill: this._defaultColor,
  22062. "fill-opacity": this._defaultOpacity
  22063. },
  22064. rootClass: {
  22065. highlight: true,
  22066. free: true
  22067. },
  22068. path: {
  22069. d: this._freeHighlight.toSVGPath()
  22070. }
  22071. }, true, true));
  22072. }
  22073. static #highlightMove(parent, event) {
  22074. if (this._freeHighlight.add(event)) {
  22075. parent.drawLayer.updateProperties(this._freeHighlightId, {
  22076. path: {
  22077. d: this._freeHighlight.toSVGPath()
  22078. }
  22079. });
  22080. }
  22081. }
  22082. static #endHighlight(parent, event) {
  22083. if (!this._freeHighlight.isEmpty()) {
  22084. parent.createAndAddNewEditor(event, false, {
  22085. highlightId: this._freeHighlightId,
  22086. highlightOutlines: this._freeHighlight.getOutlines(),
  22087. clipPathId: this._freeHighlightClipId,
  22088. methodOfCreation: "main_toolbar"
  22089. });
  22090. } else {
  22091. parent.drawLayer.remove(this._freeHighlightId);
  22092. }
  22093. this._freeHighlightId = -1;
  22094. this._freeHighlight = null;
  22095. this._freeHighlightClipId = "";
  22096. }
  22097. static async deserialize(data, parent, uiManager) {
  22098. let initialData = null;
  22099. if (data instanceof HighlightAnnotationElement) {
  22100. const {
  22101. data: {
  22102. quadPoints,
  22103. rect,
  22104. rotation,
  22105. id,
  22106. color,
  22107. opacity,
  22108. popupRef
  22109. },
  22110. parent: {
  22111. page: {
  22112. pageNumber
  22113. }
  22114. }
  22115. } = data;
  22116. initialData = data = {
  22117. annotationType: AnnotationEditorType.HIGHLIGHT,
  22118. color: Array.from(color),
  22119. opacity,
  22120. quadPoints,
  22121. boxes: null,
  22122. pageIndex: pageNumber - 1,
  22123. rect: rect.slice(0),
  22124. rotation,
  22125. id,
  22126. deleted: false,
  22127. popupRef
  22128. };
  22129. } else if (data instanceof InkAnnotationElement) {
  22130. const {
  22131. data: {
  22132. inkLists,
  22133. rect,
  22134. rotation,
  22135. id,
  22136. color,
  22137. borderStyle: {
  22138. rawWidth: thickness
  22139. },
  22140. popupRef
  22141. },
  22142. parent: {
  22143. page: {
  22144. pageNumber
  22145. }
  22146. }
  22147. } = data;
  22148. initialData = data = {
  22149. annotationType: AnnotationEditorType.HIGHLIGHT,
  22150. color: Array.from(color),
  22151. thickness,
  22152. inkLists,
  22153. boxes: null,
  22154. pageIndex: pageNumber - 1,
  22155. rect: rect.slice(0),
  22156. rotation,
  22157. id,
  22158. deleted: false,
  22159. popupRef
  22160. };
  22161. }
  22162. const {
  22163. color,
  22164. quadPoints,
  22165. inkLists,
  22166. opacity
  22167. } = data;
  22168. const editor = await super.deserialize(data, parent, uiManager);
  22169. editor.color = Util.makeHexColor(...color);
  22170. editor.#opacity = opacity || 1;
  22171. if (inkLists) {
  22172. editor.#thickness = data.thickness;
  22173. }
  22174. editor.annotationElementId = data.id || null;
  22175. editor._initialData = initialData;
  22176. const [pageWidth, pageHeight] = editor.pageDimensions;
  22177. const [pageX, pageY] = editor.pageTranslation;
  22178. if (quadPoints) {
  22179. const boxes = editor.#boxes = [];
  22180. for (let i = 0; i < quadPoints.length; i += 8) {
  22181. boxes.push({
  22182. x: (quadPoints[i] - pageX) / pageWidth,
  22183. y: 1 - (quadPoints[i + 1] - pageY) / pageHeight,
  22184. width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth,
  22185. height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight
  22186. });
  22187. }
  22188. editor.#createOutlines();
  22189. editor.#addToDrawLayer();
  22190. editor.rotate(editor.rotation);
  22191. } else if (inkLists) {
  22192. editor.#isFreeHighlight = true;
  22193. const points = inkLists[0];
  22194. const point = {
  22195. x: points[0] - pageX,
  22196. y: pageHeight - (points[1] - pageY)
  22197. };
  22198. const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001);
  22199. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22200. point.x = points[i] - pageX;
  22201. point.y = pageHeight - (points[i + 1] - pageY);
  22202. outliner.add(point);
  22203. }
  22204. const {
  22205. id,
  22206. clipPathId
  22207. } = parent.drawLayer.draw({
  22208. bbox: [0, 0, 1, 1],
  22209. root: {
  22210. viewBox: "0 0 1 1",
  22211. fill: editor.color,
  22212. "fill-opacity": editor._defaultOpacity
  22213. },
  22214. rootClass: {
  22215. highlight: true,
  22216. free: true
  22217. },
  22218. path: {
  22219. d: outliner.toSVGPath()
  22220. }
  22221. }, true, true);
  22222. editor.#createFreeOutlines({
  22223. highlightOutlines: outliner.getOutlines(),
  22224. highlightId: id,
  22225. clipPathId
  22226. });
  22227. editor.#addToDrawLayer();
  22228. editor.rotate(editor.parentRotation);
  22229. }
  22230. return editor;
  22231. }
  22232. serialize(isForCopying = false) {
  22233. if (this.isEmpty() || isForCopying) {
  22234. return null;
  22235. }
  22236. if (this.deleted) {
  22237. return this.serializeDeleted();
  22238. }
  22239. const rect = this.getRect(0, 0);
  22240. const color = AnnotationEditor._colorManager.convert(this.color);
  22241. const serialized = {
  22242. annotationType: AnnotationEditorType.HIGHLIGHT,
  22243. color,
  22244. opacity: this.#opacity,
  22245. thickness: this.#thickness,
  22246. quadPoints: this.#serializeBoxes(),
  22247. outlines: this.#serializeOutlines(rect),
  22248. pageIndex: this.pageIndex,
  22249. rect,
  22250. rotation: this.#getRotation(),
  22251. structTreeParentId: this._structTreeParentId
  22252. };
  22253. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  22254. return null;
  22255. }
  22256. serialized.id = this.annotationElementId;
  22257. return serialized;
  22258. }
  22259. #hasElementChanged(serialized) {
  22260. const {
  22261. color
  22262. } = this._initialData;
  22263. return serialized.color.some((c, i) => c !== color[i]);
  22264. }
  22265. renderAnnotationElement(annotation) {
  22266. annotation.updateEdited({
  22267. rect: this.getRect(0, 0)
  22268. });
  22269. return null;
  22270. }
  22271. static canCreateNewEmptyEditor() {
  22272. return false;
  22273. }
  22274. }
  22275. ;// ./src/display/editor/draw.js
  22276. class DrawingOptions {
  22277. #svgProperties = Object.create(null);
  22278. updateProperty(name, value) {
  22279. this[name] = value;
  22280. this.updateSVGProperty(name, value);
  22281. }
  22282. updateProperties(properties) {
  22283. if (!properties) {
  22284. return;
  22285. }
  22286. for (const [name, value] of Object.entries(properties)) {
  22287. if (!name.startsWith("_")) {
  22288. this.updateProperty(name, value);
  22289. }
  22290. }
  22291. }
  22292. updateSVGProperty(name, value) {
  22293. this.#svgProperties[name] = value;
  22294. }
  22295. toSVGProperties() {
  22296. const root = this.#svgProperties;
  22297. this.#svgProperties = Object.create(null);
  22298. return {
  22299. root
  22300. };
  22301. }
  22302. reset() {
  22303. this.#svgProperties = Object.create(null);
  22304. }
  22305. updateAll(options = this) {
  22306. this.updateProperties(options);
  22307. }
  22308. clone() {
  22309. unreachable("Not implemented");
  22310. }
  22311. }
  22312. class DrawingEditor extends AnnotationEditor {
  22313. #drawOutlines = null;
  22314. #mustBeCommitted;
  22315. _drawId = null;
  22316. static _currentDrawId = -1;
  22317. static _currentParent = null;
  22318. static #currentDraw = null;
  22319. static #currentDrawingAC = null;
  22320. static #currentDrawingOptions = null;
  22321. static #currentPointerId = NaN;
  22322. static #currentPointerType = null;
  22323. static #currentPointerIds = null;
  22324. static #currentMoveTimestamp = NaN;
  22325. static _INNER_MARGIN = 3;
  22326. constructor(params) {
  22327. super(params);
  22328. this.#mustBeCommitted = params.mustBeCommitted || false;
  22329. this._addOutlines(params);
  22330. }
  22331. _addOutlines(params) {
  22332. if (params.drawOutlines) {
  22333. this.#createDrawOutlines(params);
  22334. this.#addToDrawLayer();
  22335. }
  22336. }
  22337. #createDrawOutlines({
  22338. drawOutlines,
  22339. drawId,
  22340. drawingOptions
  22341. }) {
  22342. this.#drawOutlines = drawOutlines;
  22343. this._drawingOptions ||= drawingOptions;
  22344. if (drawId >= 0) {
  22345. this._drawId = drawId;
  22346. this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties);
  22347. } else {
  22348. this._drawId = this.#createDrawing(drawOutlines, this.parent);
  22349. }
  22350. this.#updateBbox(drawOutlines.box);
  22351. }
  22352. #createDrawing(drawOutlines, parent) {
  22353. const {
  22354. id
  22355. } = parent.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false);
  22356. return id;
  22357. }
  22358. static _mergeSVGProperties(p1, p2) {
  22359. const p1Keys = new Set(Object.keys(p1));
  22360. for (const [key, value] of Object.entries(p2)) {
  22361. if (p1Keys.has(key)) {
  22362. Object.assign(p1[key], value);
  22363. } else {
  22364. p1[key] = value;
  22365. }
  22366. }
  22367. return p1;
  22368. }
  22369. static getDefaultDrawingOptions(_options) {
  22370. unreachable("Not implemented");
  22371. }
  22372. static get typesMap() {
  22373. unreachable("Not implemented");
  22374. }
  22375. static get isDrawer() {
  22376. return true;
  22377. }
  22378. static get supportMultipleDrawings() {
  22379. return false;
  22380. }
  22381. static updateDefaultParams(type, value) {
  22382. const propertyName = this.typesMap.get(type);
  22383. if (propertyName) {
  22384. this._defaultDrawingOptions.updateProperty(propertyName, value);
  22385. }
  22386. if (this._currentParent) {
  22387. DrawingEditor.#currentDraw.updateProperty(propertyName, value);
  22388. this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
  22389. }
  22390. }
  22391. updateParams(type, value) {
  22392. const propertyName = this.constructor.typesMap.get(type);
  22393. if (propertyName) {
  22394. this._updateProperty(type, propertyName, value);
  22395. }
  22396. }
  22397. static get defaultPropertiesToUpdate() {
  22398. const properties = [];
  22399. const options = this._defaultDrawingOptions;
  22400. for (const [type, name] of this.typesMap) {
  22401. properties.push([type, options[name]]);
  22402. }
  22403. return properties;
  22404. }
  22405. get propertiesToUpdate() {
  22406. const properties = [];
  22407. const {
  22408. _drawingOptions
  22409. } = this;
  22410. for (const [type, name] of this.constructor.typesMap) {
  22411. properties.push([type, _drawingOptions[name]]);
  22412. }
  22413. return properties;
  22414. }
  22415. _updateProperty(type, name, value) {
  22416. const options = this._drawingOptions;
  22417. const savedValue = options[name];
  22418. const setter = val => {
  22419. options.updateProperty(name, val);
  22420. const bbox = this.#drawOutlines.updateProperty(name, val);
  22421. if (bbox) {
  22422. this.#updateBbox(bbox);
  22423. }
  22424. this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties());
  22425. };
  22426. this.addCommands({
  22427. cmd: setter.bind(this, value),
  22428. undo: setter.bind(this, savedValue),
  22429. post: this._uiManager.updateUI.bind(this._uiManager, this),
  22430. mustExec: true,
  22431. type,
  22432. overwriteIfSameType: true,
  22433. keepUndo: true
  22434. });
  22435. }
  22436. _onResizing() {
  22437. this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), {
  22438. bbox: this.#rotateBox()
  22439. }));
  22440. }
  22441. _onResized() {
  22442. this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), {
  22443. bbox: this.#rotateBox()
  22444. }));
  22445. }
  22446. _onTranslating(_x, _y) {
  22447. this.parent?.drawLayer.updateProperties(this._drawId, {
  22448. bbox: this.#rotateBox()
  22449. });
  22450. }
  22451. _onTranslated() {
  22452. this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), {
  22453. bbox: this.#rotateBox()
  22454. }));
  22455. }
  22456. _onStartDragging() {
  22457. this.parent?.drawLayer.updateProperties(this._drawId, {
  22458. rootClass: {
  22459. moving: true
  22460. }
  22461. });
  22462. }
  22463. _onStopDragging() {
  22464. this.parent?.drawLayer.updateProperties(this._drawId, {
  22465. rootClass: {
  22466. moving: false
  22467. }
  22468. });
  22469. }
  22470. commit() {
  22471. super.commit();
  22472. this.disableEditMode();
  22473. this.disableEditing();
  22474. }
  22475. disableEditing() {
  22476. super.disableEditing();
  22477. this.div.classList.toggle("disabled", true);
  22478. }
  22479. enableEditing() {
  22480. super.enableEditing();
  22481. this.div.classList.toggle("disabled", false);
  22482. }
  22483. getBaseTranslation() {
  22484. return [0, 0];
  22485. }
  22486. get isResizable() {
  22487. return true;
  22488. }
  22489. onceAdded(focus) {
  22490. if (!this.annotationElementId) {
  22491. this.parent.addUndoableEditor(this);
  22492. }
  22493. this._isDraggable = true;
  22494. if (this.#mustBeCommitted) {
  22495. this.#mustBeCommitted = false;
  22496. this.commit();
  22497. this.parent.setSelected(this);
  22498. if (focus && this.isOnScreen) {
  22499. this.div.focus();
  22500. }
  22501. }
  22502. }
  22503. remove() {
  22504. this.#cleanDrawLayer();
  22505. super.remove();
  22506. }
  22507. rebuild() {
  22508. if (!this.parent) {
  22509. return;
  22510. }
  22511. super.rebuild();
  22512. if (this.div === null) {
  22513. return;
  22514. }
  22515. this.#addToDrawLayer();
  22516. this.#updateBbox(this.#drawOutlines.box);
  22517. if (!this.isAttachedToDOM) {
  22518. this.parent.add(this);
  22519. }
  22520. }
  22521. setParent(parent) {
  22522. let mustBeSelected = false;
  22523. if (this.parent && !parent) {
  22524. this._uiManager.removeShouldRescale(this);
  22525. this.#cleanDrawLayer();
  22526. } else if (parent) {
  22527. this._uiManager.addShouldRescale(this);
  22528. this.#addToDrawLayer(parent);
  22529. mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
  22530. }
  22531. super.setParent(parent);
  22532. if (mustBeSelected) {
  22533. this.select();
  22534. }
  22535. }
  22536. #cleanDrawLayer() {
  22537. if (this._drawId === null || !this.parent) {
  22538. return;
  22539. }
  22540. this.parent.drawLayer.remove(this._drawId);
  22541. this._drawId = null;
  22542. this._drawingOptions.reset();
  22543. }
  22544. #addToDrawLayer(parent = this.parent) {
  22545. if (this._drawId !== null && this.parent === parent) {
  22546. return;
  22547. }
  22548. if (this._drawId !== null) {
  22549. this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer);
  22550. return;
  22551. }
  22552. this._drawingOptions.updateAll();
  22553. this._drawId = this.#createDrawing(this.#drawOutlines, parent);
  22554. }
  22555. #convertToParentSpace([x, y, width, height]) {
  22556. const {
  22557. parentDimensions: [pW, pH],
  22558. rotation
  22559. } = this;
  22560. switch (rotation) {
  22561. case 90:
  22562. return [y, 1 - x, width * (pH / pW), height * (pW / pH)];
  22563. case 180:
  22564. return [1 - x, 1 - y, width, height];
  22565. case 270:
  22566. return [1 - y, x, width * (pH / pW), height * (pW / pH)];
  22567. default:
  22568. return [x, y, width, height];
  22569. }
  22570. }
  22571. #convertToDrawSpace() {
  22572. const {
  22573. x,
  22574. y,
  22575. width,
  22576. height,
  22577. parentDimensions: [pW, pH],
  22578. rotation
  22579. } = this;
  22580. switch (rotation) {
  22581. case 90:
  22582. return [1 - y, x, width * (pW / pH), height * (pH / pW)];
  22583. case 180:
  22584. return [1 - x, 1 - y, width, height];
  22585. case 270:
  22586. return [y, 1 - x, width * (pW / pH), height * (pH / pW)];
  22587. default:
  22588. return [x, y, width, height];
  22589. }
  22590. }
  22591. #updateBbox(bbox) {
  22592. [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox);
  22593. if (this.div) {
  22594. this.fixAndSetPosition();
  22595. const [parentWidth, parentHeight] = this.parentDimensions;
  22596. this.setDims(this.width * parentWidth, this.height * parentHeight);
  22597. }
  22598. this._onResized();
  22599. }
  22600. #rotateBox() {
  22601. const {
  22602. x,
  22603. y,
  22604. width,
  22605. height,
  22606. rotation,
  22607. parentRotation,
  22608. parentDimensions: [pW, pH]
  22609. } = this;
  22610. switch ((rotation * 4 + parentRotation) / 90) {
  22611. case 1:
  22612. return [1 - y - height, x, height, width];
  22613. case 2:
  22614. return [1 - x - width, 1 - y - height, width, height];
  22615. case 3:
  22616. return [y, 1 - x - width, height, width];
  22617. case 4:
  22618. return [x, y - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
  22619. case 5:
  22620. return [1 - y, x, width * (pW / pH), height * (pH / pW)];
  22621. case 6:
  22622. return [1 - x - height * (pH / pW), 1 - y, height * (pH / pW), width * (pW / pH)];
  22623. case 7:
  22624. return [y - width * (pW / pH), 1 - x - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
  22625. case 8:
  22626. return [x - width, y - height, width, height];
  22627. case 9:
  22628. return [1 - y, x - width, height, width];
  22629. case 10:
  22630. return [1 - x, 1 - y, width, height];
  22631. case 11:
  22632. return [y - height, 1 - x, height, width];
  22633. case 12:
  22634. return [x - height * (pH / pW), y, height * (pH / pW), width * (pW / pH)];
  22635. case 13:
  22636. return [1 - y - width * (pW / pH), x - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
  22637. case 14:
  22638. return [1 - x, 1 - y - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
  22639. case 15:
  22640. return [y, 1 - x, width * (pW / pH), height * (pH / pW)];
  22641. default:
  22642. return [x, y, width, height];
  22643. }
  22644. }
  22645. rotate() {
  22646. if (!this.parent) {
  22647. return;
  22648. }
  22649. this.parent.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties({
  22650. bbox: this.#rotateBox()
  22651. }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360)));
  22652. }
  22653. onScaleChanging() {
  22654. if (!this.parent) {
  22655. return;
  22656. }
  22657. this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale));
  22658. }
  22659. static onScaleChangingWhenDrawing() {}
  22660. render() {
  22661. if (this.div) {
  22662. return this.div;
  22663. }
  22664. let baseX, baseY;
  22665. if (this._isCopy) {
  22666. baseX = this.x;
  22667. baseY = this.y;
  22668. }
  22669. const div = super.render();
  22670. div.classList.add("draw");
  22671. const drawDiv = document.createElement("div");
  22672. div.append(drawDiv);
  22673. drawDiv.setAttribute("aria-hidden", "true");
  22674. drawDiv.className = "internal";
  22675. const [parentWidth, parentHeight] = this.parentDimensions;
  22676. this.setDims(this.width * parentWidth, this.height * parentHeight);
  22677. this._uiManager.addShouldRescale(this);
  22678. this.disableEditing();
  22679. if (this._isCopy) {
  22680. this._moveAfterPaste(baseX, baseY);
  22681. }
  22682. return div;
  22683. }
  22684. static createDrawerInstance(_x, _y, _parentWidth, _parentHeight, _rotation) {
  22685. unreachable("Not implemented");
  22686. }
  22687. static startDrawing(parent, uiManager, _isLTR, event) {
  22688. const {
  22689. target,
  22690. offsetX: x,
  22691. offsetY: y,
  22692. pointerId,
  22693. pointerType
  22694. } = event;
  22695. if (DrawingEditor.#currentPointerType && DrawingEditor.#currentPointerType !== pointerType) {
  22696. return;
  22697. }
  22698. const {
  22699. viewport: {
  22700. rotation
  22701. }
  22702. } = parent;
  22703. const {
  22704. width: parentWidth,
  22705. height: parentHeight
  22706. } = target.getBoundingClientRect();
  22707. const ac = DrawingEditor.#currentDrawingAC = new AbortController();
  22708. const signal = parent.combinedSignal(ac);
  22709. DrawingEditor.#currentPointerId ||= pointerId;
  22710. DrawingEditor.#currentPointerType ??= pointerType;
  22711. window.addEventListener("pointerup", e => {
  22712. if (DrawingEditor.#currentPointerId === e.pointerId) {
  22713. this._endDraw(e);
  22714. } else {
  22715. DrawingEditor.#currentPointerIds?.delete(e.pointerId);
  22716. }
  22717. }, {
  22718. signal
  22719. });
  22720. window.addEventListener("pointercancel", e => {
  22721. if (DrawingEditor.#currentPointerId === e.pointerId) {
  22722. this._currentParent.endDrawingSession();
  22723. } else {
  22724. DrawingEditor.#currentPointerIds?.delete(e.pointerId);
  22725. }
  22726. }, {
  22727. signal
  22728. });
  22729. window.addEventListener("pointerdown", e => {
  22730. if (DrawingEditor.#currentPointerType !== e.pointerType) {
  22731. return;
  22732. }
  22733. (DrawingEditor.#currentPointerIds ||= new Set()).add(e.pointerId);
  22734. if (DrawingEditor.#currentDraw.isCancellable()) {
  22735. DrawingEditor.#currentDraw.removeLastElement();
  22736. if (DrawingEditor.#currentDraw.isEmpty()) {
  22737. this._currentParent.endDrawingSession(true);
  22738. } else {
  22739. this._endDraw(null);
  22740. }
  22741. }
  22742. }, {
  22743. capture: true,
  22744. passive: false,
  22745. signal
  22746. });
  22747. window.addEventListener("contextmenu", noContextMenu, {
  22748. signal
  22749. });
  22750. target.addEventListener("pointermove", this._drawMove.bind(this), {
  22751. signal
  22752. });
  22753. target.addEventListener("touchmove", e => {
  22754. if (e.timeStamp === DrawingEditor.#currentMoveTimestamp) {
  22755. stopEvent(e);
  22756. }
  22757. }, {
  22758. signal
  22759. });
  22760. parent.toggleDrawing();
  22761. uiManager._editorUndoBar?.hide();
  22762. if (DrawingEditor.#currentDraw) {
  22763. parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.startNew(x, y, parentWidth, parentHeight, rotation));
  22764. return;
  22765. }
  22766. uiManager.updateUIForDefaultProperties(this);
  22767. DrawingEditor.#currentDraw = this.createDrawerInstance(x, y, parentWidth, parentHeight, rotation);
  22768. DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions();
  22769. this._currentParent = parent;
  22770. ({
  22771. id: this._currentDrawId
  22772. } = parent.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#currentDrawingOptions.toSVGProperties(), DrawingEditor.#currentDraw.defaultSVGProperties), true, false));
  22773. }
  22774. static _drawMove(event) {
  22775. DrawingEditor.#currentMoveTimestamp = -1;
  22776. if (!DrawingEditor.#currentDraw) {
  22777. return;
  22778. }
  22779. const {
  22780. offsetX,
  22781. offsetY,
  22782. pointerId
  22783. } = event;
  22784. if (DrawingEditor.#currentPointerId !== pointerId) {
  22785. return;
  22786. }
  22787. if (DrawingEditor.#currentPointerIds?.size >= 1) {
  22788. this._endDraw(event);
  22789. return;
  22790. }
  22791. this._currentParent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.add(offsetX, offsetY));
  22792. DrawingEditor.#currentMoveTimestamp = event.timeStamp;
  22793. stopEvent(event);
  22794. }
  22795. static _cleanup(all) {
  22796. if (all) {
  22797. this._currentDrawId = -1;
  22798. this._currentParent = null;
  22799. DrawingEditor.#currentDraw = null;
  22800. DrawingEditor.#currentDrawingOptions = null;
  22801. DrawingEditor.#currentPointerType = null;
  22802. DrawingEditor.#currentMoveTimestamp = NaN;
  22803. }
  22804. if (DrawingEditor.#currentDrawingAC) {
  22805. DrawingEditor.#currentDrawingAC.abort();
  22806. DrawingEditor.#currentDrawingAC = null;
  22807. DrawingEditor.#currentPointerId = NaN;
  22808. DrawingEditor.#currentPointerIds = null;
  22809. }
  22810. }
  22811. static _endDraw(event) {
  22812. const parent = this._currentParent;
  22813. if (!parent) {
  22814. return;
  22815. }
  22816. parent.toggleDrawing(true);
  22817. this._cleanup(false);
  22818. if (event?.target === parent.div) {
  22819. parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY));
  22820. }
  22821. if (this.supportMultipleDrawings) {
  22822. const draw = DrawingEditor.#currentDraw;
  22823. const drawId = this._currentDrawId;
  22824. const lastElement = draw.getLastElement();
  22825. parent.addCommands({
  22826. cmd: () => {
  22827. parent.drawLayer.updateProperties(drawId, draw.setLastElement(lastElement));
  22828. },
  22829. undo: () => {
  22830. parent.drawLayer.updateProperties(drawId, draw.removeLastElement());
  22831. },
  22832. mustExec: false,
  22833. type: AnnotationEditorParamsType.DRAW_STEP
  22834. });
  22835. return;
  22836. }
  22837. this.endDrawing(false);
  22838. }
  22839. static endDrawing(isAborted) {
  22840. const parent = this._currentParent;
  22841. if (!parent) {
  22842. return null;
  22843. }
  22844. parent.toggleDrawing(true);
  22845. parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP);
  22846. if (!DrawingEditor.#currentDraw.isEmpty()) {
  22847. const {
  22848. pageDimensions: [pageWidth, pageHeight],
  22849. scale
  22850. } = parent;
  22851. const editor = parent.createAndAddNewEditor({
  22852. offsetX: 0,
  22853. offsetY: 0
  22854. }, false, {
  22855. drawId: this._currentDrawId,
  22856. drawOutlines: DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN),
  22857. drawingOptions: DrawingEditor.#currentDrawingOptions,
  22858. mustBeCommitted: !isAborted
  22859. });
  22860. this._cleanup(true);
  22861. return editor;
  22862. }
  22863. parent.drawLayer.remove(this._currentDrawId);
  22864. this._cleanup(true);
  22865. return null;
  22866. }
  22867. createDrawingOptions(_data) {}
  22868. static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) {
  22869. unreachable("Not implemented");
  22870. }
  22871. static async deserialize(data, parent, uiManager) {
  22872. const {
  22873. rawDims: {
  22874. pageWidth,
  22875. pageHeight,
  22876. pageX,
  22877. pageY
  22878. }
  22879. } = parent.viewport;
  22880. const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data);
  22881. const editor = await super.deserialize(data, parent, uiManager);
  22882. editor.createDrawingOptions(data);
  22883. editor.#createDrawOutlines({
  22884. drawOutlines
  22885. });
  22886. editor.#addToDrawLayer();
  22887. editor.onScaleChanging();
  22888. editor.rotate();
  22889. return editor;
  22890. }
  22891. serializeDraw(isForCopying) {
  22892. const [pageX, pageY] = this.pageTranslation;
  22893. const [pageWidth, pageHeight] = this.pageDimensions;
  22894. return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying);
  22895. }
  22896. renderAnnotationElement(annotation) {
  22897. annotation.updateEdited({
  22898. rect: this.getRect(0, 0)
  22899. });
  22900. return null;
  22901. }
  22902. static canCreateNewEmptyEditor() {
  22903. return false;
  22904. }
  22905. }
  22906. ;// ./src/display/editor/drawers/inkdraw.js
  22907. class InkDrawOutliner {
  22908. #last = new Float64Array(6);
  22909. #line;
  22910. #lines;
  22911. #rotation;
  22912. #thickness;
  22913. #points;
  22914. #lastSVGPath = "";
  22915. #lastIndex = 0;
  22916. #outlines = new InkDrawOutline();
  22917. #parentWidth;
  22918. #parentHeight;
  22919. constructor(x, y, parentWidth, parentHeight, rotation, thickness) {
  22920. this.#parentWidth = parentWidth;
  22921. this.#parentHeight = parentHeight;
  22922. this.#rotation = rotation;
  22923. this.#thickness = thickness;
  22924. [x, y] = this.#normalizePoint(x, y);
  22925. const line = this.#line = [NaN, NaN, NaN, NaN, x, y];
  22926. this.#points = [x, y];
  22927. this.#lines = [{
  22928. line,
  22929. points: this.#points
  22930. }];
  22931. this.#last.set(line, 0);
  22932. }
  22933. updateProperty(name, value) {
  22934. if (name === "stroke-width") {
  22935. this.#thickness = value;
  22936. }
  22937. }
  22938. #normalizePoint(x, y) {
  22939. return Outline._normalizePoint(x, y, this.#parentWidth, this.#parentHeight, this.#rotation);
  22940. }
  22941. isEmpty() {
  22942. return !this.#lines || this.#lines.length === 0;
  22943. }
  22944. isCancellable() {
  22945. return this.#points.length <= 10;
  22946. }
  22947. add(x, y) {
  22948. [x, y] = this.#normalizePoint(x, y);
  22949. const [x1, y1, x2, y2] = this.#last.subarray(2, 6);
  22950. const diffX = x - x2;
  22951. const diffY = y - y2;
  22952. const d = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY);
  22953. if (d <= 2) {
  22954. return null;
  22955. }
  22956. this.#points.push(x, y);
  22957. if (isNaN(x1)) {
  22958. this.#last.set([x2, y2, x, y], 2);
  22959. this.#line.push(NaN, NaN, NaN, NaN, x, y);
  22960. return {
  22961. path: {
  22962. d: this.toSVGPath()
  22963. }
  22964. };
  22965. }
  22966. if (isNaN(this.#last[0])) {
  22967. this.#line.splice(6, 6);
  22968. }
  22969. this.#last.set([x1, y1, x2, y2, x, y], 0);
  22970. this.#line.push(...Outline.createBezierPoints(x1, y1, x2, y2, x, y));
  22971. return {
  22972. path: {
  22973. d: this.toSVGPath()
  22974. }
  22975. };
  22976. }
  22977. end(x, y) {
  22978. const change = this.add(x, y);
  22979. if (change) {
  22980. return change;
  22981. }
  22982. if (this.#points.length === 2) {
  22983. return {
  22984. path: {
  22985. d: this.toSVGPath()
  22986. }
  22987. };
  22988. }
  22989. return null;
  22990. }
  22991. startNew(x, y, parentWidth, parentHeight, rotation) {
  22992. this.#parentWidth = parentWidth;
  22993. this.#parentHeight = parentHeight;
  22994. this.#rotation = rotation;
  22995. [x, y] = this.#normalizePoint(x, y);
  22996. const line = this.#line = [NaN, NaN, NaN, NaN, x, y];
  22997. this.#points = [x, y];
  22998. const last = this.#lines.at(-1);
  22999. if (last) {
  23000. last.line = new Float32Array(last.line);
  23001. last.points = new Float32Array(last.points);
  23002. }
  23003. this.#lines.push({
  23004. line,
  23005. points: this.#points
  23006. });
  23007. this.#last.set(line, 0);
  23008. this.#lastIndex = 0;
  23009. this.toSVGPath();
  23010. return null;
  23011. }
  23012. getLastElement() {
  23013. return this.#lines.at(-1);
  23014. }
  23015. setLastElement(element) {
  23016. if (!this.#lines) {
  23017. return this.#outlines.setLastElement(element);
  23018. }
  23019. this.#lines.push(element);
  23020. this.#line = element.line;
  23021. this.#points = element.points;
  23022. this.#lastIndex = 0;
  23023. return {
  23024. path: {
  23025. d: this.toSVGPath()
  23026. }
  23027. };
  23028. }
  23029. removeLastElement() {
  23030. if (!this.#lines) {
  23031. return this.#outlines.removeLastElement();
  23032. }
  23033. this.#lines.pop();
  23034. this.#lastSVGPath = "";
  23035. for (let i = 0, ii = this.#lines.length; i < ii; i++) {
  23036. const {
  23037. line,
  23038. points
  23039. } = this.#lines[i];
  23040. this.#line = line;
  23041. this.#points = points;
  23042. this.#lastIndex = 0;
  23043. this.toSVGPath();
  23044. }
  23045. return {
  23046. path: {
  23047. d: this.#lastSVGPath
  23048. }
  23049. };
  23050. }
  23051. toSVGPath() {
  23052. const firstX = Outline.svgRound(this.#line[4]);
  23053. const firstY = Outline.svgRound(this.#line[5]);
  23054. if (this.#points.length === 2) {
  23055. this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`;
  23056. return this.#lastSVGPath;
  23057. }
  23058. if (this.#points.length <= 6) {
  23059. const i = this.#lastSVGPath.lastIndexOf("M");
  23060. this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i)} M ${firstX} ${firstY}`;
  23061. this.#lastIndex = 6;
  23062. }
  23063. if (this.#points.length === 4) {
  23064. const secondX = Outline.svgRound(this.#line[10]);
  23065. const secondY = Outline.svgRound(this.#line[11]);
  23066. this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`;
  23067. this.#lastIndex = 12;
  23068. return this.#lastSVGPath;
  23069. }
  23070. const buffer = [];
  23071. if (this.#lastIndex === 0) {
  23072. buffer.push(`M ${firstX} ${firstY}`);
  23073. this.#lastIndex = 6;
  23074. }
  23075. for (let i = this.#lastIndex, ii = this.#line.length; i < ii; i += 6) {
  23076. const [c1x, c1y, c2x, c2y, x, y] = this.#line.slice(i, i + 6).map(Outline.svgRound);
  23077. buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`);
  23078. }
  23079. this.#lastSVGPath += buffer.join(" ");
  23080. this.#lastIndex = this.#line.length;
  23081. return this.#lastSVGPath;
  23082. }
  23083. getOutlines(parentWidth, parentHeight, scale, innerMargin) {
  23084. const last = this.#lines.at(-1);
  23085. last.line = new Float32Array(last.line);
  23086. last.points = new Float32Array(last.points);
  23087. this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin);
  23088. this.#last = null;
  23089. this.#line = null;
  23090. this.#lines = null;
  23091. this.#lastSVGPath = null;
  23092. return this.#outlines;
  23093. }
  23094. get defaultSVGProperties() {
  23095. return {
  23096. root: {
  23097. viewBox: "0 0 10000 10000"
  23098. },
  23099. rootClass: {
  23100. draw: true
  23101. },
  23102. bbox: [0, 0, 1, 1]
  23103. };
  23104. }
  23105. }
  23106. class InkDrawOutline extends Outline {
  23107. #bbox;
  23108. #currentRotation = 0;
  23109. #innerMargin;
  23110. #lines;
  23111. #parentWidth;
  23112. #parentHeight;
  23113. #parentScale;
  23114. #rotation;
  23115. #thickness;
  23116. build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) {
  23117. this.#parentWidth = parentWidth;
  23118. this.#parentHeight = parentHeight;
  23119. this.#parentScale = parentScale;
  23120. this.#rotation = rotation;
  23121. this.#thickness = thickness;
  23122. this.#innerMargin = innerMargin ?? 0;
  23123. this.#lines = lines;
  23124. this.#computeBbox();
  23125. }
  23126. get thickness() {
  23127. return this.#thickness;
  23128. }
  23129. setLastElement(element) {
  23130. this.#lines.push(element);
  23131. return {
  23132. path: {
  23133. d: this.toSVGPath()
  23134. }
  23135. };
  23136. }
  23137. removeLastElement() {
  23138. this.#lines.pop();
  23139. return {
  23140. path: {
  23141. d: this.toSVGPath()
  23142. }
  23143. };
  23144. }
  23145. toSVGPath() {
  23146. const buffer = [];
  23147. for (const {
  23148. line
  23149. } of this.#lines) {
  23150. buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`);
  23151. if (line.length === 6) {
  23152. buffer.push("Z");
  23153. continue;
  23154. }
  23155. if (line.length === 12 && isNaN(line[6])) {
  23156. buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`);
  23157. continue;
  23158. }
  23159. for (let i = 6, ii = line.length; i < ii; i += 6) {
  23160. const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6).map(Outline.svgRound);
  23161. buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`);
  23162. }
  23163. }
  23164. return buffer.join("");
  23165. }
  23166. serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) {
  23167. const serializedLines = [];
  23168. const serializedPoints = [];
  23169. const [x, y, width, height] = this.#getBBoxWithNoMargin();
  23170. let tx, ty, sx, sy, x1, y1, x2, y2, rescaleFn;
  23171. switch (this.#rotation) {
  23172. case 0:
  23173. rescaleFn = Outline._rescale;
  23174. tx = pageX;
  23175. ty = pageY + pageHeight;
  23176. sx = pageWidth;
  23177. sy = -pageHeight;
  23178. x1 = pageX + x * pageWidth;
  23179. y1 = pageY + (1 - y - height) * pageHeight;
  23180. x2 = pageX + (x + width) * pageWidth;
  23181. y2 = pageY + (1 - y) * pageHeight;
  23182. break;
  23183. case 90:
  23184. rescaleFn = Outline._rescaleAndSwap;
  23185. tx = pageX;
  23186. ty = pageY;
  23187. sx = pageWidth;
  23188. sy = pageHeight;
  23189. x1 = pageX + y * pageWidth;
  23190. y1 = pageY + x * pageHeight;
  23191. x2 = pageX + (y + height) * pageWidth;
  23192. y2 = pageY + (x + width) * pageHeight;
  23193. break;
  23194. case 180:
  23195. rescaleFn = Outline._rescale;
  23196. tx = pageX + pageWidth;
  23197. ty = pageY;
  23198. sx = -pageWidth;
  23199. sy = pageHeight;
  23200. x1 = pageX + (1 - x - width) * pageWidth;
  23201. y1 = pageY + y * pageHeight;
  23202. x2 = pageX + (1 - x) * pageWidth;
  23203. y2 = pageY + (y + height) * pageHeight;
  23204. break;
  23205. case 270:
  23206. rescaleFn = Outline._rescaleAndSwap;
  23207. tx = pageX + pageWidth;
  23208. ty = pageY + pageHeight;
  23209. sx = -pageWidth;
  23210. sy = -pageHeight;
  23211. x1 = pageX + (1 - y - height) * pageWidth;
  23212. y1 = pageY + (1 - x - width) * pageHeight;
  23213. x2 = pageX + (1 - y) * pageWidth;
  23214. y2 = pageY + (1 - x) * pageHeight;
  23215. break;
  23216. }
  23217. for (const {
  23218. line,
  23219. points
  23220. } of this.#lines) {
  23221. serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null));
  23222. serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null));
  23223. }
  23224. return {
  23225. lines: serializedLines,
  23226. points: serializedPoints,
  23227. rect: [x1, y1, x2, y2]
  23228. };
  23229. }
  23230. static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, {
  23231. paths: {
  23232. lines,
  23233. points
  23234. },
  23235. rotation,
  23236. thickness
  23237. }) {
  23238. const newLines = [];
  23239. let tx, ty, sx, sy, rescaleFn;
  23240. switch (rotation) {
  23241. case 0:
  23242. rescaleFn = Outline._rescale;
  23243. tx = -pageX / pageWidth;
  23244. ty = pageY / pageHeight + 1;
  23245. sx = 1 / pageWidth;
  23246. sy = -1 / pageHeight;
  23247. break;
  23248. case 90:
  23249. rescaleFn = Outline._rescaleAndSwap;
  23250. tx = -pageY / pageHeight;
  23251. ty = -pageX / pageWidth;
  23252. sx = 1 / pageHeight;
  23253. sy = 1 / pageWidth;
  23254. break;
  23255. case 180:
  23256. rescaleFn = Outline._rescale;
  23257. tx = pageX / pageWidth + 1;
  23258. ty = -pageY / pageHeight;
  23259. sx = -1 / pageWidth;
  23260. sy = 1 / pageHeight;
  23261. break;
  23262. case 270:
  23263. rescaleFn = Outline._rescaleAndSwap;
  23264. tx = pageY / pageHeight + 1;
  23265. ty = pageX / pageWidth + 1;
  23266. sx = -1 / pageHeight;
  23267. sy = -1 / pageWidth;
  23268. break;
  23269. }
  23270. if (!lines) {
  23271. lines = [];
  23272. for (const point of points) {
  23273. const len = point.length;
  23274. if (len === 2) {
  23275. lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]]));
  23276. continue;
  23277. }
  23278. if (len === 4) {
  23279. lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]]));
  23280. continue;
  23281. }
  23282. const line = new Float32Array(3 * (len - 2));
  23283. lines.push(line);
  23284. let [x1, y1, x2, y2] = point.subarray(0, 4);
  23285. line.set([NaN, NaN, NaN, NaN, x1, y1], 0);
  23286. for (let i = 4; i < len; i += 2) {
  23287. const x = point[i];
  23288. const y = point[i + 1];
  23289. line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3);
  23290. [x1, y1, x2, y2] = [x2, y2, x, y];
  23291. }
  23292. }
  23293. }
  23294. for (let i = 0, ii = lines.length; i < ii; i++) {
  23295. newLines.push({
  23296. line: rescaleFn(lines[i].map(x => x ?? NaN), tx, ty, sx, sy),
  23297. points: rescaleFn(points[i].map(x => x ?? NaN), tx, ty, sx, sy)
  23298. });
  23299. }
  23300. const outlines = new this.prototype.constructor();
  23301. outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin);
  23302. return outlines;
  23303. }
  23304. #getMarginComponents(thickness = this.#thickness) {
  23305. const margin = this.#innerMargin + thickness / 2 * this.#parentScale;
  23306. return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth];
  23307. }
  23308. #getBBoxWithNoMargin() {
  23309. const [x, y, width, height] = this.#bbox;
  23310. const [marginX, marginY] = this.#getMarginComponents(0);
  23311. return [x + marginX, y + marginY, width - 2 * marginX, height - 2 * marginY];
  23312. }
  23313. #computeBbox() {
  23314. const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
  23315. for (const {
  23316. line
  23317. } of this.#lines) {
  23318. if (line.length <= 12) {
  23319. for (let i = 4, ii = line.length; i < ii; i += 6) {
  23320. Util.pointBoundingBox(line[i], line[i + 1], bbox);
  23321. }
  23322. continue;
  23323. }
  23324. let lastX = line[4],
  23325. lastY = line[5];
  23326. for (let i = 6, ii = line.length; i < ii; i += 6) {
  23327. const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6);
  23328. Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x, y, bbox);
  23329. lastX = x;
  23330. lastY = y;
  23331. }
  23332. }
  23333. const [marginX, marginY] = this.#getMarginComponents();
  23334. bbox[0] = MathClamp(bbox[0] - marginX, 0, 1);
  23335. bbox[1] = MathClamp(bbox[1] - marginY, 0, 1);
  23336. bbox[2] = MathClamp(bbox[2] + marginX, 0, 1);
  23337. bbox[3] = MathClamp(bbox[3] + marginY, 0, 1);
  23338. bbox[2] -= bbox[0];
  23339. bbox[3] -= bbox[1];
  23340. }
  23341. get box() {
  23342. return this.#bbox;
  23343. }
  23344. updateProperty(name, value) {
  23345. if (name === "stroke-width") {
  23346. return this.#updateThickness(value);
  23347. }
  23348. return null;
  23349. }
  23350. #updateThickness(thickness) {
  23351. const [oldMarginX, oldMarginY] = this.#getMarginComponents();
  23352. this.#thickness = thickness;
  23353. const [newMarginX, newMarginY] = this.#getMarginComponents();
  23354. const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY];
  23355. const bbox = this.#bbox;
  23356. bbox[0] -= diffMarginX;
  23357. bbox[1] -= diffMarginY;
  23358. bbox[2] += 2 * diffMarginX;
  23359. bbox[3] += 2 * diffMarginY;
  23360. return bbox;
  23361. }
  23362. updateParentDimensions([width, height], scale) {
  23363. const [oldMarginX, oldMarginY] = this.#getMarginComponents();
  23364. this.#parentWidth = width;
  23365. this.#parentHeight = height;
  23366. this.#parentScale = scale;
  23367. const [newMarginX, newMarginY] = this.#getMarginComponents();
  23368. const diffMarginX = newMarginX - oldMarginX;
  23369. const diffMarginY = newMarginY - oldMarginY;
  23370. const bbox = this.#bbox;
  23371. bbox[0] -= diffMarginX;
  23372. bbox[1] -= diffMarginY;
  23373. bbox[2] += 2 * diffMarginX;
  23374. bbox[3] += 2 * diffMarginY;
  23375. return bbox;
  23376. }
  23377. updateRotation(rotation) {
  23378. this.#currentRotation = rotation;
  23379. return {
  23380. path: {
  23381. transform: this.rotationTransform
  23382. }
  23383. };
  23384. }
  23385. get viewBox() {
  23386. return this.#bbox.map(Outline.svgRound).join(" ");
  23387. }
  23388. get defaultProperties() {
  23389. const [x, y] = this.#bbox;
  23390. return {
  23391. root: {
  23392. viewBox: this.viewBox
  23393. },
  23394. path: {
  23395. "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`
  23396. }
  23397. };
  23398. }
  23399. get rotationTransform() {
  23400. const [,, width, height] = this.#bbox;
  23401. let a = 0,
  23402. b = 0,
  23403. c = 0,
  23404. d = 0,
  23405. e = 0,
  23406. f = 0;
  23407. switch (this.#currentRotation) {
  23408. case 90:
  23409. b = height / width;
  23410. c = -width / height;
  23411. e = width;
  23412. break;
  23413. case 180:
  23414. a = -1;
  23415. d = -1;
  23416. e = width;
  23417. f = height;
  23418. break;
  23419. case 270:
  23420. b = -height / width;
  23421. c = width / height;
  23422. f = height;
  23423. break;
  23424. default:
  23425. return "";
  23426. }
  23427. return `matrix(${a} ${b} ${c} ${d} ${Outline.svgRound(e)} ${Outline.svgRound(f)})`;
  23428. }
  23429. getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) {
  23430. const [marginX, marginY] = this.#getMarginComponents();
  23431. const [x, y, width, height] = this.#bbox;
  23432. if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
  23433. const tx = newX + newWidth / 2 - (x + width / 2);
  23434. const ty = newY + newHeight / 2 - (y + height / 2);
  23435. return {
  23436. path: {
  23437. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
  23438. transform: `${this.rotationTransform} translate(${tx} ${ty})`
  23439. }
  23440. };
  23441. }
  23442. const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
  23443. const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
  23444. const s2x = width / newWidth;
  23445. const s2y = height / newHeight;
  23446. return {
  23447. path: {
  23448. "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`,
  23449. transform: `${this.rotationTransform} scale(${s2x} ${s2y}) ` + `translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) ` + `translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})`
  23450. }
  23451. };
  23452. }
  23453. getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) {
  23454. const [marginX, marginY] = this.#getMarginComponents();
  23455. const bbox = this.#bbox;
  23456. const [x, y, width, height] = bbox;
  23457. bbox[0] = newX;
  23458. bbox[1] = newY;
  23459. bbox[2] = newWidth;
  23460. bbox[3] = newHeight;
  23461. if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
  23462. const tx = newX + newWidth / 2 - (x + width / 2);
  23463. const ty = newY + newHeight / 2 - (y + height / 2);
  23464. for (const {
  23465. line,
  23466. points
  23467. } of this.#lines) {
  23468. Outline._translate(line, tx, ty, line);
  23469. Outline._translate(points, tx, ty, points);
  23470. }
  23471. return {
  23472. root: {
  23473. viewBox: this.viewBox
  23474. },
  23475. path: {
  23476. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
  23477. transform: this.rotationTransform || null,
  23478. d: this.toSVGPath()
  23479. }
  23480. };
  23481. }
  23482. const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
  23483. const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
  23484. const tx = -s1x * (x + marginX) + newX + marginX;
  23485. const ty = -s1y * (y + marginY) + newY + marginY;
  23486. if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) {
  23487. for (const {
  23488. line,
  23489. points
  23490. } of this.#lines) {
  23491. Outline._rescale(line, tx, ty, s1x, s1y, line);
  23492. Outline._rescale(points, tx, ty, s1x, s1y, points);
  23493. }
  23494. }
  23495. return {
  23496. root: {
  23497. viewBox: this.viewBox
  23498. },
  23499. path: {
  23500. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
  23501. transform: this.rotationTransform || null,
  23502. d: this.toSVGPath()
  23503. }
  23504. };
  23505. }
  23506. getPathTranslatedSVGProperties([newX, newY], parentDimensions) {
  23507. const [newParentWidth, newParentHeight] = parentDimensions;
  23508. const bbox = this.#bbox;
  23509. const tx = newX - bbox[0];
  23510. const ty = newY - bbox[1];
  23511. if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) {
  23512. for (const {
  23513. line,
  23514. points
  23515. } of this.#lines) {
  23516. Outline._translate(line, tx, ty, line);
  23517. Outline._translate(points, tx, ty, points);
  23518. }
  23519. } else {
  23520. const sx = this.#parentWidth / newParentWidth;
  23521. const sy = this.#parentHeight / newParentHeight;
  23522. this.#parentWidth = newParentWidth;
  23523. this.#parentHeight = newParentHeight;
  23524. for (const {
  23525. line,
  23526. points
  23527. } of this.#lines) {
  23528. Outline._rescale(line, tx, ty, sx, sy, line);
  23529. Outline._rescale(points, tx, ty, sx, sy, points);
  23530. }
  23531. bbox[2] *= sx;
  23532. bbox[3] *= sy;
  23533. }
  23534. bbox[0] = newX;
  23535. bbox[1] = newY;
  23536. return {
  23537. root: {
  23538. viewBox: this.viewBox
  23539. },
  23540. path: {
  23541. d: this.toSVGPath(),
  23542. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`
  23543. }
  23544. };
  23545. }
  23546. get defaultSVGProperties() {
  23547. const bbox = this.#bbox;
  23548. return {
  23549. root: {
  23550. viewBox: this.viewBox
  23551. },
  23552. rootClass: {
  23553. draw: true
  23554. },
  23555. path: {
  23556. d: this.toSVGPath(),
  23557. "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`,
  23558. transform: this.rotationTransform || null
  23559. },
  23560. bbox
  23561. };
  23562. }
  23563. }
  23564. ;// ./src/display/editor/ink.js
  23565. class InkDrawingOptions extends DrawingOptions {
  23566. constructor(viewerParameters) {
  23567. super();
  23568. this._viewParameters = viewerParameters;
  23569. super.updateProperties({
  23570. fill: "none",
  23571. stroke: AnnotationEditor._defaultLineColor,
  23572. "stroke-opacity": 1,
  23573. "stroke-width": 1,
  23574. "stroke-linecap": "round",
  23575. "stroke-linejoin": "round",
  23576. "stroke-miterlimit": 10
  23577. });
  23578. }
  23579. updateSVGProperty(name, value) {
  23580. if (name === "stroke-width") {
  23581. value ??= this["stroke-width"];
  23582. value *= this._viewParameters.realScale;
  23583. }
  23584. super.updateSVGProperty(name, value);
  23585. }
  23586. clone() {
  23587. const clone = new InkDrawingOptions(this._viewParameters);
  23588. clone.updateAll(this);
  23589. return clone;
  23590. }
  23591. }
  23592. class InkEditor extends DrawingEditor {
  23593. static _type = "ink";
  23594. static _editorType = AnnotationEditorType.INK;
  23595. static _defaultDrawingOptions = null;
  23596. constructor(params) {
  23597. super({
  23598. ...params,
  23599. name: "inkEditor"
  23600. });
  23601. this._willKeepAspectRatio = true;
  23602. this.defaultL10nId = "pdfjs-editor-ink-editor";
  23603. }
  23604. static initialize(l10n, uiManager) {
  23605. AnnotationEditor.initialize(l10n, uiManager);
  23606. this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters);
  23607. }
  23608. static getDefaultDrawingOptions(options) {
  23609. const clone = this._defaultDrawingOptions.clone();
  23610. clone.updateProperties(options);
  23611. return clone;
  23612. }
  23613. static get supportMultipleDrawings() {
  23614. return true;
  23615. }
  23616. static get typesMap() {
  23617. return shadow(this, "typesMap", new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]]));
  23618. }
  23619. static createDrawerInstance(x, y, parentWidth, parentHeight, rotation) {
  23620. return new InkDrawOutliner(x, y, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]);
  23621. }
  23622. static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {
  23623. return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
  23624. }
  23625. static async deserialize(data, parent, uiManager) {
  23626. let initialData = null;
  23627. if (data instanceof InkAnnotationElement) {
  23628. const {
  23629. data: {
  23630. inkLists,
  23631. rect,
  23632. rotation,
  23633. id,
  23634. color,
  23635. opacity,
  23636. borderStyle: {
  23637. rawWidth: thickness
  23638. },
  23639. popupRef
  23640. },
  23641. parent: {
  23642. page: {
  23643. pageNumber
  23644. }
  23645. }
  23646. } = data;
  23647. initialData = data = {
  23648. annotationType: AnnotationEditorType.INK,
  23649. color: Array.from(color),
  23650. thickness,
  23651. opacity,
  23652. paths: {
  23653. points: inkLists
  23654. },
  23655. boxes: null,
  23656. pageIndex: pageNumber - 1,
  23657. rect: rect.slice(0),
  23658. rotation,
  23659. id,
  23660. deleted: false,
  23661. popupRef
  23662. };
  23663. }
  23664. const editor = await super.deserialize(data, parent, uiManager);
  23665. editor.annotationElementId = data.id || null;
  23666. editor._initialData = initialData;
  23667. return editor;
  23668. }
  23669. onScaleChanging() {
  23670. if (!this.parent) {
  23671. return;
  23672. }
  23673. super.onScaleChanging();
  23674. const {
  23675. _drawId,
  23676. _drawingOptions,
  23677. parent
  23678. } = this;
  23679. _drawingOptions.updateSVGProperty("stroke-width");
  23680. parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties());
  23681. }
  23682. static onScaleChangingWhenDrawing() {
  23683. const parent = this._currentParent;
  23684. if (!parent) {
  23685. return;
  23686. }
  23687. super.onScaleChangingWhenDrawing();
  23688. this._defaultDrawingOptions.updateSVGProperty("stroke-width");
  23689. parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
  23690. }
  23691. createDrawingOptions({
  23692. color,
  23693. thickness,
  23694. opacity
  23695. }) {
  23696. this._drawingOptions = InkEditor.getDefaultDrawingOptions({
  23697. stroke: Util.makeHexColor(...color),
  23698. "stroke-width": thickness,
  23699. "stroke-opacity": opacity
  23700. });
  23701. }
  23702. serialize(isForCopying = false) {
  23703. if (this.isEmpty()) {
  23704. return null;
  23705. }
  23706. if (this.deleted) {
  23707. return this.serializeDeleted();
  23708. }
  23709. const {
  23710. lines,
  23711. points,
  23712. rect
  23713. } = this.serializeDraw(isForCopying);
  23714. const {
  23715. _drawingOptions: {
  23716. stroke,
  23717. "stroke-opacity": opacity,
  23718. "stroke-width": thickness
  23719. }
  23720. } = this;
  23721. const serialized = {
  23722. annotationType: AnnotationEditorType.INK,
  23723. color: AnnotationEditor._colorManager.convert(stroke),
  23724. opacity,
  23725. thickness,
  23726. paths: {
  23727. lines,
  23728. points
  23729. },
  23730. pageIndex: this.pageIndex,
  23731. rect,
  23732. rotation: this.rotation,
  23733. structTreeParentId: this._structTreeParentId
  23734. };
  23735. if (isForCopying) {
  23736. serialized.isCopy = true;
  23737. return serialized;
  23738. }
  23739. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  23740. return null;
  23741. }
  23742. serialized.id = this.annotationElementId;
  23743. return serialized;
  23744. }
  23745. #hasElementChanged(serialized) {
  23746. const {
  23747. color,
  23748. thickness,
  23749. opacity,
  23750. pageIndex
  23751. } = this._initialData;
  23752. return this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c, i) => c !== color[i]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex;
  23753. }
  23754. renderAnnotationElement(annotation) {
  23755. const {
  23756. points,
  23757. rect
  23758. } = this.serializeDraw(false);
  23759. annotation.updateEdited({
  23760. rect,
  23761. thickness: this._drawingOptions["stroke-width"],
  23762. points
  23763. });
  23764. return null;
  23765. }
  23766. }
  23767. ;// ./src/display/editor/drawers/contour.js
  23768. class ContourDrawOutline extends InkDrawOutline {
  23769. toSVGPath() {
  23770. let path = super.toSVGPath();
  23771. if (!path.endsWith("Z")) {
  23772. path += "Z";
  23773. }
  23774. return path;
  23775. }
  23776. }
  23777. ;// ./src/display/editor/drawers/signaturedraw.js
  23778. const BASE_HEADER_LENGTH = 8;
  23779. const POINTS_PROPERTIES_NUMBER = 3;
  23780. class SignatureExtractor {
  23781. static #PARAMETERS = {
  23782. maxDim: 512,
  23783. sigmaSFactor: 0.02,
  23784. sigmaR: 25,
  23785. kernelSize: 16
  23786. };
  23787. static #neighborIndexToId(i0, j0, i, j) {
  23788. i -= i0;
  23789. j -= j0;
  23790. if (i === 0) {
  23791. return j > 0 ? 0 : 4;
  23792. }
  23793. if (i === 1) {
  23794. return j + 6;
  23795. }
  23796. return 2 - j;
  23797. }
  23798. static #neighborIdToIndex = new Int32Array([0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1, 1, 0, 1, 1]);
  23799. static #clockwiseNonZero(buf, width, i0, j0, i, j, offset) {
  23800. const id = this.#neighborIndexToId(i0, j0, i, j);
  23801. for (let k = 0; k < 8; k++) {
  23802. const kk = (-k + id - offset + 16) % 8;
  23803. const shiftI = this.#neighborIdToIndex[2 * kk];
  23804. const shiftJ = this.#neighborIdToIndex[2 * kk + 1];
  23805. if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {
  23806. return kk;
  23807. }
  23808. }
  23809. return -1;
  23810. }
  23811. static #counterClockwiseNonZero(buf, width, i0, j0, i, j, offset) {
  23812. const id = this.#neighborIndexToId(i0, j0, i, j);
  23813. for (let k = 0; k < 8; k++) {
  23814. const kk = (k + id + offset + 16) % 8;
  23815. const shiftI = this.#neighborIdToIndex[2 * kk];
  23816. const shiftJ = this.#neighborIdToIndex[2 * kk + 1];
  23817. if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {
  23818. return kk;
  23819. }
  23820. }
  23821. return -1;
  23822. }
  23823. static #findContours(buf, width, height, threshold) {
  23824. const N = buf.length;
  23825. const types = new Int32Array(N);
  23826. for (let i = 0; i < N; i++) {
  23827. types[i] = buf[i] <= threshold ? 1 : 0;
  23828. }
  23829. for (let i = 1; i < height - 1; i++) {
  23830. types[i * width] = types[i * width + width - 1] = 0;
  23831. }
  23832. for (let i = 0; i < width; i++) {
  23833. types[i] = types[width * height - 1 - i] = 0;
  23834. }
  23835. let nbd = 1;
  23836. let lnbd;
  23837. const contours = [];
  23838. for (let i = 1; i < height - 1; i++) {
  23839. lnbd = 1;
  23840. for (let j = 1; j < width - 1; j++) {
  23841. const ij = i * width + j;
  23842. const pix = types[ij];
  23843. if (pix === 0) {
  23844. continue;
  23845. }
  23846. let i2 = i;
  23847. let j2 = j;
  23848. if (pix === 1 && types[ij - 1] === 0) {
  23849. nbd += 1;
  23850. j2 -= 1;
  23851. } else if (pix >= 1 && types[ij + 1] === 0) {
  23852. nbd += 1;
  23853. j2 += 1;
  23854. if (pix > 1) {
  23855. lnbd = pix;
  23856. }
  23857. } else {
  23858. if (pix !== 1) {
  23859. lnbd = Math.abs(pix);
  23860. }
  23861. continue;
  23862. }
  23863. const points = [j, i];
  23864. const isHole = j2 === j + 1;
  23865. const contour = {
  23866. isHole,
  23867. points,
  23868. id: nbd,
  23869. parent: 0
  23870. };
  23871. contours.push(contour);
  23872. let contour0;
  23873. for (const c of contours) {
  23874. if (c.id === lnbd) {
  23875. contour0 = c;
  23876. break;
  23877. }
  23878. }
  23879. if (!contour0) {
  23880. contour.parent = isHole ? lnbd : 0;
  23881. } else if (contour0.isHole) {
  23882. contour.parent = isHole ? contour0.parent : lnbd;
  23883. } else {
  23884. contour.parent = isHole ? lnbd : contour0.parent;
  23885. }
  23886. const k = this.#clockwiseNonZero(types, width, i, j, i2, j2, 0);
  23887. if (k === -1) {
  23888. types[ij] = -nbd;
  23889. if (types[ij] !== 1) {
  23890. lnbd = Math.abs(types[ij]);
  23891. }
  23892. continue;
  23893. }
  23894. let shiftI = this.#neighborIdToIndex[2 * k];
  23895. let shiftJ = this.#neighborIdToIndex[2 * k + 1];
  23896. const i1 = i + shiftI;
  23897. const j1 = j + shiftJ;
  23898. i2 = i1;
  23899. j2 = j1;
  23900. let i3 = i;
  23901. let j3 = j;
  23902. while (true) {
  23903. const kk = this.#counterClockwiseNonZero(types, width, i3, j3, i2, j2, 1);
  23904. shiftI = this.#neighborIdToIndex[2 * kk];
  23905. shiftJ = this.#neighborIdToIndex[2 * kk + 1];
  23906. const i4 = i3 + shiftI;
  23907. const j4 = j3 + shiftJ;
  23908. points.push(j4, i4);
  23909. const ij3 = i3 * width + j3;
  23910. if (types[ij3 + 1] === 0) {
  23911. types[ij3] = -nbd;
  23912. } else if (types[ij3] === 1) {
  23913. types[ij3] = nbd;
  23914. }
  23915. if (i4 === i && j4 === j && i3 === i1 && j3 === j1) {
  23916. if (types[ij] !== 1) {
  23917. lnbd = Math.abs(types[ij]);
  23918. }
  23919. break;
  23920. } else {
  23921. i2 = i3;
  23922. j2 = j3;
  23923. i3 = i4;
  23924. j3 = j4;
  23925. }
  23926. }
  23927. }
  23928. }
  23929. return contours;
  23930. }
  23931. static #douglasPeuckerHelper(points, start, end, output) {
  23932. if (end - start <= 4) {
  23933. for (let i = start; i < end - 2; i += 2) {
  23934. output.push(points[i], points[i + 1]);
  23935. }
  23936. return;
  23937. }
  23938. const ax = points[start];
  23939. const ay = points[start + 1];
  23940. const abx = points[end - 4] - ax;
  23941. const aby = points[end - 3] - ay;
  23942. const dist = Math.hypot(abx, aby);
  23943. const nabx = abx / dist;
  23944. const naby = aby / dist;
  23945. const aa = nabx * ay - naby * ax;
  23946. const m = aby / abx;
  23947. const invS = 1 / dist;
  23948. const phi = Math.atan(m);
  23949. const cosPhi = Math.cos(phi);
  23950. const sinPhi = Math.sin(phi);
  23951. const tmax = invS * (Math.abs(cosPhi) + Math.abs(sinPhi));
  23952. const poly = invS * (1 - tmax + tmax ** 2);
  23953. const partialPhi = Math.max(Math.atan(Math.abs(sinPhi + cosPhi) * poly), Math.atan(Math.abs(sinPhi - cosPhi) * poly));
  23954. let dmax = 0;
  23955. let index = start;
  23956. for (let i = start + 2; i < end - 2; i += 2) {
  23957. const d = Math.abs(aa - nabx * points[i + 1] + naby * points[i]);
  23958. if (d > dmax) {
  23959. index = i;
  23960. dmax = d;
  23961. }
  23962. }
  23963. if (dmax > (dist * partialPhi) ** 2) {
  23964. this.#douglasPeuckerHelper(points, start, index + 2, output);
  23965. this.#douglasPeuckerHelper(points, index, end, output);
  23966. } else {
  23967. output.push(ax, ay);
  23968. }
  23969. }
  23970. static #douglasPeucker(points) {
  23971. const output = [];
  23972. const len = points.length;
  23973. this.#douglasPeuckerHelper(points, 0, len, output);
  23974. output.push(points[len - 2], points[len - 1]);
  23975. return output.length <= 4 ? null : output;
  23976. }
  23977. static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) {
  23978. const kernel = new Float32Array(kernelSize ** 2);
  23979. const sigmaS2 = -2 * sigmaS ** 2;
  23980. const halfSize = kernelSize >> 1;
  23981. for (let i = 0; i < kernelSize; i++) {
  23982. const x = (i - halfSize) ** 2;
  23983. for (let j = 0; j < kernelSize; j++) {
  23984. kernel[i * kernelSize + j] = Math.exp((x + (j - halfSize) ** 2) / sigmaS2);
  23985. }
  23986. }
  23987. const rangeValues = new Float32Array(256);
  23988. const sigmaR2 = -2 * sigmaR ** 2;
  23989. for (let i = 0; i < 256; i++) {
  23990. rangeValues[i] = Math.exp(i ** 2 / sigmaR2);
  23991. }
  23992. const N = buf.length;
  23993. const out = new Uint8Array(N);
  23994. const histogram = new Uint32Array(256);
  23995. for (let i = 0; i < height; i++) {
  23996. for (let j = 0; j < width; j++) {
  23997. const ij = i * width + j;
  23998. const center = buf[ij];
  23999. let sum = 0;
  24000. let norm = 0;
  24001. for (let k = 0; k < kernelSize; k++) {
  24002. const y = i + k - halfSize;
  24003. if (y < 0 || y >= height) {
  24004. continue;
  24005. }
  24006. for (let l = 0; l < kernelSize; l++) {
  24007. const x = j + l - halfSize;
  24008. if (x < 0 || x >= width) {
  24009. continue;
  24010. }
  24011. const neighbour = buf[y * width + x];
  24012. const w = kernel[k * kernelSize + l] * rangeValues[Math.abs(neighbour - center)];
  24013. sum += neighbour * w;
  24014. norm += w;
  24015. }
  24016. }
  24017. const pix = out[ij] = Math.round(sum / norm);
  24018. histogram[pix]++;
  24019. }
  24020. }
  24021. return [out, histogram];
  24022. }
  24023. static #getHistogram(buf) {
  24024. const histogram = new Uint32Array(256);
  24025. for (const g of buf) {
  24026. histogram[g]++;
  24027. }
  24028. return histogram;
  24029. }
  24030. static #toUint8(buf) {
  24031. const N = buf.length;
  24032. const out = new Uint8ClampedArray(N >> 2);
  24033. let max = -Infinity;
  24034. let min = Infinity;
  24035. for (let i = 0, ii = out.length; i < ii; i++) {
  24036. const A = buf[(i << 2) + 3];
  24037. if (A === 0) {
  24038. max = out[i] = 0xff;
  24039. continue;
  24040. }
  24041. const pix = out[i] = buf[i << 2];
  24042. if (pix > max) {
  24043. max = pix;
  24044. }
  24045. if (pix < min) {
  24046. min = pix;
  24047. }
  24048. }
  24049. const ratio = 255 / (max - min);
  24050. for (let i = 0; i < N; i++) {
  24051. out[i] = (out[i] - min) * ratio;
  24052. }
  24053. return out;
  24054. }
  24055. static #guessThreshold(histogram) {
  24056. let i;
  24057. let M = -Infinity;
  24058. let L = -Infinity;
  24059. const min = histogram.findIndex(v => v !== 0);
  24060. let pos = min;
  24061. let spos = min;
  24062. for (i = min; i < 256; i++) {
  24063. const v = histogram[i];
  24064. if (v > M) {
  24065. if (i - pos > L) {
  24066. L = i - pos;
  24067. spos = i - 1;
  24068. }
  24069. M = v;
  24070. pos = i;
  24071. }
  24072. }
  24073. for (i = spos - 1; i >= 0; i--) {
  24074. if (histogram[i] > histogram[i + 1]) {
  24075. break;
  24076. }
  24077. }
  24078. return i;
  24079. }
  24080. static #getGrayPixels(bitmap) {
  24081. const originalBitmap = bitmap;
  24082. const {
  24083. width,
  24084. height
  24085. } = bitmap;
  24086. const {
  24087. maxDim
  24088. } = this.#PARAMETERS;
  24089. let newWidth = width;
  24090. let newHeight = height;
  24091. if (width > maxDim || height > maxDim) {
  24092. let prevWidth = width;
  24093. let prevHeight = height;
  24094. let steps = Math.log2(Math.max(width, height) / maxDim);
  24095. const isteps = Math.floor(steps);
  24096. steps = steps === isteps ? isteps - 1 : isteps;
  24097. for (let i = 0; i < steps; i++) {
  24098. newWidth = Math.ceil(prevWidth / 2);
  24099. newHeight = Math.ceil(prevHeight / 2);
  24100. const offscreen = new OffscreenCanvas(newWidth, newHeight);
  24101. const ctx = offscreen.getContext("2d");
  24102. ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
  24103. prevWidth = newWidth;
  24104. prevHeight = newHeight;
  24105. if (bitmap !== originalBitmap) {
  24106. bitmap.close();
  24107. }
  24108. bitmap = offscreen.transferToImageBitmap();
  24109. }
  24110. const ratio = Math.min(maxDim / newWidth, maxDim / newHeight);
  24111. newWidth = Math.round(newWidth * ratio);
  24112. newHeight = Math.round(newHeight * ratio);
  24113. }
  24114. const offscreen = new OffscreenCanvas(newWidth, newHeight);
  24115. const ctx = offscreen.getContext("2d", {
  24116. willReadFrequently: true
  24117. });
  24118. ctx.filter = "grayscale(1)";
  24119. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newWidth, newHeight);
  24120. const grayImage = ctx.getImageData(0, 0, newWidth, newHeight).data;
  24121. const uint8Buf = this.#toUint8(grayImage);
  24122. return [uint8Buf, newWidth, newHeight];
  24123. }
  24124. static extractContoursFromText(text, {
  24125. fontFamily,
  24126. fontStyle,
  24127. fontWeight
  24128. }, pageWidth, pageHeight, rotation, innerMargin) {
  24129. let canvas = new OffscreenCanvas(1, 1);
  24130. let ctx = canvas.getContext("2d", {
  24131. alpha: false
  24132. });
  24133. const fontSize = 200;
  24134. const font = ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
  24135. const {
  24136. actualBoundingBoxLeft,
  24137. actualBoundingBoxRight,
  24138. actualBoundingBoxAscent,
  24139. actualBoundingBoxDescent,
  24140. fontBoundingBoxAscent,
  24141. fontBoundingBoxDescent,
  24142. width
  24143. } = ctx.measureText(text);
  24144. const SCALE = 1.5;
  24145. const canvasWidth = Math.ceil(Math.max(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight) || 0, width) * SCALE);
  24146. const canvasHeight = Math.ceil(Math.max(Math.abs(actualBoundingBoxAscent) + Math.abs(actualBoundingBoxDescent) || fontSize, Math.abs(fontBoundingBoxAscent) + Math.abs(fontBoundingBoxDescent) || fontSize) * SCALE);
  24147. canvas = new OffscreenCanvas(canvasWidth, canvasHeight);
  24148. ctx = canvas.getContext("2d", {
  24149. alpha: true,
  24150. willReadFrequently: true
  24151. });
  24152. ctx.font = font;
  24153. ctx.filter = "grayscale(1)";
  24154. ctx.fillStyle = "white";
  24155. ctx.fillRect(0, 0, canvasWidth, canvasHeight);
  24156. ctx.fillStyle = "black";
  24157. ctx.fillText(text, canvasWidth * (SCALE - 1) / 2, canvasHeight * (3 - SCALE) / 2);
  24158. const uint8Buf = this.#toUint8(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data);
  24159. const histogram = this.#getHistogram(uint8Buf);
  24160. const threshold = this.#guessThreshold(histogram);
  24161. const contourList = this.#findContours(uint8Buf, canvasWidth, canvasHeight, threshold);
  24162. return this.processDrawnLines({
  24163. lines: {
  24164. curves: contourList,
  24165. width: canvasWidth,
  24166. height: canvasHeight
  24167. },
  24168. pageWidth,
  24169. pageHeight,
  24170. rotation,
  24171. innerMargin,
  24172. mustSmooth: true,
  24173. areContours: true
  24174. });
  24175. }
  24176. static process(bitmap, pageWidth, pageHeight, rotation, innerMargin) {
  24177. const [uint8Buf, width, height] = this.#getGrayPixels(bitmap);
  24178. const [buffer, histogram] = this.#bilateralFilter(uint8Buf, width, height, Math.hypot(width, height) * this.#PARAMETERS.sigmaSFactor, this.#PARAMETERS.sigmaR, this.#PARAMETERS.kernelSize);
  24179. const threshold = this.#guessThreshold(histogram);
  24180. const contourList = this.#findContours(buffer, width, height, threshold);
  24181. return this.processDrawnLines({
  24182. lines: {
  24183. curves: contourList,
  24184. width,
  24185. height
  24186. },
  24187. pageWidth,
  24188. pageHeight,
  24189. rotation,
  24190. innerMargin,
  24191. mustSmooth: true,
  24192. areContours: true
  24193. });
  24194. }
  24195. static processDrawnLines({
  24196. lines,
  24197. pageWidth,
  24198. pageHeight,
  24199. rotation,
  24200. innerMargin,
  24201. mustSmooth,
  24202. areContours
  24203. }) {
  24204. if (rotation % 180 !== 0) {
  24205. [pageWidth, pageHeight] = [pageHeight, pageWidth];
  24206. }
  24207. const {
  24208. curves,
  24209. width,
  24210. height
  24211. } = lines;
  24212. const thickness = lines.thickness ?? 0;
  24213. const linesAndPoints = [];
  24214. const ratio = Math.min(pageWidth / width, pageHeight / height);
  24215. const xScale = ratio / pageWidth;
  24216. const yScale = ratio / pageHeight;
  24217. const newCurves = [];
  24218. for (const {
  24219. points
  24220. } of curves) {
  24221. const reducedPoints = mustSmooth ? this.#douglasPeucker(points) : points;
  24222. if (!reducedPoints) {
  24223. continue;
  24224. }
  24225. newCurves.push(reducedPoints);
  24226. const len = reducedPoints.length;
  24227. const newPoints = new Float32Array(len);
  24228. const line = new Float32Array(3 * (len === 2 ? 2 : len - 2));
  24229. linesAndPoints.push({
  24230. line,
  24231. points: newPoints
  24232. });
  24233. if (len === 2) {
  24234. newPoints[0] = reducedPoints[0] * xScale;
  24235. newPoints[1] = reducedPoints[1] * yScale;
  24236. line.set([NaN, NaN, NaN, NaN, newPoints[0], newPoints[1]], 0);
  24237. continue;
  24238. }
  24239. let [x1, y1, x2, y2] = reducedPoints;
  24240. x1 *= xScale;
  24241. y1 *= yScale;
  24242. x2 *= xScale;
  24243. y2 *= yScale;
  24244. newPoints.set([x1, y1, x2, y2], 0);
  24245. line.set([NaN, NaN, NaN, NaN, x1, y1], 0);
  24246. for (let i = 4; i < len; i += 2) {
  24247. const x = newPoints[i] = reducedPoints[i] * xScale;
  24248. const y = newPoints[i + 1] = reducedPoints[i + 1] * yScale;
  24249. line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3);
  24250. [x1, y1, x2, y2] = [x2, y2, x, y];
  24251. }
  24252. }
  24253. if (linesAndPoints.length === 0) {
  24254. return null;
  24255. }
  24256. const outline = areContours ? new ContourDrawOutline() : new InkDrawOutline();
  24257. outline.build(linesAndPoints, pageWidth, pageHeight, 1, rotation, areContours ? 0 : thickness, innerMargin);
  24258. return {
  24259. outline,
  24260. newCurves,
  24261. areContours,
  24262. thickness,
  24263. width,
  24264. height
  24265. };
  24266. }
  24267. static async compressSignature({
  24268. outlines,
  24269. areContours,
  24270. thickness,
  24271. width,
  24272. height
  24273. }) {
  24274. let minDiff = Infinity;
  24275. let maxDiff = -Infinity;
  24276. let outlinesLength = 0;
  24277. for (const points of outlines) {
  24278. outlinesLength += points.length;
  24279. for (let i = 2, ii = points.length; i < ii; i++) {
  24280. const dx = points[i] - points[i - 2];
  24281. minDiff = Math.min(minDiff, dx);
  24282. maxDiff = Math.max(maxDiff, dx);
  24283. }
  24284. }
  24285. let bufferType;
  24286. if (minDiff >= -128 && maxDiff <= 127) {
  24287. bufferType = Int8Array;
  24288. } else if (minDiff >= -32768 && maxDiff <= 32767) {
  24289. bufferType = Int16Array;
  24290. } else {
  24291. bufferType = Int32Array;
  24292. }
  24293. const len = outlines.length;
  24294. const headerLength = BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * len;
  24295. const header = new Uint32Array(headerLength);
  24296. let offset = 0;
  24297. header[offset++] = headerLength * Uint32Array.BYTES_PER_ELEMENT + (outlinesLength - 2 * len) * bufferType.BYTES_PER_ELEMENT;
  24298. header[offset++] = 0;
  24299. header[offset++] = width;
  24300. header[offset++] = height;
  24301. header[offset++] = areContours ? 0 : 1;
  24302. header[offset++] = Math.max(0, Math.floor(thickness ?? 0));
  24303. header[offset++] = len;
  24304. header[offset++] = bufferType.BYTES_PER_ELEMENT;
  24305. for (const points of outlines) {
  24306. header[offset++] = points.length - 2;
  24307. header[offset++] = points[0];
  24308. header[offset++] = points[1];
  24309. }
  24310. const cs = new CompressionStream("deflate-raw");
  24311. const writer = cs.writable.getWriter();
  24312. await writer.ready;
  24313. writer.write(header);
  24314. const BufferCtor = bufferType.prototype.constructor;
  24315. for (const points of outlines) {
  24316. const diffs = new BufferCtor(points.length - 2);
  24317. for (let i = 2, ii = points.length; i < ii; i++) {
  24318. diffs[i - 2] = points[i] - points[i - 2];
  24319. }
  24320. writer.write(diffs);
  24321. }
  24322. writer.close();
  24323. const buf = await new Response(cs.readable).arrayBuffer();
  24324. const bytes = new Uint8Array(buf);
  24325. return toBase64Util(bytes);
  24326. }
  24327. static async decompressSignature(signatureData) {
  24328. try {
  24329. const bytes = fromBase64Util(signatureData);
  24330. const {
  24331. readable,
  24332. writable
  24333. } = new DecompressionStream("deflate-raw");
  24334. const writer = writable.getWriter();
  24335. await writer.ready;
  24336. writer.write(bytes).then(async () => {
  24337. await writer.ready;
  24338. await writer.close();
  24339. }).catch(() => {});
  24340. let data = null;
  24341. let offset = 0;
  24342. for await (const chunk of readable) {
  24343. data ||= new Uint8Array(new Uint32Array(chunk.buffer, 0, 4)[0]);
  24344. data.set(chunk, offset);
  24345. offset += chunk.length;
  24346. }
  24347. const header = new Uint32Array(data.buffer, 0, data.length >> 2);
  24348. const version = header[1];
  24349. if (version !== 0) {
  24350. throw new Error(`Invalid version: ${version}`);
  24351. }
  24352. const width = header[2];
  24353. const height = header[3];
  24354. const areContours = header[4] === 0;
  24355. const thickness = header[5];
  24356. const numberOfDrawings = header[6];
  24357. const bufferType = header[7];
  24358. const outlines = [];
  24359. const diffsOffset = (BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * numberOfDrawings) * Uint32Array.BYTES_PER_ELEMENT;
  24360. let diffs;
  24361. switch (bufferType) {
  24362. case Int8Array.BYTES_PER_ELEMENT:
  24363. diffs = new Int8Array(data.buffer, diffsOffset);
  24364. break;
  24365. case Int16Array.BYTES_PER_ELEMENT:
  24366. diffs = new Int16Array(data.buffer, diffsOffset);
  24367. break;
  24368. case Int32Array.BYTES_PER_ELEMENT:
  24369. diffs = new Int32Array(data.buffer, diffsOffset);
  24370. break;
  24371. }
  24372. offset = 0;
  24373. for (let i = 0; i < numberOfDrawings; i++) {
  24374. const len = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH];
  24375. const points = new Float32Array(len + 2);
  24376. outlines.push(points);
  24377. for (let j = 0; j < POINTS_PROPERTIES_NUMBER - 1; j++) {
  24378. points[j] = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH + j + 1];
  24379. }
  24380. for (let j = 0; j < len; j++) {
  24381. points[j + 2] = points[j] + diffs[offset++];
  24382. }
  24383. }
  24384. return {
  24385. areContours,
  24386. thickness,
  24387. outlines,
  24388. width,
  24389. height
  24390. };
  24391. } catch (e) {
  24392. warn(`decompressSignature: ${e}`);
  24393. return null;
  24394. }
  24395. }
  24396. }
  24397. ;// ./src/display/editor/signature.js
  24398. class SignatureOptions extends DrawingOptions {
  24399. constructor() {
  24400. super();
  24401. super.updateProperties({
  24402. fill: AnnotationEditor._defaultLineColor,
  24403. "stroke-width": 0
  24404. });
  24405. }
  24406. clone() {
  24407. const clone = new SignatureOptions();
  24408. clone.updateAll(this);
  24409. return clone;
  24410. }
  24411. }
  24412. class DrawnSignatureOptions extends InkDrawingOptions {
  24413. constructor(viewerParameters) {
  24414. super(viewerParameters);
  24415. super.updateProperties({
  24416. stroke: AnnotationEditor._defaultLineColor,
  24417. "stroke-width": 1
  24418. });
  24419. }
  24420. clone() {
  24421. const clone = new DrawnSignatureOptions(this._viewParameters);
  24422. clone.updateAll(this);
  24423. return clone;
  24424. }
  24425. }
  24426. class SignatureEditor extends DrawingEditor {
  24427. #isExtracted = false;
  24428. #description = null;
  24429. #signatureData = null;
  24430. #signatureUUID = null;
  24431. static _type = "signature";
  24432. static _editorType = AnnotationEditorType.SIGNATURE;
  24433. static _defaultDrawingOptions = null;
  24434. constructor(params) {
  24435. super({
  24436. ...params,
  24437. mustBeCommitted: true,
  24438. name: "signatureEditor"
  24439. });
  24440. this._willKeepAspectRatio = true;
  24441. this.#signatureData = params.signatureData || null;
  24442. this.#description = null;
  24443. this.defaultL10nId = "pdfjs-editor-signature-editor1";
  24444. }
  24445. static initialize(l10n, uiManager) {
  24446. AnnotationEditor.initialize(l10n, uiManager);
  24447. this._defaultDrawingOptions = new SignatureOptions();
  24448. this._defaultDrawnSignatureOptions = new DrawnSignatureOptions(uiManager.viewParameters);
  24449. }
  24450. static getDefaultDrawingOptions(options) {
  24451. const clone = this._defaultDrawingOptions.clone();
  24452. clone.updateProperties(options);
  24453. return clone;
  24454. }
  24455. static get supportMultipleDrawings() {
  24456. return false;
  24457. }
  24458. static get typesMap() {
  24459. return shadow(this, "typesMap", new Map());
  24460. }
  24461. static get isDrawer() {
  24462. return false;
  24463. }
  24464. get telemetryFinalData() {
  24465. return {
  24466. type: "signature",
  24467. hasDescription: !!this.#description
  24468. };
  24469. }
  24470. static computeTelemetryFinalData(data) {
  24471. const hasDescriptionStats = data.get("hasDescription");
  24472. return {
  24473. hasAltText: hasDescriptionStats.get(true) ?? 0,
  24474. hasNoAltText: hasDescriptionStats.get(false) ?? 0
  24475. };
  24476. }
  24477. get isResizable() {
  24478. return true;
  24479. }
  24480. onScaleChanging() {
  24481. if (this._drawId === null) {
  24482. return;
  24483. }
  24484. super.onScaleChanging();
  24485. }
  24486. render() {
  24487. if (this.div) {
  24488. return this.div;
  24489. }
  24490. let baseX, baseY;
  24491. const {
  24492. _isCopy
  24493. } = this;
  24494. if (_isCopy) {
  24495. this._isCopy = false;
  24496. baseX = this.x;
  24497. baseY = this.y;
  24498. }
  24499. super.render();
  24500. if (this._drawId === null) {
  24501. if (this.#signatureData) {
  24502. const {
  24503. lines,
  24504. mustSmooth,
  24505. areContours,
  24506. description,
  24507. uuid,
  24508. heightInPage
  24509. } = this.#signatureData;
  24510. const {
  24511. rawDims: {
  24512. pageWidth,
  24513. pageHeight
  24514. },
  24515. rotation
  24516. } = this.parent.viewport;
  24517. const outline = SignatureExtractor.processDrawnLines({
  24518. lines,
  24519. pageWidth,
  24520. pageHeight,
  24521. rotation,
  24522. innerMargin: SignatureEditor._INNER_MARGIN,
  24523. mustSmooth,
  24524. areContours
  24525. });
  24526. this.addSignature(outline, heightInPage, description, uuid);
  24527. } else {
  24528. this.div.setAttribute("data-l10n-args", JSON.stringify({
  24529. description: ""
  24530. }));
  24531. this.div.hidden = true;
  24532. this._uiManager.getSignature(this);
  24533. }
  24534. }
  24535. if (_isCopy) {
  24536. this._isCopy = true;
  24537. this._moveAfterPaste(baseX, baseY);
  24538. }
  24539. return this.div;
  24540. }
  24541. setUuid(uuid) {
  24542. this.#signatureUUID = uuid;
  24543. this.addEditToolbar();
  24544. }
  24545. getUuid() {
  24546. return this.#signatureUUID;
  24547. }
  24548. get description() {
  24549. return this.#description;
  24550. }
  24551. set description(description) {
  24552. this.#description = description;
  24553. super.addEditToolbar().then(toolbar => {
  24554. toolbar?.updateEditSignatureButton(description);
  24555. });
  24556. }
  24557. getSignaturePreview() {
  24558. const {
  24559. newCurves,
  24560. areContours,
  24561. thickness,
  24562. width,
  24563. height
  24564. } = this.#signatureData;
  24565. const maxDim = Math.max(width, height);
  24566. const outlineData = SignatureExtractor.processDrawnLines({
  24567. lines: {
  24568. curves: newCurves.map(points => ({
  24569. points
  24570. })),
  24571. thickness,
  24572. width,
  24573. height
  24574. },
  24575. pageWidth: maxDim,
  24576. pageHeight: maxDim,
  24577. rotation: 0,
  24578. innerMargin: 0,
  24579. mustSmooth: false,
  24580. areContours
  24581. });
  24582. return {
  24583. areContours,
  24584. outline: outlineData.outline
  24585. };
  24586. }
  24587. async addEditToolbar() {
  24588. const toolbar = await super.addEditToolbar();
  24589. if (!toolbar) {
  24590. return null;
  24591. }
  24592. if (this._uiManager.signatureManager && this.#description !== null) {
  24593. await toolbar.addEditSignatureButton(this._uiManager.signatureManager, this.#signatureUUID, this.#description);
  24594. toolbar.show();
  24595. }
  24596. return toolbar;
  24597. }
  24598. addSignature(data, heightInPage, description, uuid) {
  24599. const {
  24600. x: savedX,
  24601. y: savedY
  24602. } = this;
  24603. const {
  24604. outline
  24605. } = this.#signatureData = data;
  24606. this.#isExtracted = outline instanceof ContourDrawOutline;
  24607. this.#description = description;
  24608. this.div.setAttribute("data-l10n-args", JSON.stringify({
  24609. description
  24610. }));
  24611. let drawingOptions;
  24612. if (this.#isExtracted) {
  24613. drawingOptions = SignatureEditor.getDefaultDrawingOptions();
  24614. } else {
  24615. drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone();
  24616. drawingOptions.updateProperties({
  24617. "stroke-width": outline.thickness
  24618. });
  24619. }
  24620. this._addOutlines({
  24621. drawOutlines: outline,
  24622. drawingOptions
  24623. });
  24624. const [parentWidth, parentHeight] = this.parentDimensions;
  24625. const [, pageHeight] = this.pageDimensions;
  24626. let newHeight = heightInPage / pageHeight;
  24627. newHeight = newHeight >= 1 ? 0.5 : newHeight;
  24628. this.width *= newHeight / this.height;
  24629. if (this.width >= 1) {
  24630. newHeight *= 0.9 / this.width;
  24631. this.width = 0.9;
  24632. }
  24633. this.height = newHeight;
  24634. this.setDims(parentWidth * this.width, parentHeight * this.height);
  24635. this.x = savedX;
  24636. this.y = savedY;
  24637. this.center();
  24638. this._onResized();
  24639. this.onScaleChanging();
  24640. this.rotate();
  24641. this._uiManager.addToAnnotationStorage(this);
  24642. this.setUuid(uuid);
  24643. this._reportTelemetry({
  24644. action: "pdfjs.signature.inserted",
  24645. data: {
  24646. hasBeenSaved: !!uuid,
  24647. hasDescription: !!description
  24648. }
  24649. });
  24650. this.div.hidden = false;
  24651. }
  24652. getFromImage(bitmap) {
  24653. const {
  24654. rawDims: {
  24655. pageWidth,
  24656. pageHeight
  24657. },
  24658. rotation
  24659. } = this.parent.viewport;
  24660. return SignatureExtractor.process(bitmap, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN);
  24661. }
  24662. getFromText(text, fontInfo) {
  24663. const {
  24664. rawDims: {
  24665. pageWidth,
  24666. pageHeight
  24667. },
  24668. rotation
  24669. } = this.parent.viewport;
  24670. return SignatureExtractor.extractContoursFromText(text, fontInfo, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN);
  24671. }
  24672. getDrawnSignature(curves) {
  24673. const {
  24674. rawDims: {
  24675. pageWidth,
  24676. pageHeight
  24677. },
  24678. rotation
  24679. } = this.parent.viewport;
  24680. return SignatureExtractor.processDrawnLines({
  24681. lines: curves,
  24682. pageWidth,
  24683. pageHeight,
  24684. rotation,
  24685. innerMargin: SignatureEditor._INNER_MARGIN,
  24686. mustSmooth: false,
  24687. areContours: false
  24688. });
  24689. }
  24690. createDrawingOptions({
  24691. areContours,
  24692. thickness
  24693. }) {
  24694. if (areContours) {
  24695. this._drawingOptions = SignatureEditor.getDefaultDrawingOptions();
  24696. } else {
  24697. this._drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone();
  24698. this._drawingOptions.updateProperties({
  24699. "stroke-width": thickness
  24700. });
  24701. }
  24702. }
  24703. serialize(isForCopying = false) {
  24704. if (this.isEmpty()) {
  24705. return null;
  24706. }
  24707. const {
  24708. lines,
  24709. points,
  24710. rect
  24711. } = this.serializeDraw(isForCopying);
  24712. const {
  24713. _drawingOptions: {
  24714. "stroke-width": thickness
  24715. }
  24716. } = this;
  24717. const serialized = {
  24718. annotationType: AnnotationEditorType.SIGNATURE,
  24719. isSignature: true,
  24720. areContours: this.#isExtracted,
  24721. color: [0, 0, 0],
  24722. thickness: this.#isExtracted ? 0 : thickness,
  24723. pageIndex: this.pageIndex,
  24724. rect,
  24725. rotation: this.rotation,
  24726. structTreeParentId: this._structTreeParentId
  24727. };
  24728. if (isForCopying) {
  24729. serialized.paths = {
  24730. lines,
  24731. points
  24732. };
  24733. serialized.uuid = this.#signatureUUID;
  24734. serialized.isCopy = true;
  24735. } else {
  24736. serialized.lines = lines;
  24737. }
  24738. if (this.#description) {
  24739. serialized.accessibilityData = {
  24740. type: "Figure",
  24741. alt: this.#description
  24742. };
  24743. }
  24744. return serialized;
  24745. }
  24746. static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {
  24747. if (data.areContours) {
  24748. return ContourDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
  24749. }
  24750. return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
  24751. }
  24752. static async deserialize(data, parent, uiManager) {
  24753. const editor = await super.deserialize(data, parent, uiManager);
  24754. editor.#isExtracted = data.areContours;
  24755. editor.#description = data.accessibilityData?.alt || "";
  24756. editor.#signatureUUID = data.uuid;
  24757. return editor;
  24758. }
  24759. }
  24760. ;// ./src/display/editor/stamp.js
  24761. class StampEditor extends AnnotationEditor {
  24762. #bitmap = null;
  24763. #bitmapId = null;
  24764. #bitmapPromise = null;
  24765. #bitmapUrl = null;
  24766. #bitmapFile = null;
  24767. #bitmapFileName = "";
  24768. #canvas = null;
  24769. #missingCanvas = false;
  24770. #resizeTimeoutId = null;
  24771. #isSvg = false;
  24772. #hasBeenAddedInUndoStack = false;
  24773. static _type = "stamp";
  24774. static _editorType = AnnotationEditorType.STAMP;
  24775. constructor(params) {
  24776. super({
  24777. ...params,
  24778. name: "stampEditor"
  24779. });
  24780. this.#bitmapUrl = params.bitmapUrl;
  24781. this.#bitmapFile = params.bitmapFile;
  24782. this.defaultL10nId = "pdfjs-editor-stamp-editor";
  24783. }
  24784. static initialize(l10n, uiManager) {
  24785. AnnotationEditor.initialize(l10n, uiManager);
  24786. }
  24787. static isHandlingMimeForPasting(mime) {
  24788. return SupportedImageMimeTypes.includes(mime);
  24789. }
  24790. static paste(item, parent) {
  24791. parent.pasteEditor({
  24792. mode: AnnotationEditorType.STAMP
  24793. }, {
  24794. bitmapFile: item.getAsFile()
  24795. });
  24796. }
  24797. altTextFinish() {
  24798. if (this._uiManager.useNewAltTextFlow) {
  24799. this.div.hidden = false;
  24800. }
  24801. super.altTextFinish();
  24802. }
  24803. get telemetryFinalData() {
  24804. return {
  24805. type: "stamp",
  24806. hasAltText: !!this.altTextData?.altText
  24807. };
  24808. }
  24809. static computeTelemetryFinalData(data) {
  24810. const hasAltTextStats = data.get("hasAltText");
  24811. return {
  24812. hasAltText: hasAltTextStats.get(true) ?? 0,
  24813. hasNoAltText: hasAltTextStats.get(false) ?? 0
  24814. };
  24815. }
  24816. #getBitmapFetched(data, fromId = false) {
  24817. if (!data) {
  24818. this.remove();
  24819. return;
  24820. }
  24821. this.#bitmap = data.bitmap;
  24822. if (!fromId) {
  24823. this.#bitmapId = data.id;
  24824. this.#isSvg = data.isSvg;
  24825. }
  24826. if (data.file) {
  24827. this.#bitmapFileName = data.file.name;
  24828. }
  24829. this.#createCanvas();
  24830. }
  24831. #getBitmapDone() {
  24832. this.#bitmapPromise = null;
  24833. this._uiManager.enableWaiting(false);
  24834. if (!this.#canvas) {
  24835. return;
  24836. }
  24837. if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  24838. this._editToolbar.hide();
  24839. this._uiManager.editAltText(this, true);
  24840. return;
  24841. }
  24842. if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  24843. this._reportTelemetry({
  24844. action: "pdfjs.image.image_added",
  24845. data: {
  24846. alt_text_modal: false,
  24847. alt_text_type: "empty"
  24848. }
  24849. });
  24850. try {
  24851. this.mlGuessAltText();
  24852. } catch {}
  24853. }
  24854. this.div.focus();
  24855. }
  24856. async mlGuessAltText(imageData = null, updateAltTextData = true) {
  24857. if (this.hasAltTextData()) {
  24858. return null;
  24859. }
  24860. const {
  24861. mlManager
  24862. } = this._uiManager;
  24863. if (!mlManager) {
  24864. throw new Error("No ML.");
  24865. }
  24866. if (!(await mlManager.isEnabledFor("altText"))) {
  24867. throw new Error("ML isn't enabled for alt text.");
  24868. }
  24869. const {
  24870. data,
  24871. width,
  24872. height
  24873. } = imageData || this.copyCanvas(null, null, true).imageData;
  24874. const response = await mlManager.guess({
  24875. name: "altText",
  24876. request: {
  24877. data,
  24878. width,
  24879. height,
  24880. channels: data.length / (width * height)
  24881. }
  24882. });
  24883. if (!response) {
  24884. throw new Error("No response from the AI service.");
  24885. }
  24886. if (response.error) {
  24887. throw new Error("Error from the AI service.");
  24888. }
  24889. if (response.cancel) {
  24890. return null;
  24891. }
  24892. if (!response.output) {
  24893. throw new Error("No valid response from the AI service.");
  24894. }
  24895. const altText = response.output;
  24896. await this.setGuessedAltText(altText);
  24897. if (updateAltTextData && !this.hasAltTextData()) {
  24898. this.altTextData = {
  24899. alt: altText,
  24900. decorative: false
  24901. };
  24902. }
  24903. return altText;
  24904. }
  24905. #getBitmap() {
  24906. if (this.#bitmapId) {
  24907. this._uiManager.enableWaiting(true);
  24908. this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
  24909. return;
  24910. }
  24911. if (this.#bitmapUrl) {
  24912. const url = this.#bitmapUrl;
  24913. this.#bitmapUrl = null;
  24914. this._uiManager.enableWaiting(true);
  24915. this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  24916. return;
  24917. }
  24918. if (this.#bitmapFile) {
  24919. const file = this.#bitmapFile;
  24920. this.#bitmapFile = null;
  24921. this._uiManager.enableWaiting(true);
  24922. this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  24923. return;
  24924. }
  24925. const input = document.createElement("input");
  24926. input.type = "file";
  24927. input.accept = SupportedImageMimeTypes.join(",");
  24928. const signal = this._uiManager._signal;
  24929. this.#bitmapPromise = new Promise(resolve => {
  24930. input.addEventListener("change", async () => {
  24931. if (!input.files || input.files.length === 0) {
  24932. this.remove();
  24933. } else {
  24934. this._uiManager.enableWaiting(true);
  24935. const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
  24936. this._reportTelemetry({
  24937. action: "pdfjs.image.image_selected",
  24938. data: {
  24939. alt_text_modal: this._uiManager.useNewAltTextFlow
  24940. }
  24941. });
  24942. this.#getBitmapFetched(data);
  24943. }
  24944. resolve();
  24945. }, {
  24946. signal
  24947. });
  24948. input.addEventListener("cancel", () => {
  24949. this.remove();
  24950. resolve();
  24951. }, {
  24952. signal
  24953. });
  24954. }).finally(() => this.#getBitmapDone());
  24955. input.click();
  24956. }
  24957. remove() {
  24958. if (this.#bitmapId) {
  24959. this.#bitmap = null;
  24960. this._uiManager.imageManager.deleteId(this.#bitmapId);
  24961. this.#canvas?.remove();
  24962. this.#canvas = null;
  24963. if (this.#resizeTimeoutId) {
  24964. clearTimeout(this.#resizeTimeoutId);
  24965. this.#resizeTimeoutId = null;
  24966. }
  24967. }
  24968. super.remove();
  24969. }
  24970. rebuild() {
  24971. if (!this.parent) {
  24972. if (this.#bitmapId) {
  24973. this.#getBitmap();
  24974. }
  24975. return;
  24976. }
  24977. super.rebuild();
  24978. if (this.div === null) {
  24979. return;
  24980. }
  24981. if (this.#bitmapId && this.#canvas === null) {
  24982. this.#getBitmap();
  24983. }
  24984. if (!this.isAttachedToDOM) {
  24985. this.parent.add(this);
  24986. }
  24987. }
  24988. onceAdded(focus) {
  24989. this._isDraggable = true;
  24990. if (focus) {
  24991. this.div.focus();
  24992. }
  24993. }
  24994. isEmpty() {
  24995. return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId || this.#missingCanvas);
  24996. }
  24997. get isResizable() {
  24998. return true;
  24999. }
  25000. render() {
  25001. if (this.div) {
  25002. return this.div;
  25003. }
  25004. let baseX, baseY;
  25005. if (this._isCopy) {
  25006. baseX = this.x;
  25007. baseY = this.y;
  25008. }
  25009. super.render();
  25010. this.div.hidden = true;
  25011. this.addAltTextButton();
  25012. if (!this.#missingCanvas) {
  25013. if (this.#bitmap) {
  25014. this.#createCanvas();
  25015. } else {
  25016. this.#getBitmap();
  25017. }
  25018. }
  25019. if (this._isCopy) {
  25020. this._moveAfterPaste(baseX, baseY);
  25021. }
  25022. this._uiManager.addShouldRescale(this);
  25023. return this.div;
  25024. }
  25025. setCanvas(annotationElementId, canvas) {
  25026. const {
  25027. id: bitmapId,
  25028. bitmap
  25029. } = this._uiManager.imageManager.getFromCanvas(annotationElementId, canvas);
  25030. canvas.remove();
  25031. if (bitmapId && this._uiManager.imageManager.isValidId(bitmapId)) {
  25032. this.#bitmapId = bitmapId;
  25033. if (bitmap) {
  25034. this.#bitmap = bitmap;
  25035. }
  25036. this.#missingCanvas = false;
  25037. this.#createCanvas();
  25038. }
  25039. }
  25040. _onResized() {
  25041. this.onScaleChanging();
  25042. }
  25043. onScaleChanging() {
  25044. if (!this.parent) {
  25045. return;
  25046. }
  25047. if (this.#resizeTimeoutId !== null) {
  25048. clearTimeout(this.#resizeTimeoutId);
  25049. }
  25050. const TIME_TO_WAIT = 200;
  25051. this.#resizeTimeoutId = setTimeout(() => {
  25052. this.#resizeTimeoutId = null;
  25053. this.#drawBitmap();
  25054. }, TIME_TO_WAIT);
  25055. }
  25056. #createCanvas() {
  25057. const {
  25058. div
  25059. } = this;
  25060. let {
  25061. width,
  25062. height
  25063. } = this.#bitmap;
  25064. const [pageWidth, pageHeight] = this.pageDimensions;
  25065. const MAX_RATIO = 0.75;
  25066. if (this.width) {
  25067. width = this.width * pageWidth;
  25068. height = this.height * pageHeight;
  25069. } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
  25070. const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
  25071. width *= factor;
  25072. height *= factor;
  25073. }
  25074. const [parentWidth, parentHeight] = this.parentDimensions;
  25075. this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight);
  25076. this._uiManager.enableWaiting(false);
  25077. const canvas = this.#canvas = document.createElement("canvas");
  25078. canvas.setAttribute("role", "img");
  25079. this.addContainer(canvas);
  25080. this.width = width / pageWidth;
  25081. this.height = height / pageHeight;
  25082. if (this._initialOptions?.isCentered) {
  25083. this.center();
  25084. } else {
  25085. this.fixAndSetPosition();
  25086. }
  25087. this._initialOptions = null;
  25088. if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {
  25089. div.hidden = false;
  25090. }
  25091. this.#drawBitmap();
  25092. if (!this.#hasBeenAddedInUndoStack) {
  25093. this.parent.addUndoableEditor(this);
  25094. this.#hasBeenAddedInUndoStack = true;
  25095. }
  25096. this._reportTelemetry({
  25097. action: "inserted_image"
  25098. });
  25099. if (this.#bitmapFileName) {
  25100. this.div.setAttribute("aria-description", this.#bitmapFileName);
  25101. }
  25102. }
  25103. copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {
  25104. if (!maxDataDimension) {
  25105. maxDataDimension = 224;
  25106. }
  25107. const {
  25108. width: bitmapWidth,
  25109. height: bitmapHeight
  25110. } = this.#bitmap;
  25111. const outputScale = new OutputScale();
  25112. let bitmap = this.#bitmap;
  25113. let width = bitmapWidth,
  25114. height = bitmapHeight;
  25115. let canvas = null;
  25116. if (maxPreviewDimension) {
  25117. if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {
  25118. const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);
  25119. width = Math.floor(bitmapWidth * ratio);
  25120. height = Math.floor(bitmapHeight * ratio);
  25121. }
  25122. canvas = document.createElement("canvas");
  25123. const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);
  25124. const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);
  25125. if (!this.#isSvg) {
  25126. bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);
  25127. }
  25128. const ctx = canvas.getContext("2d");
  25129. ctx.filter = this._uiManager.hcmFilter;
  25130. let white = "white",
  25131. black = "#cfcfd8";
  25132. if (this._uiManager.hcmFilter !== "none") {
  25133. black = "black";
  25134. } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
  25135. white = "#8f8f9d";
  25136. black = "#42414d";
  25137. }
  25138. const boxDim = 15;
  25139. const boxDimWidth = boxDim * outputScale.sx;
  25140. const boxDimHeight = boxDim * outputScale.sy;
  25141. const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);
  25142. const patternCtx = pattern.getContext("2d");
  25143. patternCtx.fillStyle = white;
  25144. patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);
  25145. patternCtx.fillStyle = black;
  25146. patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);
  25147. patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);
  25148. ctx.fillStyle = ctx.createPattern(pattern, "repeat");
  25149. ctx.fillRect(0, 0, scaledWidth, scaledHeight);
  25150. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  25151. }
  25152. let imageData = null;
  25153. if (createImageData) {
  25154. let dataWidth, dataHeight;
  25155. if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {
  25156. dataWidth = bitmap.width;
  25157. dataHeight = bitmap.height;
  25158. } else {
  25159. bitmap = this.#bitmap;
  25160. if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {
  25161. const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);
  25162. dataWidth = Math.floor(bitmapWidth * ratio);
  25163. dataHeight = Math.floor(bitmapHeight * ratio);
  25164. if (!this.#isSvg) {
  25165. bitmap = this.#scaleBitmap(dataWidth, dataHeight);
  25166. }
  25167. }
  25168. }
  25169. const offscreen = new OffscreenCanvas(dataWidth, dataHeight);
  25170. const offscreenCtx = offscreen.getContext("2d", {
  25171. willReadFrequently: true
  25172. });
  25173. offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);
  25174. imageData = {
  25175. width: dataWidth,
  25176. height: dataHeight,
  25177. data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data
  25178. };
  25179. }
  25180. return {
  25181. canvas,
  25182. width,
  25183. height,
  25184. imageData
  25185. };
  25186. }
  25187. #scaleBitmap(width, height) {
  25188. const {
  25189. width: bitmapWidth,
  25190. height: bitmapHeight
  25191. } = this.#bitmap;
  25192. let newWidth = bitmapWidth;
  25193. let newHeight = bitmapHeight;
  25194. let bitmap = this.#bitmap;
  25195. while (newWidth > 2 * width || newHeight > 2 * height) {
  25196. const prevWidth = newWidth;
  25197. const prevHeight = newHeight;
  25198. if (newWidth > 2 * width) {
  25199. newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
  25200. }
  25201. if (newHeight > 2 * height) {
  25202. newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
  25203. }
  25204. const offscreen = new OffscreenCanvas(newWidth, newHeight);
  25205. const ctx = offscreen.getContext("2d");
  25206. ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
  25207. bitmap = offscreen.transferToImageBitmap();
  25208. }
  25209. return bitmap;
  25210. }
  25211. #drawBitmap() {
  25212. const [parentWidth, parentHeight] = this.parentDimensions;
  25213. const {
  25214. width,
  25215. height
  25216. } = this;
  25217. const outputScale = new OutputScale();
  25218. const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx);
  25219. const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy);
  25220. const canvas = this.#canvas;
  25221. if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {
  25222. return;
  25223. }
  25224. canvas.width = scaledWidth;
  25225. canvas.height = scaledHeight;
  25226. const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);
  25227. const ctx = canvas.getContext("2d");
  25228. ctx.filter = this._uiManager.hcmFilter;
  25229. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  25230. }
  25231. #serializeBitmap(toUrl) {
  25232. if (toUrl) {
  25233. if (this.#isSvg) {
  25234. const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
  25235. if (url) {
  25236. return url;
  25237. }
  25238. }
  25239. const canvas = document.createElement("canvas");
  25240. ({
  25241. width: canvas.width,
  25242. height: canvas.height
  25243. } = this.#bitmap);
  25244. const ctx = canvas.getContext("2d");
  25245. ctx.drawImage(this.#bitmap, 0, 0);
  25246. return canvas.toDataURL();
  25247. }
  25248. if (this.#isSvg) {
  25249. const [pageWidth, pageHeight] = this.pageDimensions;
  25250. const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
  25251. const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
  25252. const offscreen = new OffscreenCanvas(width, height);
  25253. const ctx = offscreen.getContext("2d");
  25254. ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
  25255. return offscreen.transferToImageBitmap();
  25256. }
  25257. return structuredClone(this.#bitmap);
  25258. }
  25259. static async deserialize(data, parent, uiManager) {
  25260. let initialData = null;
  25261. let missingCanvas = false;
  25262. if (data instanceof StampAnnotationElement) {
  25263. const {
  25264. data: {
  25265. rect,
  25266. rotation,
  25267. id,
  25268. structParent,
  25269. popupRef
  25270. },
  25271. container,
  25272. parent: {
  25273. page: {
  25274. pageNumber
  25275. }
  25276. },
  25277. canvas
  25278. } = data;
  25279. let bitmapId, bitmap;
  25280. if (canvas) {
  25281. delete data.canvas;
  25282. ({
  25283. id: bitmapId,
  25284. bitmap
  25285. } = uiManager.imageManager.getFromCanvas(container.id, canvas));
  25286. canvas.remove();
  25287. } else {
  25288. missingCanvas = true;
  25289. data._hasNoCanvas = true;
  25290. }
  25291. const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";
  25292. initialData = data = {
  25293. annotationType: AnnotationEditorType.STAMP,
  25294. bitmapId,
  25295. bitmap,
  25296. pageIndex: pageNumber - 1,
  25297. rect: rect.slice(0),
  25298. rotation,
  25299. id,
  25300. deleted: false,
  25301. accessibilityData: {
  25302. decorative: false,
  25303. altText
  25304. },
  25305. isSvg: false,
  25306. structParent,
  25307. popupRef
  25308. };
  25309. }
  25310. const editor = await super.deserialize(data, parent, uiManager);
  25311. const {
  25312. rect,
  25313. bitmap,
  25314. bitmapUrl,
  25315. bitmapId,
  25316. isSvg,
  25317. accessibilityData
  25318. } = data;
  25319. if (missingCanvas) {
  25320. uiManager.addMissingCanvas(data.id, editor);
  25321. editor.#missingCanvas = true;
  25322. } else if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
  25323. editor.#bitmapId = bitmapId;
  25324. if (bitmap) {
  25325. editor.#bitmap = bitmap;
  25326. }
  25327. } else {
  25328. editor.#bitmapUrl = bitmapUrl;
  25329. }
  25330. editor.#isSvg = isSvg;
  25331. const [parentWidth, parentHeight] = editor.pageDimensions;
  25332. editor.width = (rect[2] - rect[0]) / parentWidth;
  25333. editor.height = (rect[3] - rect[1]) / parentHeight;
  25334. editor.annotationElementId = data.id || null;
  25335. if (accessibilityData) {
  25336. editor.altTextData = accessibilityData;
  25337. }
  25338. editor._initialData = initialData;
  25339. editor.#hasBeenAddedInUndoStack = !!initialData;
  25340. return editor;
  25341. }
  25342. serialize(isForCopying = false, context = null) {
  25343. if (this.isEmpty()) {
  25344. return null;
  25345. }
  25346. if (this.deleted) {
  25347. return this.serializeDeleted();
  25348. }
  25349. const serialized = {
  25350. annotationType: AnnotationEditorType.STAMP,
  25351. bitmapId: this.#bitmapId,
  25352. pageIndex: this.pageIndex,
  25353. rect: this.getRect(0, 0),
  25354. rotation: this.rotation,
  25355. isSvg: this.#isSvg,
  25356. structTreeParentId: this._structTreeParentId
  25357. };
  25358. if (isForCopying) {
  25359. serialized.bitmapUrl = this.#serializeBitmap(true);
  25360. serialized.accessibilityData = this.serializeAltText(true);
  25361. serialized.isCopy = true;
  25362. return serialized;
  25363. }
  25364. const {
  25365. decorative,
  25366. altText
  25367. } = this.serializeAltText(false);
  25368. if (!decorative && altText) {
  25369. serialized.accessibilityData = {
  25370. type: "Figure",
  25371. alt: altText
  25372. };
  25373. }
  25374. if (this.annotationElementId) {
  25375. const changes = this.#hasElementChanged(serialized);
  25376. if (changes.isSame) {
  25377. return null;
  25378. }
  25379. if (changes.isSameAltText) {
  25380. delete serialized.accessibilityData;
  25381. } else {
  25382. serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;
  25383. }
  25384. }
  25385. serialized.id = this.annotationElementId;
  25386. if (context === null) {
  25387. return serialized;
  25388. }
  25389. context.stamps ||= new Map();
  25390. const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
  25391. if (!context.stamps.has(this.#bitmapId)) {
  25392. context.stamps.set(this.#bitmapId, {
  25393. area,
  25394. serialized
  25395. });
  25396. serialized.bitmap = this.#serializeBitmap(false);
  25397. } else if (this.#isSvg) {
  25398. const prevData = context.stamps.get(this.#bitmapId);
  25399. if (area > prevData.area) {
  25400. prevData.area = area;
  25401. prevData.serialized.bitmap.close();
  25402. prevData.serialized.bitmap = this.#serializeBitmap(false);
  25403. }
  25404. }
  25405. return serialized;
  25406. }
  25407. #hasElementChanged(serialized) {
  25408. const {
  25409. pageIndex,
  25410. accessibilityData: {
  25411. altText
  25412. }
  25413. } = this._initialData;
  25414. const isSamePageIndex = serialized.pageIndex === pageIndex;
  25415. const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;
  25416. return {
  25417. isSame: !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText,
  25418. isSameAltText
  25419. };
  25420. }
  25421. renderAnnotationElement(annotation) {
  25422. annotation.updateEdited({
  25423. rect: this.getRect(0, 0)
  25424. });
  25425. return null;
  25426. }
  25427. }
  25428. ;// ./src/display/editor/annotation_editor_layer.js
  25429. class AnnotationEditorLayer {
  25430. #accessibilityManager;
  25431. #allowClick = false;
  25432. #annotationLayer = null;
  25433. #clickAC = null;
  25434. #editorFocusTimeoutId = null;
  25435. #editors = new Map();
  25436. #hadPointerDown = false;
  25437. #isDisabling = false;
  25438. #isEnabling = false;
  25439. #drawingAC = null;
  25440. #focusedElement = null;
  25441. #textLayer = null;
  25442. #textSelectionAC = null;
  25443. #uiManager;
  25444. static _initialized = false;
  25445. static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor, SignatureEditor].map(type => [type._editorType, type]));
  25446. constructor({
  25447. uiManager,
  25448. pageIndex,
  25449. div,
  25450. structTreeLayer,
  25451. accessibilityManager,
  25452. annotationLayer,
  25453. drawLayer,
  25454. textLayer,
  25455. viewport,
  25456. l10n
  25457. }) {
  25458. const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()];
  25459. if (!AnnotationEditorLayer._initialized) {
  25460. AnnotationEditorLayer._initialized = true;
  25461. for (const editorType of editorTypes) {
  25462. editorType.initialize(l10n, uiManager);
  25463. }
  25464. }
  25465. uiManager.registerEditorTypes(editorTypes);
  25466. this.#uiManager = uiManager;
  25467. this.pageIndex = pageIndex;
  25468. this.div = div;
  25469. this.#accessibilityManager = accessibilityManager;
  25470. this.#annotationLayer = annotationLayer;
  25471. this.viewport = viewport;
  25472. this.#textLayer = textLayer;
  25473. this.drawLayer = drawLayer;
  25474. this._structTree = structTreeLayer;
  25475. this.#uiManager.addLayer(this);
  25476. }
  25477. get isEmpty() {
  25478. return this.#editors.size === 0;
  25479. }
  25480. get isInvisible() {
  25481. return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
  25482. }
  25483. updateToolbar(options) {
  25484. this.#uiManager.updateToolbar(options);
  25485. }
  25486. updateMode(mode = this.#uiManager.getMode()) {
  25487. this.#cleanup();
  25488. switch (mode) {
  25489. case AnnotationEditorType.NONE:
  25490. this.disableTextSelection();
  25491. this.togglePointerEvents(false);
  25492. this.toggleAnnotationLayerPointerEvents(true);
  25493. this.disableClick();
  25494. return;
  25495. case AnnotationEditorType.INK:
  25496. this.disableTextSelection();
  25497. this.togglePointerEvents(true);
  25498. this.enableClick();
  25499. break;
  25500. case AnnotationEditorType.HIGHLIGHT:
  25501. this.enableTextSelection();
  25502. this.togglePointerEvents(false);
  25503. this.disableClick();
  25504. break;
  25505. default:
  25506. this.disableTextSelection();
  25507. this.togglePointerEvents(true);
  25508. this.enableClick();
  25509. }
  25510. this.toggleAnnotationLayerPointerEvents(false);
  25511. const {
  25512. classList
  25513. } = this.div;
  25514. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  25515. classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
  25516. }
  25517. this.div.hidden = false;
  25518. }
  25519. hasTextLayer(textLayer) {
  25520. return textLayer === this.#textLayer?.div;
  25521. }
  25522. setEditingState(isEditing) {
  25523. this.#uiManager.setEditingState(isEditing);
  25524. }
  25525. addCommands(params) {
  25526. this.#uiManager.addCommands(params);
  25527. }
  25528. cleanUndoStack(type) {
  25529. this.#uiManager.cleanUndoStack(type);
  25530. }
  25531. toggleDrawing(enabled = false) {
  25532. this.div.classList.toggle("drawing", !enabled);
  25533. }
  25534. togglePointerEvents(enabled = false) {
  25535. this.div.classList.toggle("disabled", !enabled);
  25536. }
  25537. toggleAnnotationLayerPointerEvents(enabled = false) {
  25538. this.#annotationLayer?.div.classList.toggle("disabled", !enabled);
  25539. }
  25540. async enable() {
  25541. this.#isEnabling = true;
  25542. this.div.tabIndex = 0;
  25543. this.togglePointerEvents(true);
  25544. const annotationElementIds = new Set();
  25545. for (const editor of this.#editors.values()) {
  25546. editor.enableEditing();
  25547. editor.show(true);
  25548. if (editor.annotationElementId) {
  25549. this.#uiManager.removeChangedExistingAnnotation(editor);
  25550. annotationElementIds.add(editor.annotationElementId);
  25551. }
  25552. }
  25553. if (!this.#annotationLayer) {
  25554. this.#isEnabling = false;
  25555. return;
  25556. }
  25557. const editables = this.#annotationLayer.getEditableAnnotations();
  25558. for (const editable of editables) {
  25559. editable.hide();
  25560. if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
  25561. continue;
  25562. }
  25563. if (annotationElementIds.has(editable.data.id)) {
  25564. continue;
  25565. }
  25566. const editor = await this.deserialize(editable);
  25567. if (!editor) {
  25568. continue;
  25569. }
  25570. this.addOrRebuild(editor);
  25571. editor.enableEditing();
  25572. }
  25573. this.#isEnabling = false;
  25574. }
  25575. disable() {
  25576. this.#isDisabling = true;
  25577. this.div.tabIndex = -1;
  25578. this.togglePointerEvents(false);
  25579. const changedAnnotations = new Map();
  25580. const resetAnnotations = new Map();
  25581. for (const editor of this.#editors.values()) {
  25582. editor.disableEditing();
  25583. if (!editor.annotationElementId) {
  25584. continue;
  25585. }
  25586. if (editor.serialize() !== null) {
  25587. changedAnnotations.set(editor.annotationElementId, editor);
  25588. continue;
  25589. } else {
  25590. resetAnnotations.set(editor.annotationElementId, editor);
  25591. }
  25592. this.getEditableAnnotation(editor.annotationElementId)?.show();
  25593. editor.remove();
  25594. }
  25595. if (this.#annotationLayer) {
  25596. const editables = this.#annotationLayer.getEditableAnnotations();
  25597. for (const editable of editables) {
  25598. const {
  25599. id
  25600. } = editable.data;
  25601. if (this.#uiManager.isDeletedAnnotationElement(id)) {
  25602. continue;
  25603. }
  25604. let editor = resetAnnotations.get(id);
  25605. if (editor) {
  25606. editor.resetAnnotationElement(editable);
  25607. editor.show(false);
  25608. editable.show();
  25609. continue;
  25610. }
  25611. editor = changedAnnotations.get(id);
  25612. if (editor) {
  25613. this.#uiManager.addChangedExistingAnnotation(editor);
  25614. if (editor.renderAnnotationElement(editable)) {
  25615. editor.show(false);
  25616. }
  25617. }
  25618. editable.show();
  25619. }
  25620. }
  25621. this.#cleanup();
  25622. if (this.isEmpty) {
  25623. this.div.hidden = true;
  25624. }
  25625. const {
  25626. classList
  25627. } = this.div;
  25628. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  25629. classList.remove(`${editorType._type}Editing`);
  25630. }
  25631. this.disableTextSelection();
  25632. this.toggleAnnotationLayerPointerEvents(true);
  25633. this.#isDisabling = false;
  25634. }
  25635. getEditableAnnotation(id) {
  25636. return this.#annotationLayer?.getEditableAnnotation(id) || null;
  25637. }
  25638. setActiveEditor(editor) {
  25639. const currentActive = this.#uiManager.getActive();
  25640. if (currentActive === editor) {
  25641. return;
  25642. }
  25643. this.#uiManager.setActiveEditor(editor);
  25644. }
  25645. enableTextSelection() {
  25646. this.div.tabIndex = -1;
  25647. if (this.#textLayer?.div && !this.#textSelectionAC) {
  25648. this.#textSelectionAC = new AbortController();
  25649. const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);
  25650. this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {
  25651. signal
  25652. });
  25653. this.#textLayer.div.classList.add("highlighting");
  25654. }
  25655. }
  25656. disableTextSelection() {
  25657. this.div.tabIndex = 0;
  25658. if (this.#textLayer?.div && this.#textSelectionAC) {
  25659. this.#textSelectionAC.abort();
  25660. this.#textSelectionAC = null;
  25661. this.#textLayer.div.classList.remove("highlighting");
  25662. }
  25663. }
  25664. #textLayerPointerDown(event) {
  25665. this.#uiManager.unselectAll();
  25666. const {
  25667. target
  25668. } = event;
  25669. if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {
  25670. const {
  25671. isMac
  25672. } = util_FeatureTest.platform;
  25673. if (event.button !== 0 || event.ctrlKey && isMac) {
  25674. return;
  25675. }
  25676. this.#uiManager.showAllEditors("highlight", true, true);
  25677. this.#textLayer.div.classList.add("free");
  25678. this.toggleDrawing();
  25679. HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {
  25680. target: this.#textLayer.div,
  25681. x: event.x,
  25682. y: event.y
  25683. });
  25684. this.#textLayer.div.addEventListener("pointerup", () => {
  25685. this.#textLayer.div.classList.remove("free");
  25686. this.toggleDrawing(true);
  25687. }, {
  25688. once: true,
  25689. signal: this.#uiManager._signal
  25690. });
  25691. event.preventDefault();
  25692. }
  25693. }
  25694. enableClick() {
  25695. if (this.#clickAC) {
  25696. return;
  25697. }
  25698. this.#clickAC = new AbortController();
  25699. const signal = this.#uiManager.combinedSignal(this.#clickAC);
  25700. this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {
  25701. signal
  25702. });
  25703. const pointerup = this.pointerup.bind(this);
  25704. this.div.addEventListener("pointerup", pointerup, {
  25705. signal
  25706. });
  25707. this.div.addEventListener("pointercancel", pointerup, {
  25708. signal
  25709. });
  25710. }
  25711. disableClick() {
  25712. this.#clickAC?.abort();
  25713. this.#clickAC = null;
  25714. }
  25715. attach(editor) {
  25716. this.#editors.set(editor.id, editor);
  25717. const {
  25718. annotationElementId
  25719. } = editor;
  25720. if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
  25721. this.#uiManager.removeDeletedAnnotationElement(editor);
  25722. }
  25723. }
  25724. detach(editor) {
  25725. this.#editors.delete(editor.id);
  25726. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  25727. if (!this.#isDisabling && editor.annotationElementId) {
  25728. this.#uiManager.addDeletedAnnotationElement(editor);
  25729. }
  25730. }
  25731. remove(editor) {
  25732. this.detach(editor);
  25733. this.#uiManager.removeEditor(editor);
  25734. editor.div.remove();
  25735. editor.isAttachedToDOM = false;
  25736. }
  25737. changeParent(editor) {
  25738. if (editor.parent === this) {
  25739. return;
  25740. }
  25741. if (editor.parent && editor.annotationElementId) {
  25742. this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
  25743. AnnotationEditor.deleteAnnotationElement(editor);
  25744. editor.annotationElementId = null;
  25745. }
  25746. this.attach(editor);
  25747. editor.parent?.detach(editor);
  25748. editor.setParent(this);
  25749. if (editor.div && editor.isAttachedToDOM) {
  25750. editor.div.remove();
  25751. this.div.append(editor.div);
  25752. }
  25753. }
  25754. add(editor) {
  25755. if (editor.parent === this && editor.isAttachedToDOM) {
  25756. return;
  25757. }
  25758. this.changeParent(editor);
  25759. this.#uiManager.addEditor(editor);
  25760. this.attach(editor);
  25761. if (!editor.isAttachedToDOM) {
  25762. const div = editor.render();
  25763. this.div.append(div);
  25764. editor.isAttachedToDOM = true;
  25765. }
  25766. editor.fixAndSetPosition();
  25767. editor.onceAdded(!this.#isEnabling);
  25768. this.#uiManager.addToAnnotationStorage(editor);
  25769. editor._reportTelemetry(editor.telemetryInitialData);
  25770. }
  25771. moveEditorInDOM(editor) {
  25772. if (!editor.isAttachedToDOM) {
  25773. return;
  25774. }
  25775. const {
  25776. activeElement
  25777. } = document;
  25778. if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
  25779. editor._focusEventsAllowed = false;
  25780. this.#editorFocusTimeoutId = setTimeout(() => {
  25781. this.#editorFocusTimeoutId = null;
  25782. if (!editor.div.contains(document.activeElement)) {
  25783. editor.div.addEventListener("focusin", () => {
  25784. editor._focusEventsAllowed = true;
  25785. }, {
  25786. once: true,
  25787. signal: this.#uiManager._signal
  25788. });
  25789. activeElement.focus();
  25790. } else {
  25791. editor._focusEventsAllowed = true;
  25792. }
  25793. }, 0);
  25794. }
  25795. editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  25796. }
  25797. addOrRebuild(editor) {
  25798. if (editor.needsToBeRebuilt()) {
  25799. editor.parent ||= this;
  25800. editor.rebuild();
  25801. editor.show();
  25802. } else {
  25803. this.add(editor);
  25804. }
  25805. }
  25806. addUndoableEditor(editor) {
  25807. const cmd = () => editor._uiManager.rebuild(editor);
  25808. const undo = () => {
  25809. editor.remove();
  25810. };
  25811. this.addCommands({
  25812. cmd,
  25813. undo,
  25814. mustExec: false
  25815. });
  25816. }
  25817. getNextId() {
  25818. return this.#uiManager.getId();
  25819. }
  25820. get #currentEditorType() {
  25821. return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
  25822. }
  25823. combinedSignal(ac) {
  25824. return this.#uiManager.combinedSignal(ac);
  25825. }
  25826. #createNewEditor(params) {
  25827. const editorType = this.#currentEditorType;
  25828. return editorType ? new editorType.prototype.constructor(params) : null;
  25829. }
  25830. canCreateNewEmptyEditor() {
  25831. return this.#currentEditorType?.canCreateNewEmptyEditor();
  25832. }
  25833. async pasteEditor(options, params) {
  25834. this.updateToolbar(options);
  25835. await this.#uiManager.updateMode(options.mode);
  25836. const {
  25837. offsetX,
  25838. offsetY
  25839. } = this.#getCenterPoint();
  25840. const id = this.getNextId();
  25841. const editor = this.#createNewEditor({
  25842. parent: this,
  25843. id,
  25844. x: offsetX,
  25845. y: offsetY,
  25846. uiManager: this.#uiManager,
  25847. isCentered: true,
  25848. ...params
  25849. });
  25850. if (editor) {
  25851. this.add(editor);
  25852. }
  25853. }
  25854. async deserialize(data) {
  25855. return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null;
  25856. }
  25857. createAndAddNewEditor(event, isCentered, data = {}) {
  25858. const id = this.getNextId();
  25859. const editor = this.#createNewEditor({
  25860. parent: this,
  25861. id,
  25862. x: event.offsetX,
  25863. y: event.offsetY,
  25864. uiManager: this.#uiManager,
  25865. isCentered,
  25866. ...data
  25867. });
  25868. if (editor) {
  25869. this.add(editor);
  25870. }
  25871. return editor;
  25872. }
  25873. #getCenterPoint() {
  25874. const {
  25875. x,
  25876. y,
  25877. width,
  25878. height
  25879. } = this.div.getBoundingClientRect();
  25880. const tlX = Math.max(0, x);
  25881. const tlY = Math.max(0, y);
  25882. const brX = Math.min(window.innerWidth, x + width);
  25883. const brY = Math.min(window.innerHeight, y + height);
  25884. const centerX = (tlX + brX) / 2 - x;
  25885. const centerY = (tlY + brY) / 2 - y;
  25886. const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
  25887. return {
  25888. offsetX,
  25889. offsetY
  25890. };
  25891. }
  25892. addNewEditor(data = {}) {
  25893. this.createAndAddNewEditor(this.#getCenterPoint(), true, data);
  25894. }
  25895. setSelected(editor) {
  25896. this.#uiManager.setSelected(editor);
  25897. }
  25898. toggleSelected(editor) {
  25899. this.#uiManager.toggleSelected(editor);
  25900. }
  25901. unselect(editor) {
  25902. this.#uiManager.unselect(editor);
  25903. }
  25904. pointerup(event) {
  25905. const {
  25906. isMac
  25907. } = util_FeatureTest.platform;
  25908. if (event.button !== 0 || event.ctrlKey && isMac) {
  25909. return;
  25910. }
  25911. if (event.target !== this.div) {
  25912. return;
  25913. }
  25914. if (!this.#hadPointerDown) {
  25915. return;
  25916. }
  25917. this.#hadPointerDown = false;
  25918. if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) {
  25919. return;
  25920. }
  25921. if (!this.#allowClick) {
  25922. this.#allowClick = true;
  25923. return;
  25924. }
  25925. const currentMode = this.#uiManager.getMode();
  25926. if (currentMode === AnnotationEditorType.STAMP || currentMode === AnnotationEditorType.SIGNATURE) {
  25927. this.#uiManager.unselectAll();
  25928. return;
  25929. }
  25930. this.createAndAddNewEditor(event, false);
  25931. }
  25932. pointerdown(event) {
  25933. if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
  25934. this.enableTextSelection();
  25935. }
  25936. if (this.#hadPointerDown) {
  25937. this.#hadPointerDown = false;
  25938. return;
  25939. }
  25940. const {
  25941. isMac
  25942. } = util_FeatureTest.platform;
  25943. if (event.button !== 0 || event.ctrlKey && isMac) {
  25944. return;
  25945. }
  25946. if (event.target !== this.div) {
  25947. return;
  25948. }
  25949. this.#hadPointerDown = true;
  25950. if (this.#currentEditorType?.isDrawer) {
  25951. this.startDrawingSession(event);
  25952. return;
  25953. }
  25954. const editor = this.#uiManager.getActive();
  25955. this.#allowClick = !editor || editor.isEmpty();
  25956. }
  25957. startDrawingSession(event) {
  25958. this.div.focus({
  25959. preventScroll: true
  25960. });
  25961. if (this.#drawingAC) {
  25962. this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
  25963. return;
  25964. }
  25965. this.#uiManager.setCurrentDrawingSession(this);
  25966. this.#drawingAC = new AbortController();
  25967. const signal = this.#uiManager.combinedSignal(this.#drawingAC);
  25968. this.div.addEventListener("blur", ({
  25969. relatedTarget
  25970. }) => {
  25971. if (relatedTarget && !this.div.contains(relatedTarget)) {
  25972. this.#focusedElement = null;
  25973. this.commitOrRemove();
  25974. }
  25975. }, {
  25976. signal
  25977. });
  25978. this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
  25979. }
  25980. pause(on) {
  25981. if (on) {
  25982. const {
  25983. activeElement
  25984. } = document;
  25985. if (this.div.contains(activeElement)) {
  25986. this.#focusedElement = activeElement;
  25987. }
  25988. return;
  25989. }
  25990. if (this.#focusedElement) {
  25991. setTimeout(() => {
  25992. this.#focusedElement?.focus();
  25993. this.#focusedElement = null;
  25994. }, 0);
  25995. }
  25996. }
  25997. endDrawingSession(isAborted = false) {
  25998. if (!this.#drawingAC) {
  25999. return null;
  26000. }
  26001. this.#uiManager.setCurrentDrawingSession(null);
  26002. this.#drawingAC.abort();
  26003. this.#drawingAC = null;
  26004. this.#focusedElement = null;
  26005. return this.#currentEditorType.endDrawing(isAborted);
  26006. }
  26007. findNewParent(editor, x, y) {
  26008. const layer = this.#uiManager.findParent(x, y);
  26009. if (layer === null || layer === this) {
  26010. return false;
  26011. }
  26012. layer.changeParent(editor);
  26013. return true;
  26014. }
  26015. commitOrRemove() {
  26016. if (this.#drawingAC) {
  26017. this.endDrawingSession();
  26018. return true;
  26019. }
  26020. return false;
  26021. }
  26022. onScaleChanging() {
  26023. if (!this.#drawingAC) {
  26024. return;
  26025. }
  26026. this.#currentEditorType.onScaleChangingWhenDrawing(this);
  26027. }
  26028. destroy() {
  26029. this.commitOrRemove();
  26030. if (this.#uiManager.getActive()?.parent === this) {
  26031. this.#uiManager.commitOrRemove();
  26032. this.#uiManager.setActiveEditor(null);
  26033. }
  26034. if (this.#editorFocusTimeoutId) {
  26035. clearTimeout(this.#editorFocusTimeoutId);
  26036. this.#editorFocusTimeoutId = null;
  26037. }
  26038. for (const editor of this.#editors.values()) {
  26039. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  26040. editor.setParent(null);
  26041. editor.isAttachedToDOM = false;
  26042. editor.div.remove();
  26043. }
  26044. this.div = null;
  26045. this.#editors.clear();
  26046. this.#uiManager.removeLayer(this);
  26047. }
  26048. #cleanup() {
  26049. for (const editor of this.#editors.values()) {
  26050. if (editor.isEmpty()) {
  26051. editor.remove();
  26052. }
  26053. }
  26054. }
  26055. render({
  26056. viewport
  26057. }) {
  26058. this.viewport = viewport;
  26059. setLayerDimensions(this.div, viewport);
  26060. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  26061. this.add(editor);
  26062. editor.rebuild();
  26063. }
  26064. this.updateMode();
  26065. }
  26066. update({
  26067. viewport
  26068. }) {
  26069. this.#uiManager.commitOrRemove();
  26070. this.#cleanup();
  26071. const oldRotation = this.viewport.rotation;
  26072. const rotation = viewport.rotation;
  26073. this.viewport = viewport;
  26074. setLayerDimensions(this.div, {
  26075. rotation
  26076. });
  26077. if (oldRotation !== rotation) {
  26078. for (const editor of this.#editors.values()) {
  26079. editor.rotate(rotation);
  26080. }
  26081. }
  26082. }
  26083. get pageDimensions() {
  26084. const {
  26085. pageWidth,
  26086. pageHeight
  26087. } = this.viewport.rawDims;
  26088. return [pageWidth, pageHeight];
  26089. }
  26090. get scale() {
  26091. return this.#uiManager.viewParameters.realScale;
  26092. }
  26093. }
  26094. ;// ./src/display/draw_layer.js
  26095. class DrawLayer {
  26096. #parent = null;
  26097. #mapping = new Map();
  26098. #toUpdate = new Map();
  26099. static #id = 0;
  26100. constructor({
  26101. pageIndex
  26102. }) {
  26103. this.pageIndex = pageIndex;
  26104. }
  26105. setParent(parent) {
  26106. if (!this.#parent) {
  26107. this.#parent = parent;
  26108. return;
  26109. }
  26110. if (this.#parent !== parent) {
  26111. if (this.#mapping.size > 0) {
  26112. for (const root of this.#mapping.values()) {
  26113. root.remove();
  26114. parent.append(root);
  26115. }
  26116. }
  26117. this.#parent = parent;
  26118. }
  26119. }
  26120. static get _svgFactory() {
  26121. return shadow(this, "_svgFactory", new DOMSVGFactory());
  26122. }
  26123. static #setBox(element, [x, y, width, height]) {
  26124. const {
  26125. style
  26126. } = element;
  26127. style.top = `${100 * y}%`;
  26128. style.left = `${100 * x}%`;
  26129. style.width = `${100 * width}%`;
  26130. style.height = `${100 * height}%`;
  26131. }
  26132. #createSVG() {
  26133. const svg = DrawLayer._svgFactory.create(1, 1, true);
  26134. this.#parent.append(svg);
  26135. svg.setAttribute("aria-hidden", true);
  26136. return svg;
  26137. }
  26138. #createClipPath(defs, pathId) {
  26139. const clipPath = DrawLayer._svgFactory.createElement("clipPath");
  26140. defs.append(clipPath);
  26141. const clipPathId = `clip_${pathId}`;
  26142. clipPath.setAttribute("id", clipPathId);
  26143. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  26144. const clipPathUse = DrawLayer._svgFactory.createElement("use");
  26145. clipPath.append(clipPathUse);
  26146. clipPathUse.setAttribute("href", `#${pathId}`);
  26147. clipPathUse.classList.add("clip");
  26148. return clipPathId;
  26149. }
  26150. #updateProperties(element, properties) {
  26151. for (const [key, value] of Object.entries(properties)) {
  26152. if (value === null) {
  26153. element.removeAttribute(key);
  26154. } else {
  26155. element.setAttribute(key, value);
  26156. }
  26157. }
  26158. }
  26159. draw(properties, isPathUpdatable = false, hasClip = false) {
  26160. const id = DrawLayer.#id++;
  26161. const root = this.#createSVG();
  26162. const defs = DrawLayer._svgFactory.createElement("defs");
  26163. root.append(defs);
  26164. const path = DrawLayer._svgFactory.createElement("path");
  26165. defs.append(path);
  26166. const pathId = `path_p${this.pageIndex}_${id}`;
  26167. path.setAttribute("id", pathId);
  26168. path.setAttribute("vector-effect", "non-scaling-stroke");
  26169. if (isPathUpdatable) {
  26170. this.#toUpdate.set(id, path);
  26171. }
  26172. const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null;
  26173. const use = DrawLayer._svgFactory.createElement("use");
  26174. root.append(use);
  26175. use.setAttribute("href", `#${pathId}`);
  26176. this.updateProperties(root, properties);
  26177. this.#mapping.set(id, root);
  26178. return {
  26179. id,
  26180. clipPathId: `url(#${clipPathId})`
  26181. };
  26182. }
  26183. drawOutline(properties, mustRemoveSelfIntersections) {
  26184. const id = DrawLayer.#id++;
  26185. const root = this.#createSVG();
  26186. const defs = DrawLayer._svgFactory.createElement("defs");
  26187. root.append(defs);
  26188. const path = DrawLayer._svgFactory.createElement("path");
  26189. defs.append(path);
  26190. const pathId = `path_p${this.pageIndex}_${id}`;
  26191. path.setAttribute("id", pathId);
  26192. path.setAttribute("vector-effect", "non-scaling-stroke");
  26193. let maskId;
  26194. if (mustRemoveSelfIntersections) {
  26195. const mask = DrawLayer._svgFactory.createElement("mask");
  26196. defs.append(mask);
  26197. maskId = `mask_p${this.pageIndex}_${id}`;
  26198. mask.setAttribute("id", maskId);
  26199. mask.setAttribute("maskUnits", "objectBoundingBox");
  26200. const rect = DrawLayer._svgFactory.createElement("rect");
  26201. mask.append(rect);
  26202. rect.setAttribute("width", "1");
  26203. rect.setAttribute("height", "1");
  26204. rect.setAttribute("fill", "white");
  26205. const use = DrawLayer._svgFactory.createElement("use");
  26206. mask.append(use);
  26207. use.setAttribute("href", `#${pathId}`);
  26208. use.setAttribute("stroke", "none");
  26209. use.setAttribute("fill", "black");
  26210. use.setAttribute("fill-rule", "nonzero");
  26211. use.classList.add("mask");
  26212. }
  26213. const use1 = DrawLayer._svgFactory.createElement("use");
  26214. root.append(use1);
  26215. use1.setAttribute("href", `#${pathId}`);
  26216. if (maskId) {
  26217. use1.setAttribute("mask", `url(#${maskId})`);
  26218. }
  26219. const use2 = use1.cloneNode();
  26220. root.append(use2);
  26221. use1.classList.add("mainOutline");
  26222. use2.classList.add("secondaryOutline");
  26223. this.updateProperties(root, properties);
  26224. this.#mapping.set(id, root);
  26225. return id;
  26226. }
  26227. finalizeDraw(id, properties) {
  26228. this.#toUpdate.delete(id);
  26229. this.updateProperties(id, properties);
  26230. }
  26231. updateProperties(elementOrId, properties) {
  26232. if (!properties) {
  26233. return;
  26234. }
  26235. const {
  26236. root,
  26237. bbox,
  26238. rootClass,
  26239. path
  26240. } = properties;
  26241. const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId;
  26242. if (!element) {
  26243. return;
  26244. }
  26245. if (root) {
  26246. this.#updateProperties(element, root);
  26247. }
  26248. if (bbox) {
  26249. DrawLayer.#setBox(element, bbox);
  26250. }
  26251. if (rootClass) {
  26252. const {
  26253. classList
  26254. } = element;
  26255. for (const [className, value] of Object.entries(rootClass)) {
  26256. classList.toggle(className, value);
  26257. }
  26258. }
  26259. if (path) {
  26260. const defs = element.firstChild;
  26261. const pathElement = defs.firstChild;
  26262. this.#updateProperties(pathElement, path);
  26263. }
  26264. }
  26265. updateParent(id, layer) {
  26266. if (layer === this) {
  26267. return;
  26268. }
  26269. const root = this.#mapping.get(id);
  26270. if (!root) {
  26271. return;
  26272. }
  26273. layer.#parent.append(root);
  26274. this.#mapping.delete(id);
  26275. layer.#mapping.set(id, root);
  26276. }
  26277. remove(id) {
  26278. this.#toUpdate.delete(id);
  26279. if (this.#parent === null) {
  26280. return;
  26281. }
  26282. this.#mapping.get(id).remove();
  26283. this.#mapping.delete(id);
  26284. }
  26285. destroy() {
  26286. this.#parent = null;
  26287. for (const root of this.#mapping.values()) {
  26288. root.remove();
  26289. }
  26290. this.#mapping.clear();
  26291. this.#toUpdate.clear();
  26292. }
  26293. }
  26294. ;// ./src/pdf.js
  26295. {
  26296. globalThis._pdfjsTestingUtils = {
  26297. HighlightOutliner: HighlightOutliner
  26298. };
  26299. }
  26300. globalThis.pdfjsLib = {
  26301. AbortException: AbortException,
  26302. AnnotationEditorLayer: AnnotationEditorLayer,
  26303. AnnotationEditorParamsType: AnnotationEditorParamsType,
  26304. AnnotationEditorType: AnnotationEditorType,
  26305. AnnotationEditorUIManager: AnnotationEditorUIManager,
  26306. AnnotationLayer: AnnotationLayer,
  26307. AnnotationMode: AnnotationMode,
  26308. AnnotationType: AnnotationType,
  26309. build: build,
  26310. ColorPicker: ColorPicker,
  26311. createValidAbsoluteUrl: createValidAbsoluteUrl,
  26312. DOMSVGFactory: DOMSVGFactory,
  26313. DrawLayer: DrawLayer,
  26314. FeatureTest: util_FeatureTest,
  26315. fetchData: fetchData,
  26316. getDocument: getDocument,
  26317. getFilenameFromUrl: getFilenameFromUrl,
  26318. getPdfFilenameFromUrl: getPdfFilenameFromUrl,
  26319. getUuid: getUuid,
  26320. getXfaPageViewport: getXfaPageViewport,
  26321. GlobalWorkerOptions: GlobalWorkerOptions,
  26322. ImageKind: util_ImageKind,
  26323. InvalidPDFException: InvalidPDFException,
  26324. isDataScheme: isDataScheme,
  26325. isPdfFile: isPdfFile,
  26326. isValidExplicitDest: isValidExplicitDest,
  26327. MathClamp: MathClamp,
  26328. noContextMenu: noContextMenu,
  26329. normalizeUnicode: normalizeUnicode,
  26330. OPS: OPS,
  26331. OutputScale: OutputScale,
  26332. PasswordResponses: PasswordResponses,
  26333. PDFDataRangeTransport: PDFDataRangeTransport,
  26334. PDFDateString: PDFDateString,
  26335. PDFWorker: PDFWorker,
  26336. PermissionFlag: PermissionFlag,
  26337. PixelsPerInch: PixelsPerInch,
  26338. RenderingCancelledException: RenderingCancelledException,
  26339. ResponseException: ResponseException,
  26340. setLayerDimensions: setLayerDimensions,
  26341. shadow: shadow,
  26342. SignatureExtractor: SignatureExtractor,
  26343. stopEvent: stopEvent,
  26344. SupportedImageMimeTypes: SupportedImageMimeTypes,
  26345. TextLayer: TextLayer,
  26346. TouchManager: TouchManager,
  26347. updateUrlHash: updateUrlHash,
  26348. Util: Util,
  26349. VerbosityLevel: VerbosityLevel,
  26350. version: version,
  26351. XfaLayer: XfaLayer
  26352. };
  26353. export { AbortException, AnnotationEditorLayer, AnnotationEditorParamsType, AnnotationEditorType, AnnotationEditorUIManager, AnnotationLayer, AnnotationMode, AnnotationType, ColorPicker, DOMSVGFactory, DrawLayer, util_FeatureTest as FeatureTest, GlobalWorkerOptions, util_ImageKind as ImageKind, InvalidPDFException, MathClamp, OPS, OutputScale, PDFDataRangeTransport, PDFDateString, PDFWorker, PasswordResponses, PermissionFlag, PixelsPerInch, RenderingCancelledException, ResponseException, SignatureExtractor, SupportedImageMimeTypes, TextLayer, TouchManager, Util, VerbosityLevel, XfaLayer, build, createValidAbsoluteUrl, fetchData, getDocument, getFilenameFromUrl, getPdfFilenameFromUrl, getUuid, getXfaPageViewport, isDataScheme, isPdfFile, isValidExplicitDest, noContextMenu, normalizeUnicode, setLayerDimensions, shadow, stopEvent, updateUrlHash, version };
  26354. //# sourceMappingURL=pdf.mjs.map