pdf.mjs 614 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2024 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. /******/ // The require scope
  23. /******/ var __webpack_require__ = {};
  24. /******/
  25. /************************************************************************/
  26. /******/ /* webpack/runtime/define property getters */
  27. /******/ (() => {
  28. /******/ // define getter functions for harmony exports
  29. /******/ __webpack_require__.d = (exports, definition) => {
  30. /******/ for(var key in definition) {
  31. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  32. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  33. /******/ }
  34. /******/ }
  35. /******/ };
  36. /******/ })();
  37. /******/
  38. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  39. /******/ (() => {
  40. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  41. /******/ })();
  42. /******/
  43. /************************************************************************/
  44. var __webpack_exports__ = globalThis.pdfjsLib = {};
  45. // EXPORTS
  46. __webpack_require__.d(__webpack_exports__, {
  47. AbortException: () => (/* reexport */ AbortException),
  48. AnnotationEditorLayer: () => (/* reexport */ AnnotationEditorLayer),
  49. AnnotationEditorParamsType: () => (/* reexport */ AnnotationEditorParamsType),
  50. AnnotationEditorType: () => (/* reexport */ AnnotationEditorType),
  51. AnnotationEditorUIManager: () => (/* reexport */ AnnotationEditorUIManager),
  52. AnnotationLayer: () => (/* reexport */ AnnotationLayer),
  53. AnnotationMode: () => (/* reexport */ AnnotationMode),
  54. ColorPicker: () => (/* reexport */ ColorPicker),
  55. DOMSVGFactory: () => (/* reexport */ DOMSVGFactory),
  56. DrawLayer: () => (/* reexport */ DrawLayer),
  57. FeatureTest: () => (/* reexport */ util_FeatureTest),
  58. GlobalWorkerOptions: () => (/* reexport */ GlobalWorkerOptions),
  59. ImageKind: () => (/* reexport */ util_ImageKind),
  60. InvalidPDFException: () => (/* reexport */ InvalidPDFException),
  61. MissingPDFException: () => (/* reexport */ MissingPDFException),
  62. OPS: () => (/* reexport */ OPS),
  63. OutputScale: () => (/* reexport */ OutputScale),
  64. PDFDataRangeTransport: () => (/* reexport */ PDFDataRangeTransport),
  65. PDFDateString: () => (/* reexport */ PDFDateString),
  66. PDFWorker: () => (/* reexport */ PDFWorker),
  67. PasswordResponses: () => (/* reexport */ PasswordResponses),
  68. PermissionFlag: () => (/* reexport */ PermissionFlag),
  69. PixelsPerInch: () => (/* reexport */ PixelsPerInch),
  70. RenderingCancelledException: () => (/* reexport */ RenderingCancelledException),
  71. TextLayer: () => (/* reexport */ TextLayer),
  72. UnexpectedResponseException: () => (/* reexport */ UnexpectedResponseException),
  73. Util: () => (/* reexport */ Util),
  74. VerbosityLevel: () => (/* reexport */ VerbosityLevel),
  75. XfaLayer: () => (/* reexport */ XfaLayer),
  76. build: () => (/* reexport */ build),
  77. createValidAbsoluteUrl: () => (/* reexport */ createValidAbsoluteUrl),
  78. fetchData: () => (/* reexport */ fetchData),
  79. getDocument: () => (/* reexport */ getDocument),
  80. getFilenameFromUrl: () => (/* reexport */ getFilenameFromUrl),
  81. getPdfFilenameFromUrl: () => (/* reexport */ getPdfFilenameFromUrl),
  82. getXfaPageViewport: () => (/* reexport */ getXfaPageViewport),
  83. isDataScheme: () => (/* reexport */ isDataScheme),
  84. isPdfFile: () => (/* reexport */ isPdfFile),
  85. noContextMenu: () => (/* reexport */ noContextMenu),
  86. normalizeUnicode: () => (/* reexport */ normalizeUnicode),
  87. setLayerDimensions: () => (/* reexport */ setLayerDimensions),
  88. shadow: () => (/* reexport */ shadow),
  89. version: () => (/* reexport */ version)
  90. });
  91. ;// ./src/shared/util.js
  92. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  93. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  94. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  95. const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
  96. const LINE_FACTOR = 1.35;
  97. const LINE_DESCENT_FACTOR = 0.35;
  98. const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
  99. const RenderingIntentFlag = {
  100. ANY: 0x01,
  101. DISPLAY: 0x02,
  102. PRINT: 0x04,
  103. SAVE: 0x08,
  104. ANNOTATIONS_FORMS: 0x10,
  105. ANNOTATIONS_STORAGE: 0x20,
  106. ANNOTATIONS_DISABLE: 0x40,
  107. IS_EDITING: 0x80,
  108. OPLIST: 0x100
  109. };
  110. const AnnotationMode = {
  111. DISABLE: 0,
  112. ENABLE: 1,
  113. ENABLE_FORMS: 2,
  114. ENABLE_STORAGE: 3
  115. };
  116. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  117. const AnnotationEditorType = {
  118. DISABLE: -1,
  119. NONE: 0,
  120. FREETEXT: 3,
  121. HIGHLIGHT: 9,
  122. STAMP: 13,
  123. INK: 15
  124. };
  125. const AnnotationEditorParamsType = {
  126. RESIZE: 1,
  127. CREATE: 2,
  128. FREETEXT_SIZE: 11,
  129. FREETEXT_COLOR: 12,
  130. FREETEXT_OPACITY: 13,
  131. INK_COLOR: 21,
  132. INK_THICKNESS: 22,
  133. INK_OPACITY: 23,
  134. HIGHLIGHT_COLOR: 31,
  135. HIGHLIGHT_DEFAULT_COLOR: 32,
  136. HIGHLIGHT_THICKNESS: 33,
  137. HIGHLIGHT_FREE: 34,
  138. HIGHLIGHT_SHOW_ALL: 35
  139. };
  140. const PermissionFlag = {
  141. PRINT: 0x04,
  142. MODIFY_CONTENTS: 0x08,
  143. COPY: 0x10,
  144. MODIFY_ANNOTATIONS: 0x20,
  145. FILL_INTERACTIVE_FORMS: 0x100,
  146. COPY_FOR_ACCESSIBILITY: 0x200,
  147. ASSEMBLE: 0x400,
  148. PRINT_HIGH_QUALITY: 0x800
  149. };
  150. const TextRenderingMode = {
  151. FILL: 0,
  152. STROKE: 1,
  153. FILL_STROKE: 2,
  154. INVISIBLE: 3,
  155. FILL_ADD_TO_PATH: 4,
  156. STROKE_ADD_TO_PATH: 5,
  157. FILL_STROKE_ADD_TO_PATH: 6,
  158. ADD_TO_PATH: 7,
  159. FILL_STROKE_MASK: 3,
  160. ADD_TO_PATH_FLAG: 4
  161. };
  162. const util_ImageKind = {
  163. GRAYSCALE_1BPP: 1,
  164. RGB_24BPP: 2,
  165. RGBA_32BPP: 3
  166. };
  167. const AnnotationType = {
  168. TEXT: 1,
  169. LINK: 2,
  170. FREETEXT: 3,
  171. LINE: 4,
  172. SQUARE: 5,
  173. CIRCLE: 6,
  174. POLYGON: 7,
  175. POLYLINE: 8,
  176. HIGHLIGHT: 9,
  177. UNDERLINE: 10,
  178. SQUIGGLY: 11,
  179. STRIKEOUT: 12,
  180. STAMP: 13,
  181. CARET: 14,
  182. INK: 15,
  183. POPUP: 16,
  184. FILEATTACHMENT: 17,
  185. SOUND: 18,
  186. MOVIE: 19,
  187. WIDGET: 20,
  188. SCREEN: 21,
  189. PRINTERMARK: 22,
  190. TRAPNET: 23,
  191. WATERMARK: 24,
  192. THREED: 25,
  193. REDACT: 26
  194. };
  195. const AnnotationReplyType = {
  196. GROUP: "Group",
  197. REPLY: "R"
  198. };
  199. const AnnotationFlag = {
  200. INVISIBLE: 0x01,
  201. HIDDEN: 0x02,
  202. PRINT: 0x04,
  203. NOZOOM: 0x08,
  204. NOROTATE: 0x10,
  205. NOVIEW: 0x20,
  206. READONLY: 0x40,
  207. LOCKED: 0x80,
  208. TOGGLENOVIEW: 0x100,
  209. LOCKEDCONTENTS: 0x200
  210. };
  211. const AnnotationFieldFlag = {
  212. READONLY: 0x0000001,
  213. REQUIRED: 0x0000002,
  214. NOEXPORT: 0x0000004,
  215. MULTILINE: 0x0001000,
  216. PASSWORD: 0x0002000,
  217. NOTOGGLETOOFF: 0x0004000,
  218. RADIO: 0x0008000,
  219. PUSHBUTTON: 0x0010000,
  220. COMBO: 0x0020000,
  221. EDIT: 0x0040000,
  222. SORT: 0x0080000,
  223. FILESELECT: 0x0100000,
  224. MULTISELECT: 0x0200000,
  225. DONOTSPELLCHECK: 0x0400000,
  226. DONOTSCROLL: 0x0800000,
  227. COMB: 0x1000000,
  228. RICHTEXT: 0x2000000,
  229. RADIOSINUNISON: 0x2000000,
  230. COMMITONSELCHANGE: 0x4000000
  231. };
  232. const AnnotationBorderStyleType = {
  233. SOLID: 1,
  234. DASHED: 2,
  235. BEVELED: 3,
  236. INSET: 4,
  237. UNDERLINE: 5
  238. };
  239. const AnnotationActionEventType = {
  240. E: "Mouse Enter",
  241. X: "Mouse Exit",
  242. D: "Mouse Down",
  243. U: "Mouse Up",
  244. Fo: "Focus",
  245. Bl: "Blur",
  246. PO: "PageOpen",
  247. PC: "PageClose",
  248. PV: "PageVisible",
  249. PI: "PageInvisible",
  250. K: "Keystroke",
  251. F: "Format",
  252. V: "Validate",
  253. C: "Calculate"
  254. };
  255. const DocumentActionEventType = {
  256. WC: "WillClose",
  257. WS: "WillSave",
  258. DS: "DidSave",
  259. WP: "WillPrint",
  260. DP: "DidPrint"
  261. };
  262. const PageActionEventType = {
  263. O: "PageOpen",
  264. C: "PageClose"
  265. };
  266. const VerbosityLevel = {
  267. ERRORS: 0,
  268. WARNINGS: 1,
  269. INFOS: 5
  270. };
  271. const OPS = {
  272. dependency: 1,
  273. setLineWidth: 2,
  274. setLineCap: 3,
  275. setLineJoin: 4,
  276. setMiterLimit: 5,
  277. setDash: 6,
  278. setRenderingIntent: 7,
  279. setFlatness: 8,
  280. setGState: 9,
  281. save: 10,
  282. restore: 11,
  283. transform: 12,
  284. moveTo: 13,
  285. lineTo: 14,
  286. curveTo: 15,
  287. curveTo2: 16,
  288. curveTo3: 17,
  289. closePath: 18,
  290. rectangle: 19,
  291. stroke: 20,
  292. closeStroke: 21,
  293. fill: 22,
  294. eoFill: 23,
  295. fillStroke: 24,
  296. eoFillStroke: 25,
  297. closeFillStroke: 26,
  298. closeEOFillStroke: 27,
  299. endPath: 28,
  300. clip: 29,
  301. eoClip: 30,
  302. beginText: 31,
  303. endText: 32,
  304. setCharSpacing: 33,
  305. setWordSpacing: 34,
  306. setHScale: 35,
  307. setLeading: 36,
  308. setFont: 37,
  309. setTextRenderingMode: 38,
  310. setTextRise: 39,
  311. moveText: 40,
  312. setLeadingMoveText: 41,
  313. setTextMatrix: 42,
  314. nextLine: 43,
  315. showText: 44,
  316. showSpacedText: 45,
  317. nextLineShowText: 46,
  318. nextLineSetSpacingShowText: 47,
  319. setCharWidth: 48,
  320. setCharWidthAndBounds: 49,
  321. setStrokeColorSpace: 50,
  322. setFillColorSpace: 51,
  323. setStrokeColor: 52,
  324. setStrokeColorN: 53,
  325. setFillColor: 54,
  326. setFillColorN: 55,
  327. setStrokeGray: 56,
  328. setFillGray: 57,
  329. setStrokeRGBColor: 58,
  330. setFillRGBColor: 59,
  331. setStrokeCMYKColor: 60,
  332. setFillCMYKColor: 61,
  333. shadingFill: 62,
  334. beginInlineImage: 63,
  335. beginImageData: 64,
  336. endInlineImage: 65,
  337. paintXObject: 66,
  338. markPoint: 67,
  339. markPointProps: 68,
  340. beginMarkedContent: 69,
  341. beginMarkedContentProps: 70,
  342. endMarkedContent: 71,
  343. beginCompat: 72,
  344. endCompat: 73,
  345. paintFormXObjectBegin: 74,
  346. paintFormXObjectEnd: 75,
  347. beginGroup: 76,
  348. endGroup: 77,
  349. beginAnnotation: 80,
  350. endAnnotation: 81,
  351. paintImageMaskXObject: 83,
  352. paintImageMaskXObjectGroup: 84,
  353. paintImageXObject: 85,
  354. paintInlineImageXObject: 86,
  355. paintInlineImageXObjectGroup: 87,
  356. paintImageXObjectRepeat: 88,
  357. paintImageMaskXObjectRepeat: 89,
  358. paintSolidColorImageMask: 90,
  359. constructPath: 91,
  360. setStrokeTransparent: 92,
  361. setFillTransparent: 93
  362. };
  363. const PasswordResponses = {
  364. NEED_PASSWORD: 1,
  365. INCORRECT_PASSWORD: 2
  366. };
  367. let verbosity = VerbosityLevel.WARNINGS;
  368. function setVerbosityLevel(level) {
  369. if (Number.isInteger(level)) {
  370. verbosity = level;
  371. }
  372. }
  373. function getVerbosityLevel() {
  374. return verbosity;
  375. }
  376. function info(msg) {
  377. if (verbosity >= VerbosityLevel.INFOS) {
  378. console.log(`Info: ${msg}`);
  379. }
  380. }
  381. function warn(msg) {
  382. if (verbosity >= VerbosityLevel.WARNINGS) {
  383. console.log(`Warning: ${msg}`);
  384. }
  385. }
  386. function unreachable(msg) {
  387. throw new Error(msg);
  388. }
  389. function assert(cond, msg) {
  390. if (!cond) {
  391. unreachable(msg);
  392. }
  393. }
  394. function _isValidProtocol(url) {
  395. switch (url?.protocol) {
  396. case "http:":
  397. case "https:":
  398. case "ftp:":
  399. case "mailto:":
  400. case "tel:":
  401. return true;
  402. default:
  403. return false;
  404. }
  405. }
  406. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  407. if (!url) {
  408. return null;
  409. }
  410. try {
  411. if (options && typeof url === "string") {
  412. if (options.addDefaultProtocol && url.startsWith("www.")) {
  413. const dots = url.match(/\./g);
  414. if (dots?.length >= 2) {
  415. url = `http://${url}`;
  416. }
  417. }
  418. if (options.tryConvertEncoding) {
  419. try {
  420. url = stringToUTF8String(url);
  421. } catch {}
  422. }
  423. }
  424. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  425. if (_isValidProtocol(absoluteUrl)) {
  426. return absoluteUrl;
  427. }
  428. } catch {}
  429. return null;
  430. }
  431. function shadow(obj, prop, value, nonSerializable = false) {
  432. Object.defineProperty(obj, prop, {
  433. value,
  434. enumerable: !nonSerializable,
  435. configurable: true,
  436. writable: false
  437. });
  438. return value;
  439. }
  440. const BaseException = function BaseExceptionClosure() {
  441. function BaseException(message, name) {
  442. this.message = message;
  443. this.name = name;
  444. }
  445. BaseException.prototype = new Error();
  446. BaseException.constructor = BaseException;
  447. return BaseException;
  448. }();
  449. class PasswordException extends BaseException {
  450. constructor(msg, code) {
  451. super(msg, "PasswordException");
  452. this.code = code;
  453. }
  454. }
  455. class UnknownErrorException extends BaseException {
  456. constructor(msg, details) {
  457. super(msg, "UnknownErrorException");
  458. this.details = details;
  459. }
  460. }
  461. class InvalidPDFException extends BaseException {
  462. constructor(msg) {
  463. super(msg, "InvalidPDFException");
  464. }
  465. }
  466. class MissingPDFException extends BaseException {
  467. constructor(msg) {
  468. super(msg, "MissingPDFException");
  469. }
  470. }
  471. class UnexpectedResponseException extends BaseException {
  472. constructor(msg, status) {
  473. super(msg, "UnexpectedResponseException");
  474. this.status = status;
  475. }
  476. }
  477. class FormatError extends BaseException {
  478. constructor(msg) {
  479. super(msg, "FormatError");
  480. }
  481. }
  482. class AbortException extends BaseException {
  483. constructor(msg) {
  484. super(msg, "AbortException");
  485. }
  486. }
  487. function bytesToString(bytes) {
  488. if (typeof bytes !== "object" || bytes?.length === undefined) {
  489. unreachable("Invalid argument for bytesToString");
  490. }
  491. const length = bytes.length;
  492. const MAX_ARGUMENT_COUNT = 8192;
  493. if (length < MAX_ARGUMENT_COUNT) {
  494. return String.fromCharCode.apply(null, bytes);
  495. }
  496. const strBuf = [];
  497. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  498. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  499. const chunk = bytes.subarray(i, chunkEnd);
  500. strBuf.push(String.fromCharCode.apply(null, chunk));
  501. }
  502. return strBuf.join("");
  503. }
  504. function stringToBytes(str) {
  505. if (typeof str !== "string") {
  506. unreachable("Invalid argument for stringToBytes");
  507. }
  508. const length = str.length;
  509. const bytes = new Uint8Array(length);
  510. for (let i = 0; i < length; ++i) {
  511. bytes[i] = str.charCodeAt(i) & 0xff;
  512. }
  513. return bytes;
  514. }
  515. function string32(value) {
  516. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  517. }
  518. function objectSize(obj) {
  519. return Object.keys(obj).length;
  520. }
  521. function objectFromMap(map) {
  522. const obj = Object.create(null);
  523. for (const [key, value] of map) {
  524. obj[key] = value;
  525. }
  526. return obj;
  527. }
  528. function isLittleEndian() {
  529. const buffer8 = new Uint8Array(4);
  530. buffer8[0] = 1;
  531. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  532. return view32[0] === 1;
  533. }
  534. function isEvalSupported() {
  535. try {
  536. new Function("");
  537. return true;
  538. } catch {
  539. return false;
  540. }
  541. }
  542. class util_FeatureTest {
  543. static get isLittleEndian() {
  544. return shadow(this, "isLittleEndian", isLittleEndian());
  545. }
  546. static get isEvalSupported() {
  547. return shadow(this, "isEvalSupported", isEvalSupported());
  548. }
  549. static get isOffscreenCanvasSupported() {
  550. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  551. }
  552. static get platform() {
  553. if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") {
  554. return shadow(this, "platform", {
  555. isMac: navigator.platform.includes("Mac"),
  556. isWindows: navigator.platform.includes("Win"),
  557. isFirefox: typeof navigator?.userAgent === "string" && navigator.userAgent.includes("Firefox")
  558. });
  559. }
  560. return shadow(this, "platform", {
  561. isMac: false,
  562. isWindows: false,
  563. isFirefox: false
  564. });
  565. }
  566. static get isCSSRoundSupported() {
  567. return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
  568. }
  569. }
  570. const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));
  571. class Util {
  572. static makeHexColor(r, g, b) {
  573. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  574. }
  575. static scaleMinMax(transform, minMax) {
  576. let temp;
  577. if (transform[0]) {
  578. if (transform[0] < 0) {
  579. temp = minMax[0];
  580. minMax[0] = minMax[2];
  581. minMax[2] = temp;
  582. }
  583. minMax[0] *= transform[0];
  584. minMax[2] *= transform[0];
  585. if (transform[3] < 0) {
  586. temp = minMax[1];
  587. minMax[1] = minMax[3];
  588. minMax[3] = temp;
  589. }
  590. minMax[1] *= transform[3];
  591. minMax[3] *= transform[3];
  592. } else {
  593. temp = minMax[0];
  594. minMax[0] = minMax[1];
  595. minMax[1] = temp;
  596. temp = minMax[2];
  597. minMax[2] = minMax[3];
  598. minMax[3] = temp;
  599. if (transform[1] < 0) {
  600. temp = minMax[1];
  601. minMax[1] = minMax[3];
  602. minMax[3] = temp;
  603. }
  604. minMax[1] *= transform[1];
  605. minMax[3] *= transform[1];
  606. if (transform[2] < 0) {
  607. temp = minMax[0];
  608. minMax[0] = minMax[2];
  609. minMax[2] = temp;
  610. }
  611. minMax[0] *= transform[2];
  612. minMax[2] *= transform[2];
  613. }
  614. minMax[0] += transform[4];
  615. minMax[1] += transform[5];
  616. minMax[2] += transform[4];
  617. minMax[3] += transform[5];
  618. }
  619. static transform(m1, m2) {
  620. 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]];
  621. }
  622. static applyTransform(p, m) {
  623. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  624. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  625. return [xt, yt];
  626. }
  627. static applyInverseTransform(p, m) {
  628. const d = m[0] * m[3] - m[1] * m[2];
  629. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  630. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  631. return [xt, yt];
  632. }
  633. static getAxialAlignedBoundingBox(r, m) {
  634. const p1 = this.applyTransform(r, m);
  635. const p2 = this.applyTransform(r.slice(2, 4), m);
  636. const p3 = this.applyTransform([r[0], r[3]], m);
  637. const p4 = this.applyTransform([r[2], r[1]], m);
  638. return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
  639. }
  640. static inverseTransform(m) {
  641. const d = m[0] * m[3] - m[1] * m[2];
  642. 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];
  643. }
  644. static singularValueDecompose2dScale(m) {
  645. const transpose = [m[0], m[2], m[1], m[3]];
  646. const a = m[0] * transpose[0] + m[1] * transpose[2];
  647. const b = m[0] * transpose[1] + m[1] * transpose[3];
  648. const c = m[2] * transpose[0] + m[3] * transpose[2];
  649. const d = m[2] * transpose[1] + m[3] * transpose[3];
  650. const first = (a + d) / 2;
  651. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  652. const sx = first + second || 1;
  653. const sy = first - second || 1;
  654. return [Math.sqrt(sx), Math.sqrt(sy)];
  655. }
  656. static normalizeRect(rect) {
  657. const r = rect.slice(0);
  658. if (rect[0] > rect[2]) {
  659. r[0] = rect[2];
  660. r[2] = rect[0];
  661. }
  662. if (rect[1] > rect[3]) {
  663. r[1] = rect[3];
  664. r[3] = rect[1];
  665. }
  666. return r;
  667. }
  668. static intersect(rect1, rect2) {
  669. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  670. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  671. if (xLow > xHigh) {
  672. return null;
  673. }
  674. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  675. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  676. if (yLow > yHigh) {
  677. return null;
  678. }
  679. return [xLow, yLow, xHigh, yHigh];
  680. }
  681. static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {
  682. if (t <= 0 || t >= 1) {
  683. return;
  684. }
  685. const mt = 1 - t;
  686. const tt = t * t;
  687. const ttt = tt * t;
  688. const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;
  689. const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;
  690. minMax[0] = Math.min(minMax[0], x);
  691. minMax[1] = Math.min(minMax[1], y);
  692. minMax[2] = Math.max(minMax[2], x);
  693. minMax[3] = Math.max(minMax[3], y);
  694. }
  695. static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {
  696. if (Math.abs(a) < 1e-12) {
  697. if (Math.abs(b) >= 1e-12) {
  698. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);
  699. }
  700. return;
  701. }
  702. const delta = b ** 2 - 4 * c * a;
  703. if (delta < 0) {
  704. return;
  705. }
  706. const sqrtDelta = Math.sqrt(delta);
  707. const a2 = 2 * a;
  708. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);
  709. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);
  710. }
  711. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  712. if (minMax) {
  713. minMax[0] = Math.min(minMax[0], x0, x3);
  714. minMax[1] = Math.min(minMax[1], y0, y3);
  715. minMax[2] = Math.max(minMax[2], x0, x3);
  716. minMax[3] = Math.max(minMax[3], y0, y3);
  717. } else {
  718. minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)];
  719. }
  720. 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);
  721. 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);
  722. return minMax;
  723. }
  724. }
  725. 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]));
  726. function stringToPDFString(str) {
  727. if (str[0] >= "\xEF") {
  728. let encoding;
  729. if (str[0] === "\xFE" && str[1] === "\xFF") {
  730. encoding = "utf-16be";
  731. if (str.length % 2 === 1) {
  732. str = str.slice(0, -1);
  733. }
  734. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  735. encoding = "utf-16le";
  736. if (str.length % 2 === 1) {
  737. str = str.slice(0, -1);
  738. }
  739. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  740. encoding = "utf-8";
  741. }
  742. if (encoding) {
  743. try {
  744. const decoder = new TextDecoder(encoding, {
  745. fatal: true
  746. });
  747. const buffer = stringToBytes(str);
  748. const decoded = decoder.decode(buffer);
  749. if (!decoded.includes("\x1b")) {
  750. return decoded;
  751. }
  752. return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, "");
  753. } catch (ex) {
  754. warn(`stringToPDFString: "${ex}".`);
  755. }
  756. }
  757. }
  758. const strBuf = [];
  759. for (let i = 0, ii = str.length; i < ii; i++) {
  760. const charCode = str.charCodeAt(i);
  761. if (charCode === 0x1b) {
  762. while (++i < ii && str.charCodeAt(i) !== 0x1b) {}
  763. continue;
  764. }
  765. const code = PDFStringTranslateTable[charCode];
  766. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  767. }
  768. return strBuf.join("");
  769. }
  770. function stringToUTF8String(str) {
  771. return decodeURIComponent(escape(str));
  772. }
  773. function utf8StringToString(str) {
  774. return unescape(encodeURIComponent(str));
  775. }
  776. function isArrayEqual(arr1, arr2) {
  777. if (arr1.length !== arr2.length) {
  778. return false;
  779. }
  780. for (let i = 0, ii = arr1.length; i < ii; i++) {
  781. if (arr1[i] !== arr2[i]) {
  782. return false;
  783. }
  784. }
  785. return true;
  786. }
  787. function getModificationDate(date = new Date()) {
  788. 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")];
  789. return buffer.join("");
  790. }
  791. let NormalizeRegex = null;
  792. let NormalizationMap = null;
  793. function normalizeUnicode(str) {
  794. if (!NormalizeRegex) {
  795. 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;
  796. NormalizationMap = new Map([["ſt", "ſt"]]);
  797. }
  798. return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));
  799. }
  800. function getUuid() {
  801. if (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") {
  802. return crypto.randomUUID();
  803. }
  804. const buf = new Uint8Array(32);
  805. if (typeof crypto !== "undefined" && typeof crypto?.getRandomValues === "function") {
  806. crypto.getRandomValues(buf);
  807. } else {
  808. for (let i = 0; i < 32; i++) {
  809. buf[i] = Math.floor(Math.random() * 255);
  810. }
  811. }
  812. return bytesToString(buf);
  813. }
  814. const AnnotationPrefix = "pdfjs_internal_id_";
  815. const FontRenderOps = {
  816. BEZIER_CURVE_TO: 0,
  817. MOVE_TO: 1,
  818. LINE_TO: 2,
  819. QUADRATIC_CURVE_TO: 3,
  820. RESTORE: 4,
  821. SAVE: 5,
  822. SCALE: 6,
  823. TRANSFORM: 7,
  824. TRANSLATE: 8
  825. };
  826. function toHexUtil(arr) {
  827. if (Uint8Array.prototype.toHex) {
  828. return arr.toHex();
  829. }
  830. return Array.from(arr, num => hexNumbers[num]).join("");
  831. }
  832. function toBase64Util(arr) {
  833. if (Uint8Array.prototype.toBase64) {
  834. return arr.toBase64();
  835. }
  836. return btoa(bytesToString(arr));
  837. }
  838. function fromBase64Util(str) {
  839. if (Uint8Array.fromBase64) {
  840. return Uint8Array.fromBase64(str);
  841. }
  842. return stringToBytes(atob(str));
  843. }
  844. ;// ./src/display/display_utils.js
  845. const SVG_NS = "http://www.w3.org/2000/svg";
  846. class PixelsPerInch {
  847. static CSS = 96.0;
  848. static PDF = 72.0;
  849. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  850. }
  851. async function fetchData(url, type = "text") {
  852. if (isValidFetchUrl(url, document.baseURI)) {
  853. const response = await fetch(url);
  854. if (!response.ok) {
  855. throw new Error(response.statusText);
  856. }
  857. switch (type) {
  858. case "arraybuffer":
  859. return response.arrayBuffer();
  860. case "blob":
  861. return response.blob();
  862. case "json":
  863. return response.json();
  864. }
  865. return response.text();
  866. }
  867. return new Promise((resolve, reject) => {
  868. const request = new XMLHttpRequest();
  869. request.open("GET", url, true);
  870. request.responseType = type;
  871. request.onreadystatechange = () => {
  872. if (request.readyState !== XMLHttpRequest.DONE) {
  873. return;
  874. }
  875. if (request.status === 200 || request.status === 0) {
  876. switch (type) {
  877. case "arraybuffer":
  878. case "blob":
  879. case "json":
  880. resolve(request.response);
  881. return;
  882. }
  883. resolve(request.responseText);
  884. return;
  885. }
  886. reject(new Error(request.statusText));
  887. };
  888. request.send(null);
  889. });
  890. }
  891. class PageViewport {
  892. constructor({
  893. viewBox,
  894. scale,
  895. rotation,
  896. offsetX = 0,
  897. offsetY = 0,
  898. dontFlip = false
  899. }) {
  900. this.viewBox = viewBox;
  901. this.scale = scale;
  902. this.rotation = rotation;
  903. this.offsetX = offsetX;
  904. this.offsetY = offsetY;
  905. const centerX = (viewBox[2] + viewBox[0]) / 2;
  906. const centerY = (viewBox[3] + viewBox[1]) / 2;
  907. let rotateA, rotateB, rotateC, rotateD;
  908. rotation %= 360;
  909. if (rotation < 0) {
  910. rotation += 360;
  911. }
  912. switch (rotation) {
  913. case 180:
  914. rotateA = -1;
  915. rotateB = 0;
  916. rotateC = 0;
  917. rotateD = 1;
  918. break;
  919. case 90:
  920. rotateA = 0;
  921. rotateB = 1;
  922. rotateC = 1;
  923. rotateD = 0;
  924. break;
  925. case 270:
  926. rotateA = 0;
  927. rotateB = -1;
  928. rotateC = -1;
  929. rotateD = 0;
  930. break;
  931. case 0:
  932. rotateA = 1;
  933. rotateB = 0;
  934. rotateC = 0;
  935. rotateD = -1;
  936. break;
  937. default:
  938. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  939. }
  940. if (dontFlip) {
  941. rotateC = -rotateC;
  942. rotateD = -rotateD;
  943. }
  944. let offsetCanvasX, offsetCanvasY;
  945. let width, height;
  946. if (rotateA === 0) {
  947. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  948. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  949. width = (viewBox[3] - viewBox[1]) * scale;
  950. height = (viewBox[2] - viewBox[0]) * scale;
  951. } else {
  952. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  953. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  954. width = (viewBox[2] - viewBox[0]) * scale;
  955. height = (viewBox[3] - viewBox[1]) * scale;
  956. }
  957. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  958. this.width = width;
  959. this.height = height;
  960. }
  961. get rawDims() {
  962. const {
  963. viewBox
  964. } = this;
  965. return shadow(this, "rawDims", {
  966. pageWidth: viewBox[2] - viewBox[0],
  967. pageHeight: viewBox[3] - viewBox[1],
  968. pageX: viewBox[0],
  969. pageY: viewBox[1]
  970. });
  971. }
  972. clone({
  973. scale = this.scale,
  974. rotation = this.rotation,
  975. offsetX = this.offsetX,
  976. offsetY = this.offsetY,
  977. dontFlip = false
  978. } = {}) {
  979. return new PageViewport({
  980. viewBox: this.viewBox.slice(),
  981. scale,
  982. rotation,
  983. offsetX,
  984. offsetY,
  985. dontFlip
  986. });
  987. }
  988. convertToViewportPoint(x, y) {
  989. return Util.applyTransform([x, y], this.transform);
  990. }
  991. convertToViewportRectangle(rect) {
  992. const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);
  993. const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);
  994. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  995. }
  996. convertToPdfPoint(x, y) {
  997. return Util.applyInverseTransform([x, y], this.transform);
  998. }
  999. }
  1000. class RenderingCancelledException extends BaseException {
  1001. constructor(msg, extraDelay = 0) {
  1002. super(msg, "RenderingCancelledException");
  1003. this.extraDelay = extraDelay;
  1004. }
  1005. }
  1006. function isDataScheme(url) {
  1007. const ii = url.length;
  1008. let i = 0;
  1009. while (i < ii && url[i].trim() === "") {
  1010. i++;
  1011. }
  1012. return url.substring(i, i + 5).toLowerCase() === "data:";
  1013. }
  1014. function isPdfFile(filename) {
  1015. return typeof filename === "string" && /\.pdf$/i.test(filename);
  1016. }
  1017. function getFilenameFromUrl(url) {
  1018. [url] = url.split(/[#?]/, 1);
  1019. return url.substring(url.lastIndexOf("/") + 1);
  1020. }
  1021. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  1022. if (typeof url !== "string") {
  1023. return defaultFilename;
  1024. }
  1025. if (isDataScheme(url)) {
  1026. warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  1027. return defaultFilename;
  1028. }
  1029. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  1030. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  1031. const splitURI = reURI.exec(url);
  1032. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  1033. if (suggestedFilename) {
  1034. suggestedFilename = suggestedFilename[0];
  1035. if (suggestedFilename.includes("%")) {
  1036. try {
  1037. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  1038. } catch {}
  1039. }
  1040. }
  1041. return suggestedFilename || defaultFilename;
  1042. }
  1043. class StatTimer {
  1044. started = Object.create(null);
  1045. times = [];
  1046. time(name) {
  1047. if (name in this.started) {
  1048. warn(`Timer is already running for ${name}`);
  1049. }
  1050. this.started[name] = Date.now();
  1051. }
  1052. timeEnd(name) {
  1053. if (!(name in this.started)) {
  1054. warn(`Timer has not been started for ${name}`);
  1055. }
  1056. this.times.push({
  1057. name,
  1058. start: this.started[name],
  1059. end: Date.now()
  1060. });
  1061. delete this.started[name];
  1062. }
  1063. toString() {
  1064. const outBuf = [];
  1065. let longest = 0;
  1066. for (const {
  1067. name
  1068. } of this.times) {
  1069. longest = Math.max(name.length, longest);
  1070. }
  1071. for (const {
  1072. name,
  1073. start,
  1074. end
  1075. } of this.times) {
  1076. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  1077. }
  1078. return outBuf.join("");
  1079. }
  1080. }
  1081. function isValidFetchUrl(url, baseUrl) {
  1082. try {
  1083. const {
  1084. protocol
  1085. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  1086. return protocol === "http:" || protocol === "https:";
  1087. } catch {
  1088. return false;
  1089. }
  1090. }
  1091. function noContextMenu(e) {
  1092. e.preventDefault();
  1093. }
  1094. function deprecated(details) {
  1095. console.log("Deprecated API usage: " + details);
  1096. }
  1097. class PDFDateString {
  1098. static #regex;
  1099. static toDateObject(input) {
  1100. if (!input || typeof input !== "string") {
  1101. return null;
  1102. }
  1103. this.#regex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  1104. const matches = this.#regex.exec(input);
  1105. if (!matches) {
  1106. return null;
  1107. }
  1108. const year = parseInt(matches[1], 10);
  1109. let month = parseInt(matches[2], 10);
  1110. month = month >= 1 && month <= 12 ? month - 1 : 0;
  1111. let day = parseInt(matches[3], 10);
  1112. day = day >= 1 && day <= 31 ? day : 1;
  1113. let hour = parseInt(matches[4], 10);
  1114. hour = hour >= 0 && hour <= 23 ? hour : 0;
  1115. let minute = parseInt(matches[5], 10);
  1116. minute = minute >= 0 && minute <= 59 ? minute : 0;
  1117. let second = parseInt(matches[6], 10);
  1118. second = second >= 0 && second <= 59 ? second : 0;
  1119. const universalTimeRelation = matches[7] || "Z";
  1120. let offsetHour = parseInt(matches[8], 10);
  1121. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  1122. let offsetMinute = parseInt(matches[9], 10) || 0;
  1123. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  1124. if (universalTimeRelation === "-") {
  1125. hour += offsetHour;
  1126. minute += offsetMinute;
  1127. } else if (universalTimeRelation === "+") {
  1128. hour -= offsetHour;
  1129. minute -= offsetMinute;
  1130. }
  1131. return new Date(Date.UTC(year, month, day, hour, minute, second));
  1132. }
  1133. }
  1134. function getXfaPageViewport(xfaPage, {
  1135. scale = 1,
  1136. rotation = 0
  1137. }) {
  1138. const {
  1139. width,
  1140. height
  1141. } = xfaPage.attributes.style;
  1142. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  1143. return new PageViewport({
  1144. viewBox,
  1145. scale,
  1146. rotation
  1147. });
  1148. }
  1149. function getRGB(color) {
  1150. if (color.startsWith("#")) {
  1151. const colorRGB = parseInt(color.slice(1), 16);
  1152. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  1153. }
  1154. if (color.startsWith("rgb(")) {
  1155. return color.slice(4, -1).split(",").map(x => parseInt(x));
  1156. }
  1157. if (color.startsWith("rgba(")) {
  1158. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  1159. }
  1160. warn(`Not a valid color format: "${color}"`);
  1161. return [0, 0, 0];
  1162. }
  1163. function getColorValues(colors) {
  1164. const span = document.createElement("span");
  1165. span.style.visibility = "hidden";
  1166. document.body.append(span);
  1167. for (const name of colors.keys()) {
  1168. span.style.color = name;
  1169. const computedColor = window.getComputedStyle(span).color;
  1170. colors.set(name, getRGB(computedColor));
  1171. }
  1172. span.remove();
  1173. }
  1174. function getCurrentTransform(ctx) {
  1175. const {
  1176. a,
  1177. b,
  1178. c,
  1179. d,
  1180. e,
  1181. f
  1182. } = ctx.getTransform();
  1183. return [a, b, c, d, e, f];
  1184. }
  1185. function getCurrentTransformInverse(ctx) {
  1186. const {
  1187. a,
  1188. b,
  1189. c,
  1190. d,
  1191. e,
  1192. f
  1193. } = ctx.getTransform().invertSelf();
  1194. return [a, b, c, d, e, f];
  1195. }
  1196. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  1197. if (viewport instanceof PageViewport) {
  1198. const {
  1199. pageWidth,
  1200. pageHeight
  1201. } = viewport.rawDims;
  1202. const {
  1203. style
  1204. } = div;
  1205. const useRound = util_FeatureTest.isCSSRoundSupported;
  1206. const w = `var(--scale-factor) * ${pageWidth}px`,
  1207. h = `var(--scale-factor) * ${pageHeight}px`;
  1208. const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x, 1px))` : `calc(${w})`,
  1209. heightStr = useRound ? `round(down, ${h}, var(--scale-round-y, 1px))` : `calc(${h})`;
  1210. if (!mustFlip || viewport.rotation % 180 === 0) {
  1211. style.width = widthStr;
  1212. style.height = heightStr;
  1213. } else {
  1214. style.width = heightStr;
  1215. style.height = widthStr;
  1216. }
  1217. }
  1218. if (mustRotate) {
  1219. div.setAttribute("data-main-rotation", viewport.rotation);
  1220. }
  1221. }
  1222. class OutputScale {
  1223. constructor() {
  1224. const pixelRatio = window.devicePixelRatio || 1;
  1225. this.sx = pixelRatio;
  1226. this.sy = pixelRatio;
  1227. }
  1228. get scaled() {
  1229. return this.sx !== 1 || this.sy !== 1;
  1230. }
  1231. get symmetric() {
  1232. return this.sx === this.sy;
  1233. }
  1234. }
  1235. ;// ./src/display/editor/toolbar.js
  1236. class EditorToolbar {
  1237. #toolbar = null;
  1238. #colorPicker = null;
  1239. #editor;
  1240. #buttons = null;
  1241. #altText = null;
  1242. static #l10nRemove = null;
  1243. constructor(editor) {
  1244. this.#editor = editor;
  1245. EditorToolbar.#l10nRemove ||= Object.freeze({
  1246. freetext: "pdfjs-editor-remove-freetext-button",
  1247. highlight: "pdfjs-editor-remove-highlight-button",
  1248. ink: "pdfjs-editor-remove-ink-button",
  1249. stamp: "pdfjs-editor-remove-stamp-button"
  1250. });
  1251. }
  1252. render() {
  1253. const editToolbar = this.#toolbar = document.createElement("div");
  1254. editToolbar.classList.add("editToolbar", "hidden");
  1255. editToolbar.setAttribute("role", "toolbar");
  1256. const signal = this.#editor._uiManager._signal;
  1257. editToolbar.addEventListener("contextmenu", noContextMenu, {
  1258. signal
  1259. });
  1260. editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, {
  1261. signal
  1262. });
  1263. const buttons = this.#buttons = document.createElement("div");
  1264. buttons.className = "buttons";
  1265. editToolbar.append(buttons);
  1266. const position = this.#editor.toolbarPosition;
  1267. if (position) {
  1268. const {
  1269. style
  1270. } = editToolbar;
  1271. const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
  1272. style.insetInlineEnd = `${100 * x}%`;
  1273. style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
  1274. }
  1275. this.#addDeleteButton();
  1276. return editToolbar;
  1277. }
  1278. get div() {
  1279. return this.#toolbar;
  1280. }
  1281. static #pointerDown(e) {
  1282. e.stopPropagation();
  1283. }
  1284. #focusIn(e) {
  1285. this.#editor._focusEventsAllowed = false;
  1286. e.preventDefault();
  1287. e.stopPropagation();
  1288. }
  1289. #focusOut(e) {
  1290. this.#editor._focusEventsAllowed = true;
  1291. e.preventDefault();
  1292. e.stopPropagation();
  1293. }
  1294. #addListenersToElement(element) {
  1295. const signal = this.#editor._uiManager._signal;
  1296. element.addEventListener("focusin", this.#focusIn.bind(this), {
  1297. capture: true,
  1298. signal
  1299. });
  1300. element.addEventListener("focusout", this.#focusOut.bind(this), {
  1301. capture: true,
  1302. signal
  1303. });
  1304. element.addEventListener("contextmenu", noContextMenu, {
  1305. signal
  1306. });
  1307. }
  1308. hide() {
  1309. this.#toolbar.classList.add("hidden");
  1310. this.#colorPicker?.hideDropdown();
  1311. }
  1312. show() {
  1313. this.#toolbar.classList.remove("hidden");
  1314. this.#altText?.shown();
  1315. }
  1316. #addDeleteButton() {
  1317. const {
  1318. editorType,
  1319. _uiManager
  1320. } = this.#editor;
  1321. const button = document.createElement("button");
  1322. button.className = "delete";
  1323. button.tabIndex = 0;
  1324. button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]);
  1325. this.#addListenersToElement(button);
  1326. button.addEventListener("click", e => {
  1327. _uiManager.delete();
  1328. }, {
  1329. signal: _uiManager._signal
  1330. });
  1331. this.#buttons.append(button);
  1332. }
  1333. get #divider() {
  1334. const divider = document.createElement("div");
  1335. divider.className = "divider";
  1336. return divider;
  1337. }
  1338. async addAltText(altText) {
  1339. const button = await altText.render();
  1340. this.#addListenersToElement(button);
  1341. this.#buttons.prepend(button, this.#divider);
  1342. this.#altText = altText;
  1343. }
  1344. addColorPicker(colorPicker) {
  1345. this.#colorPicker = colorPicker;
  1346. const button = colorPicker.renderButton();
  1347. this.#addListenersToElement(button);
  1348. this.#buttons.prepend(button, this.#divider);
  1349. }
  1350. remove() {
  1351. this.#toolbar.remove();
  1352. this.#colorPicker?.destroy();
  1353. this.#colorPicker = null;
  1354. }
  1355. }
  1356. class HighlightToolbar {
  1357. #buttons = null;
  1358. #toolbar = null;
  1359. #uiManager;
  1360. constructor(uiManager) {
  1361. this.#uiManager = uiManager;
  1362. }
  1363. #render() {
  1364. const editToolbar = this.#toolbar = document.createElement("div");
  1365. editToolbar.className = "editToolbar";
  1366. editToolbar.setAttribute("role", "toolbar");
  1367. editToolbar.addEventListener("contextmenu", noContextMenu, {
  1368. signal: this.#uiManager._signal
  1369. });
  1370. const buttons = this.#buttons = document.createElement("div");
  1371. buttons.className = "buttons";
  1372. editToolbar.append(buttons);
  1373. this.#addHighlightButton();
  1374. return editToolbar;
  1375. }
  1376. #getLastPoint(boxes, isLTR) {
  1377. let lastY = 0;
  1378. let lastX = 0;
  1379. for (const box of boxes) {
  1380. const y = box.y + box.height;
  1381. if (y < lastY) {
  1382. continue;
  1383. }
  1384. const x = box.x + (isLTR ? box.width : 0);
  1385. if (y > lastY) {
  1386. lastX = x;
  1387. lastY = y;
  1388. continue;
  1389. }
  1390. if (isLTR) {
  1391. if (x > lastX) {
  1392. lastX = x;
  1393. }
  1394. } else if (x < lastX) {
  1395. lastX = x;
  1396. }
  1397. }
  1398. return [isLTR ? 1 - lastX : lastX, lastY];
  1399. }
  1400. show(parent, boxes, isLTR) {
  1401. const [x, y] = this.#getLastPoint(boxes, isLTR);
  1402. const {
  1403. style
  1404. } = this.#toolbar ||= this.#render();
  1405. parent.append(this.#toolbar);
  1406. style.insetInlineEnd = `${100 * x}%`;
  1407. style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;
  1408. }
  1409. hide() {
  1410. this.#toolbar.remove();
  1411. }
  1412. #addHighlightButton() {
  1413. const button = document.createElement("button");
  1414. button.className = "highlightButton";
  1415. button.tabIndex = 0;
  1416. button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`);
  1417. const span = document.createElement("span");
  1418. button.append(span);
  1419. span.className = "visuallyHidden";
  1420. span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label");
  1421. const signal = this.#uiManager._signal;
  1422. button.addEventListener("contextmenu", noContextMenu, {
  1423. signal
  1424. });
  1425. button.addEventListener("click", () => {
  1426. this.#uiManager.highlightSelection("floating_button");
  1427. }, {
  1428. signal
  1429. });
  1430. this.#buttons.append(button);
  1431. }
  1432. }
  1433. ;// ./src/display/editor/tools.js
  1434. function bindEvents(obj, element, names) {
  1435. for (const name of names) {
  1436. element.addEventListener(name, obj[name].bind(obj));
  1437. }
  1438. }
  1439. function opacityToHex(opacity) {
  1440. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  1441. }
  1442. class IdManager {
  1443. #id = 0;
  1444. get id() {
  1445. return `${AnnotationEditorPrefix}${this.#id++}`;
  1446. }
  1447. }
  1448. class ImageManager {
  1449. #baseId = getUuid();
  1450. #id = 0;
  1451. #cache = null;
  1452. static get _isSVGFittingCanvas() {
  1453. 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>`;
  1454. const canvas = new OffscreenCanvas(1, 3);
  1455. const ctx = canvas.getContext("2d", {
  1456. willReadFrequently: true
  1457. });
  1458. const image = new Image();
  1459. image.src = svg;
  1460. const promise = image.decode().then(() => {
  1461. ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
  1462. return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
  1463. });
  1464. return shadow(this, "_isSVGFittingCanvas", promise);
  1465. }
  1466. async #get(key, rawData) {
  1467. this.#cache ||= new Map();
  1468. let data = this.#cache.get(key);
  1469. if (data === null) {
  1470. return null;
  1471. }
  1472. if (data?.bitmap) {
  1473. data.refCounter += 1;
  1474. return data;
  1475. }
  1476. try {
  1477. data ||= {
  1478. bitmap: null,
  1479. id: `image_${this.#baseId}_${this.#id++}`,
  1480. refCounter: 0,
  1481. isSvg: false
  1482. };
  1483. let image;
  1484. if (typeof rawData === "string") {
  1485. data.url = rawData;
  1486. image = await fetchData(rawData, "blob");
  1487. } else if (rawData instanceof File) {
  1488. image = data.file = rawData;
  1489. } else if (rawData instanceof Blob) {
  1490. image = rawData;
  1491. }
  1492. if (image.type === "image/svg+xml") {
  1493. const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;
  1494. const fileReader = new FileReader();
  1495. const imageElement = new Image();
  1496. const imagePromise = new Promise((resolve, reject) => {
  1497. imageElement.onload = () => {
  1498. data.bitmap = imageElement;
  1499. data.isSvg = true;
  1500. resolve();
  1501. };
  1502. fileReader.onload = async () => {
  1503. const url = data.svgUrl = fileReader.result;
  1504. imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;
  1505. };
  1506. imageElement.onerror = fileReader.onerror = reject;
  1507. });
  1508. fileReader.readAsDataURL(image);
  1509. await imagePromise;
  1510. } else {
  1511. data.bitmap = await createImageBitmap(image);
  1512. }
  1513. data.refCounter = 1;
  1514. } catch (e) {
  1515. console.error(e);
  1516. data = null;
  1517. }
  1518. this.#cache.set(key, data);
  1519. if (data) {
  1520. this.#cache.set(data.id, data);
  1521. }
  1522. return data;
  1523. }
  1524. async getFromFile(file) {
  1525. const {
  1526. lastModified,
  1527. name,
  1528. size,
  1529. type
  1530. } = file;
  1531. return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
  1532. }
  1533. async getFromUrl(url) {
  1534. return this.#get(url, url);
  1535. }
  1536. async getFromBlob(id, blobPromise) {
  1537. const blob = await blobPromise;
  1538. return this.#get(id, blob);
  1539. }
  1540. async getFromId(id) {
  1541. this.#cache ||= new Map();
  1542. const data = this.#cache.get(id);
  1543. if (!data) {
  1544. return null;
  1545. }
  1546. if (data.bitmap) {
  1547. data.refCounter += 1;
  1548. return data;
  1549. }
  1550. if (data.file) {
  1551. return this.getFromFile(data.file);
  1552. }
  1553. if (data.blobPromise) {
  1554. const {
  1555. blobPromise
  1556. } = data;
  1557. delete data.blobPromise;
  1558. return this.getFromBlob(data.id, blobPromise);
  1559. }
  1560. return this.getFromUrl(data.url);
  1561. }
  1562. getFromCanvas(id, canvas) {
  1563. this.#cache ||= new Map();
  1564. let data = this.#cache.get(id);
  1565. if (data?.bitmap) {
  1566. data.refCounter += 1;
  1567. return data;
  1568. }
  1569. const offscreen = new OffscreenCanvas(canvas.width, canvas.height);
  1570. const ctx = offscreen.getContext("2d");
  1571. ctx.drawImage(canvas, 0, 0);
  1572. data = {
  1573. bitmap: offscreen.transferToImageBitmap(),
  1574. id: `image_${this.#baseId}_${this.#id++}`,
  1575. refCounter: 1,
  1576. isSvg: false
  1577. };
  1578. this.#cache.set(id, data);
  1579. this.#cache.set(data.id, data);
  1580. return data;
  1581. }
  1582. getSvgUrl(id) {
  1583. const data = this.#cache.get(id);
  1584. if (!data?.isSvg) {
  1585. return null;
  1586. }
  1587. return data.svgUrl;
  1588. }
  1589. deleteId(id) {
  1590. this.#cache ||= new Map();
  1591. const data = this.#cache.get(id);
  1592. if (!data) {
  1593. return;
  1594. }
  1595. data.refCounter -= 1;
  1596. if (data.refCounter !== 0) {
  1597. return;
  1598. }
  1599. const {
  1600. bitmap
  1601. } = data;
  1602. if (!data.url && !data.file) {
  1603. const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
  1604. const ctx = canvas.getContext("bitmaprenderer");
  1605. ctx.transferFromImageBitmap(bitmap);
  1606. data.blobPromise = canvas.convertToBlob();
  1607. }
  1608. bitmap.close?.();
  1609. data.bitmap = null;
  1610. }
  1611. isValidId(id) {
  1612. return id.startsWith(`image_${this.#baseId}_`);
  1613. }
  1614. }
  1615. class CommandManager {
  1616. #commands = [];
  1617. #locked = false;
  1618. #maxSize;
  1619. #position = -1;
  1620. constructor(maxSize = 128) {
  1621. this.#maxSize = maxSize;
  1622. }
  1623. add({
  1624. cmd,
  1625. undo,
  1626. post,
  1627. mustExec,
  1628. type = NaN,
  1629. overwriteIfSameType = false,
  1630. keepUndo = false
  1631. }) {
  1632. if (mustExec) {
  1633. cmd();
  1634. }
  1635. if (this.#locked) {
  1636. return;
  1637. }
  1638. const save = {
  1639. cmd,
  1640. undo,
  1641. post,
  1642. type
  1643. };
  1644. if (this.#position === -1) {
  1645. if (this.#commands.length > 0) {
  1646. this.#commands.length = 0;
  1647. }
  1648. this.#position = 0;
  1649. this.#commands.push(save);
  1650. return;
  1651. }
  1652. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  1653. if (keepUndo) {
  1654. save.undo = this.#commands[this.#position].undo;
  1655. }
  1656. this.#commands[this.#position] = save;
  1657. return;
  1658. }
  1659. const next = this.#position + 1;
  1660. if (next === this.#maxSize) {
  1661. this.#commands.splice(0, 1);
  1662. } else {
  1663. this.#position = next;
  1664. if (next < this.#commands.length) {
  1665. this.#commands.splice(next);
  1666. }
  1667. }
  1668. this.#commands.push(save);
  1669. }
  1670. undo() {
  1671. if (this.#position === -1) {
  1672. return;
  1673. }
  1674. this.#locked = true;
  1675. const {
  1676. undo,
  1677. post
  1678. } = this.#commands[this.#position];
  1679. undo();
  1680. post?.();
  1681. this.#locked = false;
  1682. this.#position -= 1;
  1683. }
  1684. redo() {
  1685. if (this.#position < this.#commands.length - 1) {
  1686. this.#position += 1;
  1687. this.#locked = true;
  1688. const {
  1689. cmd,
  1690. post
  1691. } = this.#commands[this.#position];
  1692. cmd();
  1693. post?.();
  1694. this.#locked = false;
  1695. }
  1696. }
  1697. hasSomethingToUndo() {
  1698. return this.#position !== -1;
  1699. }
  1700. hasSomethingToRedo() {
  1701. return this.#position < this.#commands.length - 1;
  1702. }
  1703. destroy() {
  1704. this.#commands = null;
  1705. }
  1706. }
  1707. class KeyboardManager {
  1708. constructor(callbacks) {
  1709. this.buffer = [];
  1710. this.callbacks = new Map();
  1711. this.allKeys = new Set();
  1712. const {
  1713. isMac
  1714. } = util_FeatureTest.platform;
  1715. for (const [keys, callback, options = {}] of callbacks) {
  1716. for (const key of keys) {
  1717. const isMacKey = key.startsWith("mac+");
  1718. if (isMac && isMacKey) {
  1719. this.callbacks.set(key.slice(4), {
  1720. callback,
  1721. options
  1722. });
  1723. this.allKeys.add(key.split("+").at(-1));
  1724. } else if (!isMac && !isMacKey) {
  1725. this.callbacks.set(key, {
  1726. callback,
  1727. options
  1728. });
  1729. this.allKeys.add(key.split("+").at(-1));
  1730. }
  1731. }
  1732. }
  1733. }
  1734. #serialize(event) {
  1735. if (event.altKey) {
  1736. this.buffer.push("alt");
  1737. }
  1738. if (event.ctrlKey) {
  1739. this.buffer.push("ctrl");
  1740. }
  1741. if (event.metaKey) {
  1742. this.buffer.push("meta");
  1743. }
  1744. if (event.shiftKey) {
  1745. this.buffer.push("shift");
  1746. }
  1747. this.buffer.push(event.key);
  1748. const str = this.buffer.join("+");
  1749. this.buffer.length = 0;
  1750. return str;
  1751. }
  1752. exec(self, event) {
  1753. if (!this.allKeys.has(event.key)) {
  1754. return;
  1755. }
  1756. const info = this.callbacks.get(this.#serialize(event));
  1757. if (!info) {
  1758. return;
  1759. }
  1760. const {
  1761. callback,
  1762. options: {
  1763. bubbles = false,
  1764. args = [],
  1765. checker = null
  1766. }
  1767. } = info;
  1768. if (checker && !checker(self, event)) {
  1769. return;
  1770. }
  1771. callback.bind(self, ...args, event)();
  1772. if (!bubbles) {
  1773. event.stopPropagation();
  1774. event.preventDefault();
  1775. }
  1776. }
  1777. }
  1778. class ColorManager {
  1779. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  1780. get _colors() {
  1781. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  1782. getColorValues(colors);
  1783. return shadow(this, "_colors", colors);
  1784. }
  1785. convert(color) {
  1786. const rgb = getRGB(color);
  1787. if (!window.matchMedia("(forced-colors: active)").matches) {
  1788. return rgb;
  1789. }
  1790. for (const [name, RGB] of this._colors) {
  1791. if (RGB.every((x, i) => x === rgb[i])) {
  1792. return ColorManager._colorsMapping.get(name);
  1793. }
  1794. }
  1795. return rgb;
  1796. }
  1797. getHexCode(name) {
  1798. const rgb = this._colors.get(name);
  1799. if (!rgb) {
  1800. return name;
  1801. }
  1802. return Util.makeHexColor(...rgb);
  1803. }
  1804. }
  1805. class AnnotationEditorUIManager {
  1806. #abortController = new AbortController();
  1807. #activeEditor = null;
  1808. #allEditors = new Map();
  1809. #allLayers = new Map();
  1810. #altTextManager = null;
  1811. #annotationStorage = null;
  1812. #changedExistingAnnotations = null;
  1813. #commandManager = new CommandManager();
  1814. #copyPasteAC = null;
  1815. #currentPageIndex = 0;
  1816. #deletedAnnotationsElementIds = new Set();
  1817. #draggingEditors = null;
  1818. #editorTypes = null;
  1819. #editorsToRescale = new Set();
  1820. #enableHighlightFloatingButton = false;
  1821. #enableUpdatedAddImage = false;
  1822. #enableNewAltTextWhenAddingImage = false;
  1823. #filterFactory = null;
  1824. #focusMainContainerTimeoutId = null;
  1825. #focusManagerAC = null;
  1826. #highlightColors = null;
  1827. #highlightWhenShiftUp = false;
  1828. #highlightToolbar = null;
  1829. #idManager = new IdManager();
  1830. #isEnabled = false;
  1831. #isWaiting = false;
  1832. #keyboardManagerAC = null;
  1833. #lastActiveElement = null;
  1834. #mainHighlightColorPicker = null;
  1835. #mlManager = null;
  1836. #mode = AnnotationEditorType.NONE;
  1837. #selectedEditors = new Set();
  1838. #selectedTextNode = null;
  1839. #pageColors = null;
  1840. #showAllStates = null;
  1841. #previousStates = {
  1842. isEditing: false,
  1843. isEmpty: true,
  1844. hasSomethingToUndo: false,
  1845. hasSomethingToRedo: false,
  1846. hasSelectedEditor: false,
  1847. hasSelectedText: false
  1848. };
  1849. #translation = [0, 0];
  1850. #translationTimeoutId = null;
  1851. #container = null;
  1852. #viewer = null;
  1853. #updateModeCapability = null;
  1854. static TRANSLATE_SMALL = 1;
  1855. static TRANSLATE_BIG = 10;
  1856. static get _keyboardManager() {
  1857. const proto = AnnotationEditorUIManager.prototype;
  1858. const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl();
  1859. const textInputChecker = (_self, {
  1860. target: el
  1861. }) => {
  1862. if (el instanceof HTMLInputElement) {
  1863. const {
  1864. type
  1865. } = el;
  1866. return type !== "text" && type !== "number";
  1867. }
  1868. return true;
  1869. };
  1870. const small = this.TRANSLATE_SMALL;
  1871. const big = this.TRANSLATE_BIG;
  1872. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
  1873. checker: textInputChecker
  1874. }], [["ctrl+z", "mac+meta+z"], proto.undo, {
  1875. checker: textInputChecker
  1876. }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
  1877. checker: textInputChecker
  1878. }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
  1879. checker: textInputChecker
  1880. }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
  1881. checker: (self, {
  1882. target: el
  1883. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled
  1884. }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
  1885. checker: (self, {
  1886. target: el
  1887. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement)
  1888. }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
  1889. args: [-small, 0],
  1890. checker: arrowChecker
  1891. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
  1892. args: [-big, 0],
  1893. checker: arrowChecker
  1894. }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
  1895. args: [small, 0],
  1896. checker: arrowChecker
  1897. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
  1898. args: [big, 0],
  1899. checker: arrowChecker
  1900. }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
  1901. args: [0, -small],
  1902. checker: arrowChecker
  1903. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
  1904. args: [0, -big],
  1905. checker: arrowChecker
  1906. }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
  1907. args: [0, small],
  1908. checker: arrowChecker
  1909. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
  1910. args: [0, big],
  1911. checker: arrowChecker
  1912. }]]));
  1913. }
  1914. constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager) {
  1915. const signal = this._signal = this.#abortController.signal;
  1916. this.#container = container;
  1917. this.#viewer = viewer;
  1918. this.#altTextManager = altTextManager;
  1919. this._eventBus = eventBus;
  1920. eventBus._on("editingaction", this.onEditingAction.bind(this), {
  1921. signal
  1922. });
  1923. eventBus._on("pagechanging", this.onPageChanging.bind(this), {
  1924. signal
  1925. });
  1926. eventBus._on("scalechanging", this.onScaleChanging.bind(this), {
  1927. signal
  1928. });
  1929. eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {
  1930. signal
  1931. });
  1932. eventBus._on("setpreference", this.onSetPreference.bind(this), {
  1933. signal
  1934. });
  1935. eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), {
  1936. signal
  1937. });
  1938. this.#addSelectionListener();
  1939. this.#addDragAndDropListeners();
  1940. this.#addKeyboardManager();
  1941. this.#annotationStorage = pdfDocument.annotationStorage;
  1942. this.#filterFactory = pdfDocument.filterFactory;
  1943. this.#pageColors = pageColors;
  1944. this.#highlightColors = highlightColors || null;
  1945. this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
  1946. this.#enableUpdatedAddImage = enableUpdatedAddImage;
  1947. this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;
  1948. this.#mlManager = mlManager || null;
  1949. this.viewParameters = {
  1950. realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
  1951. rotation: 0
  1952. };
  1953. this.isShiftKeyDown = false;
  1954. }
  1955. destroy() {
  1956. this.#updateModeCapability?.resolve();
  1957. this.#updateModeCapability = null;
  1958. this.#abortController?.abort();
  1959. this.#abortController = null;
  1960. this._signal = null;
  1961. for (const layer of this.#allLayers.values()) {
  1962. layer.destroy();
  1963. }
  1964. this.#allLayers.clear();
  1965. this.#allEditors.clear();
  1966. this.#editorsToRescale.clear();
  1967. this.#activeEditor = null;
  1968. this.#selectedEditors.clear();
  1969. this.#commandManager.destroy();
  1970. this.#altTextManager?.destroy();
  1971. this.#highlightToolbar?.hide();
  1972. this.#highlightToolbar = null;
  1973. if (this.#focusMainContainerTimeoutId) {
  1974. clearTimeout(this.#focusMainContainerTimeoutId);
  1975. this.#focusMainContainerTimeoutId = null;
  1976. }
  1977. if (this.#translationTimeoutId) {
  1978. clearTimeout(this.#translationTimeoutId);
  1979. this.#translationTimeoutId = null;
  1980. }
  1981. }
  1982. combinedSignal(ac) {
  1983. return AbortSignal.any([this._signal, ac.signal]);
  1984. }
  1985. get mlManager() {
  1986. return this.#mlManager;
  1987. }
  1988. get useNewAltTextFlow() {
  1989. return this.#enableUpdatedAddImage;
  1990. }
  1991. get useNewAltTextWhenAddingImage() {
  1992. return this.#enableNewAltTextWhenAddingImage;
  1993. }
  1994. get hcmFilter() {
  1995. return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
  1996. }
  1997. get direction() {
  1998. return shadow(this, "direction", getComputedStyle(this.#container).direction);
  1999. }
  2000. get highlightColors() {
  2001. return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null);
  2002. }
  2003. get highlightColorNames() {
  2004. return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null);
  2005. }
  2006. setMainHighlightColorPicker(colorPicker) {
  2007. this.#mainHighlightColorPicker = colorPicker;
  2008. }
  2009. editAltText(editor, firstTime = false) {
  2010. this.#altTextManager?.editAltText(this, editor, firstTime);
  2011. }
  2012. switchToMode(mode, callback) {
  2013. this._eventBus.on("annotationeditormodechanged", callback, {
  2014. once: true,
  2015. signal: this._signal
  2016. });
  2017. this._eventBus.dispatch("showannotationeditorui", {
  2018. source: this,
  2019. mode
  2020. });
  2021. }
  2022. setPreference(name, value) {
  2023. this._eventBus.dispatch("setpreference", {
  2024. source: this,
  2025. name,
  2026. value
  2027. });
  2028. }
  2029. onSetPreference({
  2030. name,
  2031. value
  2032. }) {
  2033. switch (name) {
  2034. case "enableNewAltTextWhenAddingImage":
  2035. this.#enableNewAltTextWhenAddingImage = value;
  2036. break;
  2037. }
  2038. }
  2039. onPageChanging({
  2040. pageNumber
  2041. }) {
  2042. this.#currentPageIndex = pageNumber - 1;
  2043. }
  2044. focusMainContainer() {
  2045. this.#container.focus();
  2046. }
  2047. findParent(x, y) {
  2048. for (const layer of this.#allLayers.values()) {
  2049. const {
  2050. x: layerX,
  2051. y: layerY,
  2052. width,
  2053. height
  2054. } = layer.div.getBoundingClientRect();
  2055. if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {
  2056. return layer;
  2057. }
  2058. }
  2059. return null;
  2060. }
  2061. disableUserSelect(value = false) {
  2062. this.#viewer.classList.toggle("noUserSelect", value);
  2063. }
  2064. addShouldRescale(editor) {
  2065. this.#editorsToRescale.add(editor);
  2066. }
  2067. removeShouldRescale(editor) {
  2068. this.#editorsToRescale.delete(editor);
  2069. }
  2070. onScaleChanging({
  2071. scale
  2072. }) {
  2073. this.commitOrRemove();
  2074. this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
  2075. for (const editor of this.#editorsToRescale) {
  2076. editor.onScaleChanging();
  2077. }
  2078. }
  2079. onRotationChanging({
  2080. pagesRotation
  2081. }) {
  2082. this.commitOrRemove();
  2083. this.viewParameters.rotation = pagesRotation;
  2084. }
  2085. #getAnchorElementForSelection({
  2086. anchorNode
  2087. }) {
  2088. return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
  2089. }
  2090. #getLayerForTextLayer(textLayer) {
  2091. const {
  2092. currentLayer
  2093. } = this;
  2094. if (currentLayer.hasTextLayer(textLayer)) {
  2095. return currentLayer;
  2096. }
  2097. for (const layer of this.#allLayers.values()) {
  2098. if (layer.hasTextLayer(textLayer)) {
  2099. return layer;
  2100. }
  2101. }
  2102. return null;
  2103. }
  2104. highlightSelection(methodOfCreation = "") {
  2105. const selection = document.getSelection();
  2106. if (!selection || selection.isCollapsed) {
  2107. return;
  2108. }
  2109. const {
  2110. anchorNode,
  2111. anchorOffset,
  2112. focusNode,
  2113. focusOffset
  2114. } = selection;
  2115. const text = selection.toString();
  2116. const anchorElement = this.#getAnchorElementForSelection(selection);
  2117. const textLayer = anchorElement.closest(".textLayer");
  2118. const boxes = this.getSelectionBoxes(textLayer);
  2119. if (!boxes) {
  2120. return;
  2121. }
  2122. selection.empty();
  2123. const layer = this.#getLayerForTextLayer(textLayer);
  2124. const isNoneMode = this.#mode === AnnotationEditorType.NONE;
  2125. const callback = () => {
  2126. layer?.createAndAddNewEditor({
  2127. x: 0,
  2128. y: 0
  2129. }, false, {
  2130. methodOfCreation,
  2131. boxes,
  2132. anchorNode,
  2133. anchorOffset,
  2134. focusNode,
  2135. focusOffset,
  2136. text
  2137. });
  2138. if (isNoneMode) {
  2139. this.showAllEditors("highlight", true, true);
  2140. }
  2141. };
  2142. if (isNoneMode) {
  2143. this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);
  2144. return;
  2145. }
  2146. callback();
  2147. }
  2148. #displayHighlightToolbar() {
  2149. const selection = document.getSelection();
  2150. if (!selection || selection.isCollapsed) {
  2151. return;
  2152. }
  2153. const anchorElement = this.#getAnchorElementForSelection(selection);
  2154. const textLayer = anchorElement.closest(".textLayer");
  2155. const boxes = this.getSelectionBoxes(textLayer);
  2156. if (!boxes) {
  2157. return;
  2158. }
  2159. this.#highlightToolbar ||= new HighlightToolbar(this);
  2160. this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr");
  2161. }
  2162. addToAnnotationStorage(editor) {
  2163. if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
  2164. this.#annotationStorage.setValue(editor.id, editor);
  2165. }
  2166. }
  2167. #selectionChange() {
  2168. const selection = document.getSelection();
  2169. if (!selection || selection.isCollapsed) {
  2170. if (this.#selectedTextNode) {
  2171. this.#highlightToolbar?.hide();
  2172. this.#selectedTextNode = null;
  2173. this.#dispatchUpdateStates({
  2174. hasSelectedText: false
  2175. });
  2176. }
  2177. return;
  2178. }
  2179. const {
  2180. anchorNode
  2181. } = selection;
  2182. if (anchorNode === this.#selectedTextNode) {
  2183. return;
  2184. }
  2185. const anchorElement = this.#getAnchorElementForSelection(selection);
  2186. const textLayer = anchorElement.closest(".textLayer");
  2187. if (!textLayer) {
  2188. if (this.#selectedTextNode) {
  2189. this.#highlightToolbar?.hide();
  2190. this.#selectedTextNode = null;
  2191. this.#dispatchUpdateStates({
  2192. hasSelectedText: false
  2193. });
  2194. }
  2195. return;
  2196. }
  2197. this.#highlightToolbar?.hide();
  2198. this.#selectedTextNode = anchorNode;
  2199. this.#dispatchUpdateStates({
  2200. hasSelectedText: true
  2201. });
  2202. if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
  2203. return;
  2204. }
  2205. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  2206. this.showAllEditors("highlight", true, true);
  2207. }
  2208. this.#highlightWhenShiftUp = this.isShiftKeyDown;
  2209. if (!this.isShiftKeyDown) {
  2210. const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;
  2211. activeLayer?.toggleDrawing();
  2212. const ac = new AbortController();
  2213. const signal = this.combinedSignal(ac);
  2214. const pointerup = e => {
  2215. if (e.type === "pointerup" && e.button !== 0) {
  2216. return;
  2217. }
  2218. ac.abort();
  2219. activeLayer?.toggleDrawing(true);
  2220. if (e.type === "pointerup") {
  2221. this.#onSelectEnd("main_toolbar");
  2222. }
  2223. };
  2224. window.addEventListener("pointerup", pointerup, {
  2225. signal
  2226. });
  2227. window.addEventListener("blur", pointerup, {
  2228. signal
  2229. });
  2230. }
  2231. }
  2232. #onSelectEnd(methodOfCreation = "") {
  2233. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  2234. this.highlightSelection(methodOfCreation);
  2235. } else if (this.#enableHighlightFloatingButton) {
  2236. this.#displayHighlightToolbar();
  2237. }
  2238. }
  2239. #addSelectionListener() {
  2240. document.addEventListener("selectionchange", this.#selectionChange.bind(this), {
  2241. signal: this._signal
  2242. });
  2243. }
  2244. #addFocusManager() {
  2245. if (this.#focusManagerAC) {
  2246. return;
  2247. }
  2248. this.#focusManagerAC = new AbortController();
  2249. const signal = this.combinedSignal(this.#focusManagerAC);
  2250. window.addEventListener("focus", this.focus.bind(this), {
  2251. signal
  2252. });
  2253. window.addEventListener("blur", this.blur.bind(this), {
  2254. signal
  2255. });
  2256. }
  2257. #removeFocusManager() {
  2258. this.#focusManagerAC?.abort();
  2259. this.#focusManagerAC = null;
  2260. }
  2261. blur() {
  2262. this.isShiftKeyDown = false;
  2263. if (this.#highlightWhenShiftUp) {
  2264. this.#highlightWhenShiftUp = false;
  2265. this.#onSelectEnd("main_toolbar");
  2266. }
  2267. if (!this.hasSelection) {
  2268. return;
  2269. }
  2270. const {
  2271. activeElement
  2272. } = document;
  2273. for (const editor of this.#selectedEditors) {
  2274. if (editor.div.contains(activeElement)) {
  2275. this.#lastActiveElement = [editor, activeElement];
  2276. editor._focusEventsAllowed = false;
  2277. break;
  2278. }
  2279. }
  2280. }
  2281. focus() {
  2282. if (!this.#lastActiveElement) {
  2283. return;
  2284. }
  2285. const [lastEditor, lastActiveElement] = this.#lastActiveElement;
  2286. this.#lastActiveElement = null;
  2287. lastActiveElement.addEventListener("focusin", () => {
  2288. lastEditor._focusEventsAllowed = true;
  2289. }, {
  2290. once: true,
  2291. signal: this._signal
  2292. });
  2293. lastActiveElement.focus();
  2294. }
  2295. #addKeyboardManager() {
  2296. if (this.#keyboardManagerAC) {
  2297. return;
  2298. }
  2299. this.#keyboardManagerAC = new AbortController();
  2300. const signal = this.combinedSignal(this.#keyboardManagerAC);
  2301. window.addEventListener("keydown", this.keydown.bind(this), {
  2302. signal
  2303. });
  2304. window.addEventListener("keyup", this.keyup.bind(this), {
  2305. signal
  2306. });
  2307. }
  2308. #removeKeyboardManager() {
  2309. this.#keyboardManagerAC?.abort();
  2310. this.#keyboardManagerAC = null;
  2311. }
  2312. #addCopyPasteListeners() {
  2313. if (this.#copyPasteAC) {
  2314. return;
  2315. }
  2316. this.#copyPasteAC = new AbortController();
  2317. const signal = this.combinedSignal(this.#copyPasteAC);
  2318. document.addEventListener("copy", this.copy.bind(this), {
  2319. signal
  2320. });
  2321. document.addEventListener("cut", this.cut.bind(this), {
  2322. signal
  2323. });
  2324. document.addEventListener("paste", this.paste.bind(this), {
  2325. signal
  2326. });
  2327. }
  2328. #removeCopyPasteListeners() {
  2329. this.#copyPasteAC?.abort();
  2330. this.#copyPasteAC = null;
  2331. }
  2332. #addDragAndDropListeners() {
  2333. const signal = this._signal;
  2334. document.addEventListener("dragover", this.dragOver.bind(this), {
  2335. signal
  2336. });
  2337. document.addEventListener("drop", this.drop.bind(this), {
  2338. signal
  2339. });
  2340. }
  2341. addEditListeners() {
  2342. this.#addKeyboardManager();
  2343. this.#addCopyPasteListeners();
  2344. }
  2345. removeEditListeners() {
  2346. this.#removeKeyboardManager();
  2347. this.#removeCopyPasteListeners();
  2348. }
  2349. dragOver(event) {
  2350. for (const {
  2351. type
  2352. } of event.dataTransfer.items) {
  2353. for (const editorType of this.#editorTypes) {
  2354. if (editorType.isHandlingMimeForPasting(type)) {
  2355. event.dataTransfer.dropEffect = "copy";
  2356. event.preventDefault();
  2357. return;
  2358. }
  2359. }
  2360. }
  2361. }
  2362. drop(event) {
  2363. for (const item of event.dataTransfer.items) {
  2364. for (const editorType of this.#editorTypes) {
  2365. if (editorType.isHandlingMimeForPasting(item.type)) {
  2366. editorType.paste(item, this.currentLayer);
  2367. event.preventDefault();
  2368. return;
  2369. }
  2370. }
  2371. }
  2372. }
  2373. copy(event) {
  2374. event.preventDefault();
  2375. this.#activeEditor?.commitOrRemove();
  2376. if (!this.hasSelection) {
  2377. return;
  2378. }
  2379. const editors = [];
  2380. for (const editor of this.#selectedEditors) {
  2381. const serialized = editor.serialize(true);
  2382. if (serialized) {
  2383. editors.push(serialized);
  2384. }
  2385. }
  2386. if (editors.length === 0) {
  2387. return;
  2388. }
  2389. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  2390. }
  2391. cut(event) {
  2392. this.copy(event);
  2393. this.delete();
  2394. }
  2395. async paste(event) {
  2396. event.preventDefault();
  2397. const {
  2398. clipboardData
  2399. } = event;
  2400. for (const item of clipboardData.items) {
  2401. for (const editorType of this.#editorTypes) {
  2402. if (editorType.isHandlingMimeForPasting(item.type)) {
  2403. editorType.paste(item, this.currentLayer);
  2404. return;
  2405. }
  2406. }
  2407. }
  2408. let data = clipboardData.getData("application/pdfjs");
  2409. if (!data) {
  2410. return;
  2411. }
  2412. try {
  2413. data = JSON.parse(data);
  2414. } catch (ex) {
  2415. warn(`paste: "${ex.message}".`);
  2416. return;
  2417. }
  2418. if (!Array.isArray(data)) {
  2419. return;
  2420. }
  2421. this.unselectAll();
  2422. const layer = this.currentLayer;
  2423. try {
  2424. const newEditors = [];
  2425. for (const editor of data) {
  2426. const deserializedEditor = await layer.deserialize(editor);
  2427. if (!deserializedEditor) {
  2428. return;
  2429. }
  2430. newEditors.push(deserializedEditor);
  2431. }
  2432. const cmd = () => {
  2433. for (const editor of newEditors) {
  2434. this.#addEditorToLayer(editor);
  2435. }
  2436. this.#selectEditors(newEditors);
  2437. };
  2438. const undo = () => {
  2439. for (const editor of newEditors) {
  2440. editor.remove();
  2441. }
  2442. };
  2443. this.addCommands({
  2444. cmd,
  2445. undo,
  2446. mustExec: true
  2447. });
  2448. } catch (ex) {
  2449. warn(`paste: "${ex.message}".`);
  2450. }
  2451. }
  2452. keydown(event) {
  2453. if (!this.isShiftKeyDown && event.key === "Shift") {
  2454. this.isShiftKeyDown = true;
  2455. }
  2456. if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
  2457. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  2458. }
  2459. }
  2460. keyup(event) {
  2461. if (this.isShiftKeyDown && event.key === "Shift") {
  2462. this.isShiftKeyDown = false;
  2463. if (this.#highlightWhenShiftUp) {
  2464. this.#highlightWhenShiftUp = false;
  2465. this.#onSelectEnd("main_toolbar");
  2466. }
  2467. }
  2468. }
  2469. onEditingAction({
  2470. name
  2471. }) {
  2472. switch (name) {
  2473. case "undo":
  2474. case "redo":
  2475. case "delete":
  2476. case "selectAll":
  2477. this[name]();
  2478. break;
  2479. case "highlightSelection":
  2480. this.highlightSelection("context_menu");
  2481. break;
  2482. }
  2483. }
  2484. #dispatchUpdateStates(details) {
  2485. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  2486. if (hasChanged) {
  2487. this._eventBus.dispatch("annotationeditorstateschanged", {
  2488. source: this,
  2489. details: Object.assign(this.#previousStates, details)
  2490. });
  2491. if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
  2492. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
  2493. }
  2494. }
  2495. }
  2496. #dispatchUpdateUI(details) {
  2497. this._eventBus.dispatch("annotationeditorparamschanged", {
  2498. source: this,
  2499. details
  2500. });
  2501. }
  2502. setEditingState(isEditing) {
  2503. if (isEditing) {
  2504. this.#addFocusManager();
  2505. this.#addCopyPasteListeners();
  2506. this.#dispatchUpdateStates({
  2507. isEditing: this.#mode !== AnnotationEditorType.NONE,
  2508. isEmpty: this.#isEmpty(),
  2509. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  2510. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  2511. hasSelectedEditor: false
  2512. });
  2513. } else {
  2514. this.#removeFocusManager();
  2515. this.#removeCopyPasteListeners();
  2516. this.#dispatchUpdateStates({
  2517. isEditing: false
  2518. });
  2519. this.disableUserSelect(false);
  2520. }
  2521. }
  2522. registerEditorTypes(types) {
  2523. if (this.#editorTypes) {
  2524. return;
  2525. }
  2526. this.#editorTypes = types;
  2527. for (const editorType of this.#editorTypes) {
  2528. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  2529. }
  2530. }
  2531. getId() {
  2532. return this.#idManager.id;
  2533. }
  2534. get currentLayer() {
  2535. return this.#allLayers.get(this.#currentPageIndex);
  2536. }
  2537. getLayer(pageIndex) {
  2538. return this.#allLayers.get(pageIndex);
  2539. }
  2540. get currentPageIndex() {
  2541. return this.#currentPageIndex;
  2542. }
  2543. addLayer(layer) {
  2544. this.#allLayers.set(layer.pageIndex, layer);
  2545. if (this.#isEnabled) {
  2546. layer.enable();
  2547. } else {
  2548. layer.disable();
  2549. }
  2550. }
  2551. removeLayer(layer) {
  2552. this.#allLayers.delete(layer.pageIndex);
  2553. }
  2554. async updateMode(mode, editId = null, isFromKeyboard = false) {
  2555. if (this.#mode === mode) {
  2556. return;
  2557. }
  2558. if (this.#updateModeCapability) {
  2559. await this.#updateModeCapability.promise;
  2560. if (!this.#updateModeCapability) {
  2561. return;
  2562. }
  2563. }
  2564. this.#updateModeCapability = Promise.withResolvers();
  2565. this.#mode = mode;
  2566. if (mode === AnnotationEditorType.NONE) {
  2567. this.setEditingState(false);
  2568. this.#disableAll();
  2569. this.#updateModeCapability.resolve();
  2570. return;
  2571. }
  2572. this.setEditingState(true);
  2573. await this.#enableAll();
  2574. this.unselectAll();
  2575. for (const layer of this.#allLayers.values()) {
  2576. layer.updateMode(mode);
  2577. }
  2578. if (!editId) {
  2579. if (isFromKeyboard) {
  2580. this.addNewEditorFromKeyboard();
  2581. }
  2582. this.#updateModeCapability.resolve();
  2583. return;
  2584. }
  2585. for (const editor of this.#allEditors.values()) {
  2586. if (editor.annotationElementId === editId) {
  2587. this.setSelected(editor);
  2588. editor.enterInEditMode();
  2589. } else {
  2590. editor.unselect();
  2591. }
  2592. }
  2593. this.#updateModeCapability.resolve();
  2594. }
  2595. addNewEditorFromKeyboard() {
  2596. if (this.currentLayer.canCreateNewEmptyEditor()) {
  2597. this.currentLayer.addNewEditor();
  2598. }
  2599. }
  2600. updateToolbar(mode) {
  2601. if (mode === this.#mode) {
  2602. return;
  2603. }
  2604. this._eventBus.dispatch("switchannotationeditormode", {
  2605. source: this,
  2606. mode
  2607. });
  2608. }
  2609. updateParams(type, value) {
  2610. if (!this.#editorTypes) {
  2611. return;
  2612. }
  2613. switch (type) {
  2614. case AnnotationEditorParamsType.CREATE:
  2615. this.currentLayer.addNewEditor();
  2616. return;
  2617. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  2618. this.#mainHighlightColorPicker?.updateColor(value);
  2619. break;
  2620. case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
  2621. this._eventBus.dispatch("reporttelemetry", {
  2622. source: this,
  2623. details: {
  2624. type: "editing",
  2625. data: {
  2626. type: "highlight",
  2627. action: "toggle_visibility"
  2628. }
  2629. }
  2630. });
  2631. (this.#showAllStates ||= new Map()).set(type, value);
  2632. this.showAllEditors("highlight", value);
  2633. break;
  2634. }
  2635. for (const editor of this.#selectedEditors) {
  2636. editor.updateParams(type, value);
  2637. }
  2638. for (const editorType of this.#editorTypes) {
  2639. editorType.updateDefaultParams(type, value);
  2640. }
  2641. }
  2642. showAllEditors(type, visible, updateButton = false) {
  2643. for (const editor of this.#allEditors.values()) {
  2644. if (editor.editorType === type) {
  2645. editor.show(visible);
  2646. }
  2647. }
  2648. const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
  2649. if (state !== visible) {
  2650. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
  2651. }
  2652. }
  2653. enableWaiting(mustWait = false) {
  2654. if (this.#isWaiting === mustWait) {
  2655. return;
  2656. }
  2657. this.#isWaiting = mustWait;
  2658. for (const layer of this.#allLayers.values()) {
  2659. if (mustWait) {
  2660. layer.disableClick();
  2661. } else {
  2662. layer.enableClick();
  2663. }
  2664. layer.div.classList.toggle("waiting", mustWait);
  2665. }
  2666. }
  2667. async #enableAll() {
  2668. if (!this.#isEnabled) {
  2669. this.#isEnabled = true;
  2670. const promises = [];
  2671. for (const layer of this.#allLayers.values()) {
  2672. promises.push(layer.enable());
  2673. }
  2674. await Promise.all(promises);
  2675. for (const editor of this.#allEditors.values()) {
  2676. editor.enable();
  2677. }
  2678. }
  2679. }
  2680. #disableAll() {
  2681. this.unselectAll();
  2682. if (this.#isEnabled) {
  2683. this.#isEnabled = false;
  2684. for (const layer of this.#allLayers.values()) {
  2685. layer.disable();
  2686. }
  2687. for (const editor of this.#allEditors.values()) {
  2688. editor.disable();
  2689. }
  2690. }
  2691. }
  2692. getEditors(pageIndex) {
  2693. const editors = [];
  2694. for (const editor of this.#allEditors.values()) {
  2695. if (editor.pageIndex === pageIndex) {
  2696. editors.push(editor);
  2697. }
  2698. }
  2699. return editors;
  2700. }
  2701. getEditor(id) {
  2702. return this.#allEditors.get(id);
  2703. }
  2704. addEditor(editor) {
  2705. this.#allEditors.set(editor.id, editor);
  2706. }
  2707. removeEditor(editor) {
  2708. if (editor.div.contains(document.activeElement)) {
  2709. if (this.#focusMainContainerTimeoutId) {
  2710. clearTimeout(this.#focusMainContainerTimeoutId);
  2711. }
  2712. this.#focusMainContainerTimeoutId = setTimeout(() => {
  2713. this.focusMainContainer();
  2714. this.#focusMainContainerTimeoutId = null;
  2715. }, 0);
  2716. }
  2717. this.#allEditors.delete(editor.id);
  2718. this.unselect(editor);
  2719. if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
  2720. this.#annotationStorage?.remove(editor.id);
  2721. }
  2722. }
  2723. addDeletedAnnotationElement(editor) {
  2724. this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
  2725. this.addChangedExistingAnnotation(editor);
  2726. editor.deleted = true;
  2727. }
  2728. isDeletedAnnotationElement(annotationElementId) {
  2729. return this.#deletedAnnotationsElementIds.has(annotationElementId);
  2730. }
  2731. removeDeletedAnnotationElement(editor) {
  2732. this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
  2733. this.removeChangedExistingAnnotation(editor);
  2734. editor.deleted = false;
  2735. }
  2736. #addEditorToLayer(editor) {
  2737. const layer = this.#allLayers.get(editor.pageIndex);
  2738. if (layer) {
  2739. layer.addOrRebuild(editor);
  2740. } else {
  2741. this.addEditor(editor);
  2742. this.addToAnnotationStorage(editor);
  2743. }
  2744. }
  2745. setActiveEditor(editor) {
  2746. if (this.#activeEditor === editor) {
  2747. return;
  2748. }
  2749. this.#activeEditor = editor;
  2750. if (editor) {
  2751. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2752. }
  2753. }
  2754. get #lastSelectedEditor() {
  2755. let ed = null;
  2756. for (ed of this.#selectedEditors) {}
  2757. return ed;
  2758. }
  2759. updateUI(editor) {
  2760. if (this.#lastSelectedEditor === editor) {
  2761. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2762. }
  2763. }
  2764. toggleSelected(editor) {
  2765. if (this.#selectedEditors.has(editor)) {
  2766. this.#selectedEditors.delete(editor);
  2767. editor.unselect();
  2768. this.#dispatchUpdateStates({
  2769. hasSelectedEditor: this.hasSelection
  2770. });
  2771. return;
  2772. }
  2773. this.#selectedEditors.add(editor);
  2774. editor.select();
  2775. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2776. this.#dispatchUpdateStates({
  2777. hasSelectedEditor: true
  2778. });
  2779. }
  2780. setSelected(editor) {
  2781. for (const ed of this.#selectedEditors) {
  2782. if (ed !== editor) {
  2783. ed.unselect();
  2784. }
  2785. }
  2786. this.#selectedEditors.clear();
  2787. this.#selectedEditors.add(editor);
  2788. editor.select();
  2789. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2790. this.#dispatchUpdateStates({
  2791. hasSelectedEditor: true
  2792. });
  2793. }
  2794. isSelected(editor) {
  2795. return this.#selectedEditors.has(editor);
  2796. }
  2797. get firstSelectedEditor() {
  2798. return this.#selectedEditors.values().next().value;
  2799. }
  2800. unselect(editor) {
  2801. editor.unselect();
  2802. this.#selectedEditors.delete(editor);
  2803. this.#dispatchUpdateStates({
  2804. hasSelectedEditor: this.hasSelection
  2805. });
  2806. }
  2807. get hasSelection() {
  2808. return this.#selectedEditors.size !== 0;
  2809. }
  2810. get isEnterHandled() {
  2811. return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
  2812. }
  2813. undo() {
  2814. this.#commandManager.undo();
  2815. this.#dispatchUpdateStates({
  2816. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  2817. hasSomethingToRedo: true,
  2818. isEmpty: this.#isEmpty()
  2819. });
  2820. }
  2821. redo() {
  2822. this.#commandManager.redo();
  2823. this.#dispatchUpdateStates({
  2824. hasSomethingToUndo: true,
  2825. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  2826. isEmpty: this.#isEmpty()
  2827. });
  2828. }
  2829. addCommands(params) {
  2830. this.#commandManager.add(params);
  2831. this.#dispatchUpdateStates({
  2832. hasSomethingToUndo: true,
  2833. hasSomethingToRedo: false,
  2834. isEmpty: this.#isEmpty()
  2835. });
  2836. }
  2837. #isEmpty() {
  2838. if (this.#allEditors.size === 0) {
  2839. return true;
  2840. }
  2841. if (this.#allEditors.size === 1) {
  2842. for (const editor of this.#allEditors.values()) {
  2843. return editor.isEmpty();
  2844. }
  2845. }
  2846. return false;
  2847. }
  2848. delete() {
  2849. this.commitOrRemove();
  2850. if (!this.hasSelection) {
  2851. return;
  2852. }
  2853. const editors = [...this.#selectedEditors];
  2854. const cmd = () => {
  2855. for (const editor of editors) {
  2856. editor.remove();
  2857. }
  2858. };
  2859. const undo = () => {
  2860. for (const editor of editors) {
  2861. this.#addEditorToLayer(editor);
  2862. }
  2863. };
  2864. this.addCommands({
  2865. cmd,
  2866. undo,
  2867. mustExec: true
  2868. });
  2869. }
  2870. commitOrRemove() {
  2871. this.#activeEditor?.commitOrRemove();
  2872. }
  2873. hasSomethingToControl() {
  2874. return this.#activeEditor || this.hasSelection;
  2875. }
  2876. #selectEditors(editors) {
  2877. for (const editor of this.#selectedEditors) {
  2878. editor.unselect();
  2879. }
  2880. this.#selectedEditors.clear();
  2881. for (const editor of editors) {
  2882. if (editor.isEmpty()) {
  2883. continue;
  2884. }
  2885. this.#selectedEditors.add(editor);
  2886. editor.select();
  2887. }
  2888. this.#dispatchUpdateStates({
  2889. hasSelectedEditor: this.hasSelection
  2890. });
  2891. }
  2892. selectAll() {
  2893. for (const editor of this.#selectedEditors) {
  2894. editor.commit();
  2895. }
  2896. this.#selectEditors(this.#allEditors.values());
  2897. }
  2898. unselectAll() {
  2899. if (this.#activeEditor) {
  2900. this.#activeEditor.commitOrRemove();
  2901. if (this.#mode !== AnnotationEditorType.NONE) {
  2902. return;
  2903. }
  2904. }
  2905. if (!this.hasSelection) {
  2906. return;
  2907. }
  2908. for (const editor of this.#selectedEditors) {
  2909. editor.unselect();
  2910. }
  2911. this.#selectedEditors.clear();
  2912. this.#dispatchUpdateStates({
  2913. hasSelectedEditor: false
  2914. });
  2915. }
  2916. translateSelectedEditors(x, y, noCommit = false) {
  2917. if (!noCommit) {
  2918. this.commitOrRemove();
  2919. }
  2920. if (!this.hasSelection) {
  2921. return;
  2922. }
  2923. this.#translation[0] += x;
  2924. this.#translation[1] += y;
  2925. const [totalX, totalY] = this.#translation;
  2926. const editors = [...this.#selectedEditors];
  2927. const TIME_TO_WAIT = 1000;
  2928. if (this.#translationTimeoutId) {
  2929. clearTimeout(this.#translationTimeoutId);
  2930. }
  2931. this.#translationTimeoutId = setTimeout(() => {
  2932. this.#translationTimeoutId = null;
  2933. this.#translation[0] = this.#translation[1] = 0;
  2934. this.addCommands({
  2935. cmd: () => {
  2936. for (const editor of editors) {
  2937. if (this.#allEditors.has(editor.id)) {
  2938. editor.translateInPage(totalX, totalY);
  2939. }
  2940. }
  2941. },
  2942. undo: () => {
  2943. for (const editor of editors) {
  2944. if (this.#allEditors.has(editor.id)) {
  2945. editor.translateInPage(-totalX, -totalY);
  2946. }
  2947. }
  2948. },
  2949. mustExec: false
  2950. });
  2951. }, TIME_TO_WAIT);
  2952. for (const editor of editors) {
  2953. editor.translateInPage(x, y);
  2954. }
  2955. }
  2956. setUpDragSession() {
  2957. if (!this.hasSelection) {
  2958. return;
  2959. }
  2960. this.disableUserSelect(true);
  2961. this.#draggingEditors = new Map();
  2962. for (const editor of this.#selectedEditors) {
  2963. this.#draggingEditors.set(editor, {
  2964. savedX: editor.x,
  2965. savedY: editor.y,
  2966. savedPageIndex: editor.pageIndex,
  2967. newX: 0,
  2968. newY: 0,
  2969. newPageIndex: -1
  2970. });
  2971. }
  2972. }
  2973. endDragSession() {
  2974. if (!this.#draggingEditors) {
  2975. return false;
  2976. }
  2977. this.disableUserSelect(false);
  2978. const map = this.#draggingEditors;
  2979. this.#draggingEditors = null;
  2980. let mustBeAddedInUndoStack = false;
  2981. for (const [{
  2982. x,
  2983. y,
  2984. pageIndex
  2985. }, value] of map) {
  2986. value.newX = x;
  2987. value.newY = y;
  2988. value.newPageIndex = pageIndex;
  2989. mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex;
  2990. }
  2991. if (!mustBeAddedInUndoStack) {
  2992. return false;
  2993. }
  2994. const move = (editor, x, y, pageIndex) => {
  2995. if (this.#allEditors.has(editor.id)) {
  2996. const parent = this.#allLayers.get(pageIndex);
  2997. if (parent) {
  2998. editor._setParentAndPosition(parent, x, y);
  2999. } else {
  3000. editor.pageIndex = pageIndex;
  3001. editor.x = x;
  3002. editor.y = y;
  3003. }
  3004. }
  3005. };
  3006. this.addCommands({
  3007. cmd: () => {
  3008. for (const [editor, {
  3009. newX,
  3010. newY,
  3011. newPageIndex
  3012. }] of map) {
  3013. move(editor, newX, newY, newPageIndex);
  3014. }
  3015. },
  3016. undo: () => {
  3017. for (const [editor, {
  3018. savedX,
  3019. savedY,
  3020. savedPageIndex
  3021. }] of map) {
  3022. move(editor, savedX, savedY, savedPageIndex);
  3023. }
  3024. },
  3025. mustExec: true
  3026. });
  3027. return true;
  3028. }
  3029. dragSelectedEditors(tx, ty) {
  3030. if (!this.#draggingEditors) {
  3031. return;
  3032. }
  3033. for (const editor of this.#draggingEditors.keys()) {
  3034. editor.drag(tx, ty);
  3035. }
  3036. }
  3037. rebuild(editor) {
  3038. if (editor.parent === null) {
  3039. const parent = this.getLayer(editor.pageIndex);
  3040. if (parent) {
  3041. parent.changeParent(editor);
  3042. parent.addOrRebuild(editor);
  3043. } else {
  3044. this.addEditor(editor);
  3045. this.addToAnnotationStorage(editor);
  3046. editor.rebuild();
  3047. }
  3048. } else {
  3049. editor.parent.addOrRebuild(editor);
  3050. }
  3051. }
  3052. get isEditorHandlingKeyboard() {
  3053. return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
  3054. }
  3055. isActive(editor) {
  3056. return this.#activeEditor === editor;
  3057. }
  3058. getActive() {
  3059. return this.#activeEditor;
  3060. }
  3061. getMode() {
  3062. return this.#mode;
  3063. }
  3064. get imageManager() {
  3065. return shadow(this, "imageManager", new ImageManager());
  3066. }
  3067. getSelectionBoxes(textLayer) {
  3068. if (!textLayer) {
  3069. return null;
  3070. }
  3071. const selection = document.getSelection();
  3072. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  3073. if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) {
  3074. return null;
  3075. }
  3076. }
  3077. const {
  3078. x: layerX,
  3079. y: layerY,
  3080. width: parentWidth,
  3081. height: parentHeight
  3082. } = textLayer.getBoundingClientRect();
  3083. let rotator;
  3084. switch (textLayer.getAttribute("data-main-rotation")) {
  3085. case "90":
  3086. rotator = (x, y, w, h) => ({
  3087. x: (y - layerY) / parentHeight,
  3088. y: 1 - (x + w - layerX) / parentWidth,
  3089. width: h / parentHeight,
  3090. height: w / parentWidth
  3091. });
  3092. break;
  3093. case "180":
  3094. rotator = (x, y, w, h) => ({
  3095. x: 1 - (x + w - layerX) / parentWidth,
  3096. y: 1 - (y + h - layerY) / parentHeight,
  3097. width: w / parentWidth,
  3098. height: h / parentHeight
  3099. });
  3100. break;
  3101. case "270":
  3102. rotator = (x, y, w, h) => ({
  3103. x: 1 - (y + h - layerY) / parentHeight,
  3104. y: (x - layerX) / parentWidth,
  3105. width: h / parentHeight,
  3106. height: w / parentWidth
  3107. });
  3108. break;
  3109. default:
  3110. rotator = (x, y, w, h) => ({
  3111. x: (x - layerX) / parentWidth,
  3112. y: (y - layerY) / parentHeight,
  3113. width: w / parentWidth,
  3114. height: h / parentHeight
  3115. });
  3116. break;
  3117. }
  3118. const boxes = [];
  3119. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  3120. const range = selection.getRangeAt(i);
  3121. if (range.collapsed) {
  3122. continue;
  3123. }
  3124. for (const {
  3125. x,
  3126. y,
  3127. width,
  3128. height
  3129. } of range.getClientRects()) {
  3130. if (width === 0 || height === 0) {
  3131. continue;
  3132. }
  3133. boxes.push(rotator(x, y, width, height));
  3134. }
  3135. }
  3136. return boxes.length === 0 ? null : boxes;
  3137. }
  3138. addChangedExistingAnnotation({
  3139. annotationElementId,
  3140. id
  3141. }) {
  3142. (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id);
  3143. }
  3144. removeChangedExistingAnnotation({
  3145. annotationElementId
  3146. }) {
  3147. this.#changedExistingAnnotations?.delete(annotationElementId);
  3148. }
  3149. renderAnnotationElement(annotation) {
  3150. const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
  3151. if (!editorId) {
  3152. return;
  3153. }
  3154. const editor = this.#annotationStorage.getRawValue(editorId);
  3155. if (!editor) {
  3156. return;
  3157. }
  3158. if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
  3159. return;
  3160. }
  3161. editor.renderAnnotationElement(annotation);
  3162. }
  3163. }
  3164. ;// ./src/display/editor/alt_text.js
  3165. class AltText {
  3166. #altText = null;
  3167. #altTextDecorative = false;
  3168. #altTextButton = null;
  3169. #altTextButtonLabel = null;
  3170. #altTextTooltip = null;
  3171. #altTextTooltipTimeout = null;
  3172. #altTextWasFromKeyBoard = false;
  3173. #badge = null;
  3174. #editor = null;
  3175. #guessedText = null;
  3176. #textWithDisclaimer = null;
  3177. #useNewAltTextFlow = false;
  3178. static #l10nNewButton = null;
  3179. static _l10n = null;
  3180. constructor(editor) {
  3181. this.#editor = editor;
  3182. this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;
  3183. AltText.#l10nNewButton ||= Object.freeze({
  3184. added: "pdfjs-editor-new-alt-text-added-button",
  3185. "added-label": "pdfjs-editor-new-alt-text-added-button-label",
  3186. missing: "pdfjs-editor-new-alt-text-missing-button",
  3187. "missing-label": "pdfjs-editor-new-alt-text-missing-button-label",
  3188. review: "pdfjs-editor-new-alt-text-to-review-button",
  3189. "review-label": "pdfjs-editor-new-alt-text-to-review-button-label"
  3190. });
  3191. }
  3192. static initialize(l10n) {
  3193. AltText._l10n ??= l10n;
  3194. }
  3195. async render() {
  3196. const altText = this.#altTextButton = document.createElement("button");
  3197. altText.className = "altText";
  3198. altText.tabIndex = "0";
  3199. const label = this.#altTextButtonLabel = document.createElement("span");
  3200. altText.append(label);
  3201. if (this.#useNewAltTextFlow) {
  3202. altText.classList.add("new");
  3203. altText.setAttribute("data-l10n-id", AltText.#l10nNewButton.missing);
  3204. label.setAttribute("data-l10n-id", AltText.#l10nNewButton["missing-label"]);
  3205. } else {
  3206. altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button");
  3207. label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label");
  3208. }
  3209. const signal = this.#editor._uiManager._signal;
  3210. altText.addEventListener("contextmenu", noContextMenu, {
  3211. signal
  3212. });
  3213. altText.addEventListener("pointerdown", event => event.stopPropagation(), {
  3214. signal
  3215. });
  3216. const onClick = event => {
  3217. event.preventDefault();
  3218. this.#editor._uiManager.editAltText(this.#editor);
  3219. if (this.#useNewAltTextFlow) {
  3220. this.#editor._reportTelemetry({
  3221. action: "pdfjs.image.alt_text.image_status_label_clicked",
  3222. data: {
  3223. label: this.#label
  3224. }
  3225. });
  3226. }
  3227. };
  3228. altText.addEventListener("click", onClick, {
  3229. capture: true,
  3230. signal
  3231. });
  3232. altText.addEventListener("keydown", event => {
  3233. if (event.target === altText && event.key === "Enter") {
  3234. this.#altTextWasFromKeyBoard = true;
  3235. onClick(event);
  3236. }
  3237. }, {
  3238. signal
  3239. });
  3240. await this.#setState();
  3241. return altText;
  3242. }
  3243. get #label() {
  3244. return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";
  3245. }
  3246. finish() {
  3247. if (!this.#altTextButton) {
  3248. return;
  3249. }
  3250. this.#altTextButton.focus({
  3251. focusVisible: this.#altTextWasFromKeyBoard
  3252. });
  3253. this.#altTextWasFromKeyBoard = false;
  3254. }
  3255. isEmpty() {
  3256. if (this.#useNewAltTextFlow) {
  3257. return this.#altText === null;
  3258. }
  3259. return !this.#altText && !this.#altTextDecorative;
  3260. }
  3261. hasData() {
  3262. if (this.#useNewAltTextFlow) {
  3263. return this.#altText !== null || !!this.#guessedText;
  3264. }
  3265. return this.isEmpty();
  3266. }
  3267. get guessedText() {
  3268. return this.#guessedText;
  3269. }
  3270. async setGuessedText(guessedText) {
  3271. if (this.#altText !== null) {
  3272. return;
  3273. }
  3274. this.#guessedText = guessedText;
  3275. this.#textWithDisclaimer = await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", {
  3276. generatedAltText: guessedText
  3277. });
  3278. this.#setState();
  3279. }
  3280. toggleAltTextBadge(visibility = false) {
  3281. if (!this.#useNewAltTextFlow || this.#altText) {
  3282. this.#badge?.remove();
  3283. this.#badge = null;
  3284. return;
  3285. }
  3286. if (!this.#badge) {
  3287. const badge = this.#badge = document.createElement("div");
  3288. badge.className = "noAltTextBadge";
  3289. this.#editor.div.append(badge);
  3290. }
  3291. this.#badge.classList.toggle("hidden", !visibility);
  3292. }
  3293. serialize(isForCopying) {
  3294. let altText = this.#altText;
  3295. if (!isForCopying && this.#guessedText === altText) {
  3296. altText = this.#textWithDisclaimer;
  3297. }
  3298. return {
  3299. altText,
  3300. decorative: this.#altTextDecorative,
  3301. guessedText: this.#guessedText,
  3302. textWithDisclaimer: this.#textWithDisclaimer
  3303. };
  3304. }
  3305. get data() {
  3306. return {
  3307. altText: this.#altText,
  3308. decorative: this.#altTextDecorative
  3309. };
  3310. }
  3311. set data({
  3312. altText,
  3313. decorative,
  3314. guessedText,
  3315. textWithDisclaimer,
  3316. cancel = false
  3317. }) {
  3318. if (guessedText) {
  3319. this.#guessedText = guessedText;
  3320. this.#textWithDisclaimer = textWithDisclaimer;
  3321. }
  3322. if (this.#altText === altText && this.#altTextDecorative === decorative) {
  3323. return;
  3324. }
  3325. if (!cancel) {
  3326. this.#altText = altText;
  3327. this.#altTextDecorative = decorative;
  3328. }
  3329. this.#setState();
  3330. }
  3331. toggle(enabled = false) {
  3332. if (!this.#altTextButton) {
  3333. return;
  3334. }
  3335. if (!enabled && this.#altTextTooltipTimeout) {
  3336. clearTimeout(this.#altTextTooltipTimeout);
  3337. this.#altTextTooltipTimeout = null;
  3338. }
  3339. this.#altTextButton.disabled = !enabled;
  3340. }
  3341. shown() {
  3342. this.#editor._reportTelemetry({
  3343. action: "pdfjs.image.alt_text.image_status_label_displayed",
  3344. data: {
  3345. label: this.#label
  3346. }
  3347. });
  3348. }
  3349. destroy() {
  3350. this.#altTextButton?.remove();
  3351. this.#altTextButton = null;
  3352. this.#altTextButtonLabel = null;
  3353. this.#altTextTooltip = null;
  3354. this.#badge?.remove();
  3355. this.#badge = null;
  3356. }
  3357. async #setState() {
  3358. const button = this.#altTextButton;
  3359. if (!button) {
  3360. return;
  3361. }
  3362. if (this.#useNewAltTextFlow) {
  3363. button.classList.toggle("done", !!this.#altText);
  3364. button.setAttribute("data-l10n-id", AltText.#l10nNewButton[this.#label]);
  3365. this.#altTextButtonLabel?.setAttribute("data-l10n-id", AltText.#l10nNewButton[`${this.#label}-label`]);
  3366. if (!this.#altText) {
  3367. this.#altTextTooltip?.remove();
  3368. return;
  3369. }
  3370. } else {
  3371. if (!this.#altText && !this.#altTextDecorative) {
  3372. button.classList.remove("done");
  3373. this.#altTextTooltip?.remove();
  3374. return;
  3375. }
  3376. button.classList.add("done");
  3377. button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button");
  3378. }
  3379. let tooltip = this.#altTextTooltip;
  3380. if (!tooltip) {
  3381. this.#altTextTooltip = tooltip = document.createElement("span");
  3382. tooltip.className = "tooltip";
  3383. tooltip.setAttribute("role", "tooltip");
  3384. tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
  3385. const DELAY_TO_SHOW_TOOLTIP = 100;
  3386. const signal = this.#editor._uiManager._signal;
  3387. signal.addEventListener("abort", () => {
  3388. clearTimeout(this.#altTextTooltipTimeout);
  3389. this.#altTextTooltipTimeout = null;
  3390. }, {
  3391. once: true
  3392. });
  3393. button.addEventListener("mouseenter", () => {
  3394. this.#altTextTooltipTimeout = setTimeout(() => {
  3395. this.#altTextTooltipTimeout = null;
  3396. this.#altTextTooltip.classList.add("show");
  3397. this.#editor._reportTelemetry({
  3398. action: "alt_text_tooltip"
  3399. });
  3400. }, DELAY_TO_SHOW_TOOLTIP);
  3401. }, {
  3402. signal
  3403. });
  3404. button.addEventListener("mouseleave", () => {
  3405. if (this.#altTextTooltipTimeout) {
  3406. clearTimeout(this.#altTextTooltipTimeout);
  3407. this.#altTextTooltipTimeout = null;
  3408. }
  3409. this.#altTextTooltip?.classList.remove("show");
  3410. }, {
  3411. signal
  3412. });
  3413. }
  3414. if (this.#altTextDecorative) {
  3415. tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip");
  3416. } else {
  3417. tooltip.removeAttribute("data-l10n-id");
  3418. tooltip.textContent = this.#altText;
  3419. }
  3420. if (!tooltip.parentNode) {
  3421. button.append(tooltip);
  3422. }
  3423. const element = this.#editor.getImageForAltText();
  3424. element?.setAttribute("aria-describedby", tooltip.id);
  3425. }
  3426. }
  3427. ;// ./src/display/editor/editor.js
  3428. class AnnotationEditor {
  3429. #accessibilityData = null;
  3430. #allResizerDivs = null;
  3431. #altText = null;
  3432. #disabled = false;
  3433. #keepAspectRatio = false;
  3434. #resizersDiv = null;
  3435. #savedDimensions = null;
  3436. #focusAC = null;
  3437. #focusedResizerName = "";
  3438. #hasBeenClicked = false;
  3439. #initialPosition = null;
  3440. #isEditing = false;
  3441. #isInEditMode = false;
  3442. #isResizerEnabledForKeyboard = false;
  3443. #moveInDOMTimeout = null;
  3444. #prevDragX = 0;
  3445. #prevDragY = 0;
  3446. #telemetryTimeouts = null;
  3447. _editToolbar = null;
  3448. _initialOptions = Object.create(null);
  3449. _initialData = null;
  3450. _isVisible = true;
  3451. _uiManager = null;
  3452. _focusEventsAllowed = true;
  3453. static _l10n = null;
  3454. static _l10nResizer = null;
  3455. #isDraggable = false;
  3456. #zIndex = AnnotationEditor._zIndex++;
  3457. static _borderLineWidth = -1;
  3458. static _colorManager = new ColorManager();
  3459. static _zIndex = 1;
  3460. static _telemetryTimeout = 1000;
  3461. static get _resizerKeyboardManager() {
  3462. const resize = AnnotationEditor.prototype._resizeWithKeyboard;
  3463. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  3464. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  3465. return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
  3466. args: [-small, 0]
  3467. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
  3468. args: [-big, 0]
  3469. }], [["ArrowRight", "mac+ArrowRight"], resize, {
  3470. args: [small, 0]
  3471. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
  3472. args: [big, 0]
  3473. }], [["ArrowUp", "mac+ArrowUp"], resize, {
  3474. args: [0, -small]
  3475. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
  3476. args: [0, -big]
  3477. }], [["ArrowDown", "mac+ArrowDown"], resize, {
  3478. args: [0, small]
  3479. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
  3480. args: [0, big]
  3481. }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]]));
  3482. }
  3483. constructor(parameters) {
  3484. this.parent = parameters.parent;
  3485. this.id = parameters.id;
  3486. this.width = this.height = null;
  3487. this.pageIndex = parameters.parent.pageIndex;
  3488. this.name = parameters.name;
  3489. this.div = null;
  3490. this._uiManager = parameters.uiManager;
  3491. this.annotationElementId = null;
  3492. this._willKeepAspectRatio = false;
  3493. this._initialOptions.isCentered = parameters.isCentered;
  3494. this._structTreeParentId = null;
  3495. const {
  3496. rotation,
  3497. rawDims: {
  3498. pageWidth,
  3499. pageHeight,
  3500. pageX,
  3501. pageY
  3502. }
  3503. } = this.parent.viewport;
  3504. this.rotation = rotation;
  3505. this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
  3506. this.pageDimensions = [pageWidth, pageHeight];
  3507. this.pageTranslation = [pageX, pageY];
  3508. const [width, height] = this.parentDimensions;
  3509. this.x = parameters.x / width;
  3510. this.y = parameters.y / height;
  3511. this.isAttachedToDOM = false;
  3512. this.deleted = false;
  3513. }
  3514. get editorType() {
  3515. return Object.getPrototypeOf(this).constructor._type;
  3516. }
  3517. static get _defaultLineColor() {
  3518. return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  3519. }
  3520. static deleteAnnotationElement(editor) {
  3521. const fakeEditor = new FakeEditor({
  3522. id: editor.parent.getNextId(),
  3523. parent: editor.parent,
  3524. uiManager: editor._uiManager
  3525. });
  3526. fakeEditor.annotationElementId = editor.annotationElementId;
  3527. fakeEditor.deleted = true;
  3528. fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
  3529. }
  3530. static initialize(l10n, _uiManager) {
  3531. AnnotationEditor._l10n ??= l10n;
  3532. AnnotationEditor._l10nResizer ||= Object.freeze({
  3533. topLeft: "pdfjs-editor-resizer-top-left",
  3534. topMiddle: "pdfjs-editor-resizer-top-middle",
  3535. topRight: "pdfjs-editor-resizer-top-right",
  3536. middleRight: "pdfjs-editor-resizer-middle-right",
  3537. bottomRight: "pdfjs-editor-resizer-bottom-right",
  3538. bottomMiddle: "pdfjs-editor-resizer-bottom-middle",
  3539. bottomLeft: "pdfjs-editor-resizer-bottom-left",
  3540. middleLeft: "pdfjs-editor-resizer-middle-left"
  3541. });
  3542. if (AnnotationEditor._borderLineWidth !== -1) {
  3543. return;
  3544. }
  3545. const style = getComputedStyle(document.documentElement);
  3546. AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
  3547. }
  3548. static updateDefaultParams(_type, _value) {}
  3549. static get defaultPropertiesToUpdate() {
  3550. return [];
  3551. }
  3552. static isHandlingMimeForPasting(mime) {
  3553. return false;
  3554. }
  3555. static paste(item, parent) {
  3556. unreachable("Not implemented");
  3557. }
  3558. get propertiesToUpdate() {
  3559. return [];
  3560. }
  3561. get _isDraggable() {
  3562. return this.#isDraggable;
  3563. }
  3564. set _isDraggable(value) {
  3565. this.#isDraggable = value;
  3566. this.div?.classList.toggle("draggable", value);
  3567. }
  3568. get isEnterHandled() {
  3569. return true;
  3570. }
  3571. center() {
  3572. const [pageWidth, pageHeight] = this.pageDimensions;
  3573. switch (this.parentRotation) {
  3574. case 90:
  3575. this.x -= this.height * pageHeight / (pageWidth * 2);
  3576. this.y += this.width * pageWidth / (pageHeight * 2);
  3577. break;
  3578. case 180:
  3579. this.x += this.width / 2;
  3580. this.y += this.height / 2;
  3581. break;
  3582. case 270:
  3583. this.x += this.height * pageHeight / (pageWidth * 2);
  3584. this.y -= this.width * pageWidth / (pageHeight * 2);
  3585. break;
  3586. default:
  3587. this.x -= this.width / 2;
  3588. this.y -= this.height / 2;
  3589. break;
  3590. }
  3591. this.fixAndSetPosition();
  3592. }
  3593. addCommands(params) {
  3594. this._uiManager.addCommands(params);
  3595. }
  3596. get currentLayer() {
  3597. return this._uiManager.currentLayer;
  3598. }
  3599. setInBackground() {
  3600. this.div.style.zIndex = 0;
  3601. }
  3602. setInForeground() {
  3603. this.div.style.zIndex = this.#zIndex;
  3604. }
  3605. setParent(parent) {
  3606. if (parent !== null) {
  3607. this.pageIndex = parent.pageIndex;
  3608. this.pageDimensions = parent.pageDimensions;
  3609. } else {
  3610. this.#stopResizing();
  3611. }
  3612. this.parent = parent;
  3613. }
  3614. focusin(event) {
  3615. if (!this._focusEventsAllowed) {
  3616. return;
  3617. }
  3618. if (!this.#hasBeenClicked) {
  3619. this.parent.setSelected(this);
  3620. } else {
  3621. this.#hasBeenClicked = false;
  3622. }
  3623. }
  3624. focusout(event) {
  3625. if (!this._focusEventsAllowed) {
  3626. return;
  3627. }
  3628. if (!this.isAttachedToDOM) {
  3629. return;
  3630. }
  3631. const target = event.relatedTarget;
  3632. if (target?.closest(`#${this.id}`)) {
  3633. return;
  3634. }
  3635. event.preventDefault();
  3636. if (!this.parent?.isMultipleSelection) {
  3637. this.commitOrRemove();
  3638. }
  3639. }
  3640. commitOrRemove() {
  3641. if (this.isEmpty()) {
  3642. this.remove();
  3643. } else {
  3644. this.commit();
  3645. }
  3646. }
  3647. commit() {
  3648. this.addToAnnotationStorage();
  3649. }
  3650. addToAnnotationStorage() {
  3651. this._uiManager.addToAnnotationStorage(this);
  3652. }
  3653. setAt(x, y, tx, ty) {
  3654. const [width, height] = this.parentDimensions;
  3655. [tx, ty] = this.screenToPageTranslation(tx, ty);
  3656. this.x = (x + tx) / width;
  3657. this.y = (y + ty) / height;
  3658. this.fixAndSetPosition();
  3659. }
  3660. #translate([width, height], x, y) {
  3661. [x, y] = this.screenToPageTranslation(x, y);
  3662. this.x += x / width;
  3663. this.y += y / height;
  3664. this.fixAndSetPosition();
  3665. }
  3666. translate(x, y) {
  3667. this.#translate(this.parentDimensions, x, y);
  3668. }
  3669. translateInPage(x, y) {
  3670. this.#initialPosition ||= [this.x, this.y];
  3671. this.#translate(this.pageDimensions, x, y);
  3672. this.div.scrollIntoView({
  3673. block: "nearest"
  3674. });
  3675. }
  3676. drag(tx, ty) {
  3677. this.#initialPosition ||= [this.x, this.y];
  3678. const [parentWidth, parentHeight] = this.parentDimensions;
  3679. this.x += tx / parentWidth;
  3680. this.y += ty / parentHeight;
  3681. if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
  3682. const {
  3683. x,
  3684. y
  3685. } = this.div.getBoundingClientRect();
  3686. if (this.parent.findNewParent(this, x, y)) {
  3687. this.x -= Math.floor(this.x);
  3688. this.y -= Math.floor(this.y);
  3689. }
  3690. }
  3691. let {
  3692. x,
  3693. y
  3694. } = this;
  3695. const [bx, by] = this.getBaseTranslation();
  3696. x += bx;
  3697. y += by;
  3698. this.div.style.left = `${(100 * x).toFixed(2)}%`;
  3699. this.div.style.top = `${(100 * y).toFixed(2)}%`;
  3700. this.div.scrollIntoView({
  3701. block: "nearest"
  3702. });
  3703. }
  3704. get _hasBeenMoved() {
  3705. return !!this.#initialPosition && (this.#initialPosition[0] !== this.x || this.#initialPosition[1] !== this.y);
  3706. }
  3707. getBaseTranslation() {
  3708. const [parentWidth, parentHeight] = this.parentDimensions;
  3709. const {
  3710. _borderLineWidth
  3711. } = AnnotationEditor;
  3712. const x = _borderLineWidth / parentWidth;
  3713. const y = _borderLineWidth / parentHeight;
  3714. switch (this.rotation) {
  3715. case 90:
  3716. return [-x, y];
  3717. case 180:
  3718. return [x, y];
  3719. case 270:
  3720. return [x, -y];
  3721. default:
  3722. return [-x, -y];
  3723. }
  3724. }
  3725. get _mustFixPosition() {
  3726. return true;
  3727. }
  3728. fixAndSetPosition(rotation = this.rotation) {
  3729. const [pageWidth, pageHeight] = this.pageDimensions;
  3730. let {
  3731. x,
  3732. y,
  3733. width,
  3734. height
  3735. } = this;
  3736. width *= pageWidth;
  3737. height *= pageHeight;
  3738. x *= pageWidth;
  3739. y *= pageHeight;
  3740. if (this._mustFixPosition) {
  3741. switch (rotation) {
  3742. case 0:
  3743. x = Math.max(0, Math.min(pageWidth - width, x));
  3744. y = Math.max(0, Math.min(pageHeight - height, y));
  3745. break;
  3746. case 90:
  3747. x = Math.max(0, Math.min(pageWidth - height, x));
  3748. y = Math.min(pageHeight, Math.max(width, y));
  3749. break;
  3750. case 180:
  3751. x = Math.min(pageWidth, Math.max(width, x));
  3752. y = Math.min(pageHeight, Math.max(height, y));
  3753. break;
  3754. case 270:
  3755. x = Math.min(pageWidth, Math.max(height, x));
  3756. y = Math.max(0, Math.min(pageHeight - width, y));
  3757. break;
  3758. }
  3759. }
  3760. this.x = x /= pageWidth;
  3761. this.y = y /= pageHeight;
  3762. const [bx, by] = this.getBaseTranslation();
  3763. x += bx;
  3764. y += by;
  3765. const {
  3766. style
  3767. } = this.div;
  3768. style.left = `${(100 * x).toFixed(2)}%`;
  3769. style.top = `${(100 * y).toFixed(2)}%`;
  3770. this.moveInDOM();
  3771. }
  3772. static #rotatePoint(x, y, angle) {
  3773. switch (angle) {
  3774. case 90:
  3775. return [y, -x];
  3776. case 180:
  3777. return [-x, -y];
  3778. case 270:
  3779. return [-y, x];
  3780. default:
  3781. return [x, y];
  3782. }
  3783. }
  3784. screenToPageTranslation(x, y) {
  3785. return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);
  3786. }
  3787. pageTranslationToScreen(x, y) {
  3788. return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);
  3789. }
  3790. #getRotationMatrix(rotation) {
  3791. switch (rotation) {
  3792. case 90:
  3793. {
  3794. const [pageWidth, pageHeight] = this.pageDimensions;
  3795. return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
  3796. }
  3797. case 180:
  3798. return [-1, 0, 0, -1];
  3799. case 270:
  3800. {
  3801. const [pageWidth, pageHeight] = this.pageDimensions;
  3802. return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
  3803. }
  3804. default:
  3805. return [1, 0, 0, 1];
  3806. }
  3807. }
  3808. get parentScale() {
  3809. return this._uiManager.viewParameters.realScale;
  3810. }
  3811. get parentRotation() {
  3812. return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
  3813. }
  3814. get parentDimensions() {
  3815. const {
  3816. parentScale,
  3817. pageDimensions: [pageWidth, pageHeight]
  3818. } = this;
  3819. return [pageWidth * parentScale, pageHeight * parentScale];
  3820. }
  3821. setDims(width, height) {
  3822. const [parentWidth, parentHeight] = this.parentDimensions;
  3823. this.div.style.width = `${(100 * width / parentWidth).toFixed(2)}%`;
  3824. if (!this.#keepAspectRatio) {
  3825. this.div.style.height = `${(100 * height / parentHeight).toFixed(2)}%`;
  3826. }
  3827. }
  3828. fixDims() {
  3829. const {
  3830. style
  3831. } = this.div;
  3832. const {
  3833. height,
  3834. width
  3835. } = style;
  3836. const widthPercent = width.endsWith("%");
  3837. const heightPercent = !this.#keepAspectRatio && height.endsWith("%");
  3838. if (widthPercent && heightPercent) {
  3839. return;
  3840. }
  3841. const [parentWidth, parentHeight] = this.parentDimensions;
  3842. if (!widthPercent) {
  3843. style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`;
  3844. }
  3845. if (!this.#keepAspectRatio && !heightPercent) {
  3846. style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`;
  3847. }
  3848. }
  3849. getInitialTranslation() {
  3850. return [0, 0];
  3851. }
  3852. #createResizers() {
  3853. if (this.#resizersDiv) {
  3854. return;
  3855. }
  3856. this.#resizersDiv = document.createElement("div");
  3857. this.#resizersDiv.classList.add("resizers");
  3858. const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
  3859. const signal = this._uiManager._signal;
  3860. for (const name of classes) {
  3861. const div = document.createElement("div");
  3862. this.#resizersDiv.append(div);
  3863. div.classList.add("resizer", name);
  3864. div.setAttribute("data-resizer-name", name);
  3865. div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {
  3866. signal
  3867. });
  3868. div.addEventListener("contextmenu", noContextMenu, {
  3869. signal
  3870. });
  3871. div.tabIndex = -1;
  3872. }
  3873. this.div.prepend(this.#resizersDiv);
  3874. }
  3875. #resizerPointerdown(name, event) {
  3876. event.preventDefault();
  3877. const {
  3878. isMac
  3879. } = util_FeatureTest.platform;
  3880. if (event.button !== 0 || event.ctrlKey && isMac) {
  3881. return;
  3882. }
  3883. this.#altText?.toggle(false);
  3884. const savedDraggable = this._isDraggable;
  3885. this._isDraggable = false;
  3886. const ac = new AbortController();
  3887. const signal = this._uiManager.combinedSignal(ac);
  3888. this.parent.togglePointerEvents(false);
  3889. window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {
  3890. passive: true,
  3891. capture: true,
  3892. signal
  3893. });
  3894. window.addEventListener("contextmenu", noContextMenu, {
  3895. signal
  3896. });
  3897. const savedX = this.x;
  3898. const savedY = this.y;
  3899. const savedWidth = this.width;
  3900. const savedHeight = this.height;
  3901. const savedParentCursor = this.parent.div.style.cursor;
  3902. const savedCursor = this.div.style.cursor;
  3903. this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
  3904. const pointerUpCallback = () => {
  3905. ac.abort();
  3906. this.parent.togglePointerEvents(true);
  3907. this.#altText?.toggle(true);
  3908. this._isDraggable = savedDraggable;
  3909. this.parent.div.style.cursor = savedParentCursor;
  3910. this.div.style.cursor = savedCursor;
  3911. this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
  3912. };
  3913. window.addEventListener("pointerup", pointerUpCallback, {
  3914. signal
  3915. });
  3916. window.addEventListener("blur", pointerUpCallback, {
  3917. signal
  3918. });
  3919. }
  3920. #addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight) {
  3921. const newX = this.x;
  3922. const newY = this.y;
  3923. const newWidth = this.width;
  3924. const newHeight = this.height;
  3925. if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
  3926. return;
  3927. }
  3928. this.addCommands({
  3929. cmd: () => {
  3930. this.width = newWidth;
  3931. this.height = newHeight;
  3932. this.x = newX;
  3933. this.y = newY;
  3934. const [parentWidth, parentHeight] = this.parentDimensions;
  3935. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  3936. this.fixAndSetPosition();
  3937. },
  3938. undo: () => {
  3939. this.width = savedWidth;
  3940. this.height = savedHeight;
  3941. this.x = savedX;
  3942. this.y = savedY;
  3943. const [parentWidth, parentHeight] = this.parentDimensions;
  3944. this.setDims(parentWidth * savedWidth, parentHeight * savedHeight);
  3945. this.fixAndSetPosition();
  3946. },
  3947. mustExec: true
  3948. });
  3949. }
  3950. #resizerPointermove(name, event) {
  3951. const [parentWidth, parentHeight] = this.parentDimensions;
  3952. const savedX = this.x;
  3953. const savedY = this.y;
  3954. const savedWidth = this.width;
  3955. const savedHeight = this.height;
  3956. const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
  3957. const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
  3958. const round = x => Math.round(x * 10000) / 10000;
  3959. const rotationMatrix = this.#getRotationMatrix(this.rotation);
  3960. const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
  3961. const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
  3962. const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];
  3963. let getPoint;
  3964. let getOpposite;
  3965. let isDiagonal = false;
  3966. let isHorizontal = false;
  3967. switch (name) {
  3968. case "topLeft":
  3969. isDiagonal = true;
  3970. getPoint = (w, h) => [0, 0];
  3971. getOpposite = (w, h) => [w, h];
  3972. break;
  3973. case "topMiddle":
  3974. getPoint = (w, h) => [w / 2, 0];
  3975. getOpposite = (w, h) => [w / 2, h];
  3976. break;
  3977. case "topRight":
  3978. isDiagonal = true;
  3979. getPoint = (w, h) => [w, 0];
  3980. getOpposite = (w, h) => [0, h];
  3981. break;
  3982. case "middleRight":
  3983. isHorizontal = true;
  3984. getPoint = (w, h) => [w, h / 2];
  3985. getOpposite = (w, h) => [0, h / 2];
  3986. break;
  3987. case "bottomRight":
  3988. isDiagonal = true;
  3989. getPoint = (w, h) => [w, h];
  3990. getOpposite = (w, h) => [0, 0];
  3991. break;
  3992. case "bottomMiddle":
  3993. getPoint = (w, h) => [w / 2, h];
  3994. getOpposite = (w, h) => [w / 2, 0];
  3995. break;
  3996. case "bottomLeft":
  3997. isDiagonal = true;
  3998. getPoint = (w, h) => [0, h];
  3999. getOpposite = (w, h) => [w, 0];
  4000. break;
  4001. case "middleLeft":
  4002. isHorizontal = true;
  4003. getPoint = (w, h) => [0, h / 2];
  4004. getOpposite = (w, h) => [w, h / 2];
  4005. break;
  4006. }
  4007. const point = getPoint(savedWidth, savedHeight);
  4008. const oppositePoint = getOpposite(savedWidth, savedHeight);
  4009. let transfOppositePoint = transf(...oppositePoint);
  4010. const oppositeX = round(savedX + transfOppositePoint[0]);
  4011. const oppositeY = round(savedY + transfOppositePoint[1]);
  4012. let ratioX = 1;
  4013. let ratioY = 1;
  4014. let [deltaX, deltaY] = this.screenToPageTranslation(event.movementX, event.movementY);
  4015. [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
  4016. if (isDiagonal) {
  4017. const oldDiag = Math.hypot(savedWidth, savedHeight);
  4018. 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);
  4019. } else if (isHorizontal) {
  4020. ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth;
  4021. } else {
  4022. ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight;
  4023. }
  4024. const newWidth = round(savedWidth * ratioX);
  4025. const newHeight = round(savedHeight * ratioY);
  4026. transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
  4027. const newX = oppositeX - transfOppositePoint[0];
  4028. const newY = oppositeY - transfOppositePoint[1];
  4029. this.width = newWidth;
  4030. this.height = newHeight;
  4031. this.x = newX;
  4032. this.y = newY;
  4033. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  4034. this.fixAndSetPosition();
  4035. }
  4036. altTextFinish() {
  4037. this.#altText?.finish();
  4038. }
  4039. async addEditToolbar() {
  4040. if (this._editToolbar || this.#isInEditMode) {
  4041. return this._editToolbar;
  4042. }
  4043. this._editToolbar = new EditorToolbar(this);
  4044. this.div.append(this._editToolbar.render());
  4045. if (this.#altText) {
  4046. await this._editToolbar.addAltText(this.#altText);
  4047. }
  4048. return this._editToolbar;
  4049. }
  4050. removeEditToolbar() {
  4051. if (!this._editToolbar) {
  4052. return;
  4053. }
  4054. this._editToolbar.remove();
  4055. this._editToolbar = null;
  4056. this.#altText?.destroy();
  4057. }
  4058. addContainer(container) {
  4059. const editToolbarDiv = this._editToolbar?.div;
  4060. if (editToolbarDiv) {
  4061. editToolbarDiv.before(container);
  4062. } else {
  4063. this.div.append(container);
  4064. }
  4065. }
  4066. getClientDimensions() {
  4067. return this.div.getBoundingClientRect();
  4068. }
  4069. async addAltTextButton() {
  4070. if (this.#altText) {
  4071. return;
  4072. }
  4073. AltText.initialize(AnnotationEditor._l10n);
  4074. this.#altText = new AltText(this);
  4075. if (this.#accessibilityData) {
  4076. this.#altText.data = this.#accessibilityData;
  4077. this.#accessibilityData = null;
  4078. }
  4079. await this.addEditToolbar();
  4080. }
  4081. get altTextData() {
  4082. return this.#altText?.data;
  4083. }
  4084. set altTextData(data) {
  4085. if (!this.#altText) {
  4086. return;
  4087. }
  4088. this.#altText.data = data;
  4089. }
  4090. get guessedAltText() {
  4091. return this.#altText?.guessedText;
  4092. }
  4093. async setGuessedAltText(text) {
  4094. await this.#altText?.setGuessedText(text);
  4095. }
  4096. serializeAltText(isForCopying) {
  4097. return this.#altText?.serialize(isForCopying);
  4098. }
  4099. hasAltText() {
  4100. return !!this.#altText && !this.#altText.isEmpty();
  4101. }
  4102. hasAltTextData() {
  4103. return this.#altText?.hasData() ?? false;
  4104. }
  4105. render() {
  4106. this.div = document.createElement("div");
  4107. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  4108. this.div.className = this.name;
  4109. this.div.setAttribute("id", this.id);
  4110. this.div.tabIndex = this.#disabled ? -1 : 0;
  4111. if (!this._isVisible) {
  4112. this.div.classList.add("hidden");
  4113. }
  4114. this.setInForeground();
  4115. this.#addFocusListeners();
  4116. const [parentWidth, parentHeight] = this.parentDimensions;
  4117. if (this.parentRotation % 180 !== 0) {
  4118. this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
  4119. this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
  4120. }
  4121. const [tx, ty] = this.getInitialTranslation();
  4122. this.translate(tx, ty);
  4123. bindEvents(this, this.div, ["pointerdown"]);
  4124. return this.div;
  4125. }
  4126. pointerdown(event) {
  4127. const {
  4128. isMac
  4129. } = util_FeatureTest.platform;
  4130. if (event.button !== 0 || event.ctrlKey && isMac) {
  4131. event.preventDefault();
  4132. return;
  4133. }
  4134. this.#hasBeenClicked = true;
  4135. if (this._isDraggable) {
  4136. this.#setUpDragSession(event);
  4137. return;
  4138. }
  4139. this.#selectOnPointerEvent(event);
  4140. }
  4141. get isSelected() {
  4142. return this._uiManager.isSelected(this);
  4143. }
  4144. #selectOnPointerEvent(event) {
  4145. const {
  4146. isMac
  4147. } = util_FeatureTest.platform;
  4148. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  4149. this.parent.toggleSelected(this);
  4150. } else {
  4151. this.parent.setSelected(this);
  4152. }
  4153. }
  4154. #setUpDragSession(event) {
  4155. const {
  4156. isSelected
  4157. } = this;
  4158. this._uiManager.setUpDragSession();
  4159. const ac = new AbortController();
  4160. const signal = this._uiManager.combinedSignal(ac);
  4161. if (isSelected) {
  4162. this.div.classList.add("moving");
  4163. this.#prevDragX = event.clientX;
  4164. this.#prevDragY = event.clientY;
  4165. const pointerMoveCallback = e => {
  4166. const {
  4167. clientX: x,
  4168. clientY: y
  4169. } = e;
  4170. const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY);
  4171. this.#prevDragX = x;
  4172. this.#prevDragY = y;
  4173. this._uiManager.dragSelectedEditors(tx, ty);
  4174. };
  4175. window.addEventListener("pointermove", pointerMoveCallback, {
  4176. passive: true,
  4177. capture: true,
  4178. signal
  4179. });
  4180. }
  4181. const pointerUpCallback = () => {
  4182. ac.abort();
  4183. if (isSelected) {
  4184. this.div.classList.remove("moving");
  4185. }
  4186. this.#hasBeenClicked = false;
  4187. if (!this._uiManager.endDragSession()) {
  4188. this.#selectOnPointerEvent(event);
  4189. }
  4190. };
  4191. window.addEventListener("pointerup", pointerUpCallback, {
  4192. signal
  4193. });
  4194. window.addEventListener("blur", pointerUpCallback, {
  4195. signal
  4196. });
  4197. }
  4198. moveInDOM() {
  4199. if (this.#moveInDOMTimeout) {
  4200. clearTimeout(this.#moveInDOMTimeout);
  4201. }
  4202. this.#moveInDOMTimeout = setTimeout(() => {
  4203. this.#moveInDOMTimeout = null;
  4204. this.parent?.moveEditorInDOM(this);
  4205. }, 0);
  4206. }
  4207. _setParentAndPosition(parent, x, y) {
  4208. parent.changeParent(this);
  4209. this.x = x;
  4210. this.y = y;
  4211. this.fixAndSetPosition();
  4212. }
  4213. getRect(tx, ty, rotation = this.rotation) {
  4214. const scale = this.parentScale;
  4215. const [pageWidth, pageHeight] = this.pageDimensions;
  4216. const [pageX, pageY] = this.pageTranslation;
  4217. const shiftX = tx / scale;
  4218. const shiftY = ty / scale;
  4219. const x = this.x * pageWidth;
  4220. const y = this.y * pageHeight;
  4221. const width = this.width * pageWidth;
  4222. const height = this.height * pageHeight;
  4223. switch (rotation) {
  4224. case 0:
  4225. return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
  4226. case 90:
  4227. return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
  4228. case 180:
  4229. return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
  4230. case 270:
  4231. return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
  4232. default:
  4233. throw new Error("Invalid rotation");
  4234. }
  4235. }
  4236. getRectInCurrentCoords(rect, pageHeight) {
  4237. const [x1, y1, x2, y2] = rect;
  4238. const width = x2 - x1;
  4239. const height = y2 - y1;
  4240. switch (this.rotation) {
  4241. case 0:
  4242. return [x1, pageHeight - y2, width, height];
  4243. case 90:
  4244. return [x1, pageHeight - y1, height, width];
  4245. case 180:
  4246. return [x2, pageHeight - y1, width, height];
  4247. case 270:
  4248. return [x2, pageHeight - y2, height, width];
  4249. default:
  4250. throw new Error("Invalid rotation");
  4251. }
  4252. }
  4253. onceAdded() {}
  4254. isEmpty() {
  4255. return false;
  4256. }
  4257. enableEditMode() {
  4258. this.#isInEditMode = true;
  4259. }
  4260. disableEditMode() {
  4261. this.#isInEditMode = false;
  4262. }
  4263. isInEditMode() {
  4264. return this.#isInEditMode;
  4265. }
  4266. shouldGetKeyboardEvents() {
  4267. return this.#isResizerEnabledForKeyboard;
  4268. }
  4269. needsToBeRebuilt() {
  4270. return this.div && !this.isAttachedToDOM;
  4271. }
  4272. #addFocusListeners() {
  4273. if (this.#focusAC || !this.div) {
  4274. return;
  4275. }
  4276. this.#focusAC = new AbortController();
  4277. const signal = this._uiManager.combinedSignal(this.#focusAC);
  4278. this.div.addEventListener("focusin", this.focusin.bind(this), {
  4279. signal
  4280. });
  4281. this.div.addEventListener("focusout", this.focusout.bind(this), {
  4282. signal
  4283. });
  4284. }
  4285. rebuild() {
  4286. this.#addFocusListeners();
  4287. }
  4288. rotate(_angle) {}
  4289. serializeDeleted() {
  4290. return {
  4291. id: this.annotationElementId,
  4292. deleted: true,
  4293. pageIndex: this.pageIndex,
  4294. popupRef: this._initialData?.popupRef || ""
  4295. };
  4296. }
  4297. serialize(isForCopying = false, context = null) {
  4298. unreachable("An editor must be serializable");
  4299. }
  4300. static async deserialize(data, parent, uiManager) {
  4301. const editor = new this.prototype.constructor({
  4302. parent,
  4303. id: parent.getNextId(),
  4304. uiManager
  4305. });
  4306. editor.rotation = data.rotation;
  4307. editor.#accessibilityData = data.accessibilityData;
  4308. const [pageWidth, pageHeight] = editor.pageDimensions;
  4309. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  4310. editor.x = x / pageWidth;
  4311. editor.y = y / pageHeight;
  4312. editor.width = width / pageWidth;
  4313. editor.height = height / pageHeight;
  4314. return editor;
  4315. }
  4316. get hasBeenModified() {
  4317. return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
  4318. }
  4319. remove() {
  4320. this.#focusAC?.abort();
  4321. this.#focusAC = null;
  4322. if (!this.isEmpty()) {
  4323. this.commit();
  4324. }
  4325. if (this.parent) {
  4326. this.parent.remove(this);
  4327. } else {
  4328. this._uiManager.removeEditor(this);
  4329. }
  4330. if (this.#moveInDOMTimeout) {
  4331. clearTimeout(this.#moveInDOMTimeout);
  4332. this.#moveInDOMTimeout = null;
  4333. }
  4334. this.#stopResizing();
  4335. this.removeEditToolbar();
  4336. if (this.#telemetryTimeouts) {
  4337. for (const timeout of this.#telemetryTimeouts.values()) {
  4338. clearTimeout(timeout);
  4339. }
  4340. this.#telemetryTimeouts = null;
  4341. }
  4342. this.parent = null;
  4343. }
  4344. get isResizable() {
  4345. return false;
  4346. }
  4347. makeResizable() {
  4348. if (this.isResizable) {
  4349. this.#createResizers();
  4350. this.#resizersDiv.classList.remove("hidden");
  4351. bindEvents(this, this.div, ["keydown"]);
  4352. }
  4353. }
  4354. get toolbarPosition() {
  4355. return null;
  4356. }
  4357. keydown(event) {
  4358. if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
  4359. return;
  4360. }
  4361. this._uiManager.setSelected(this);
  4362. this.#savedDimensions = {
  4363. savedX: this.x,
  4364. savedY: this.y,
  4365. savedWidth: this.width,
  4366. savedHeight: this.height
  4367. };
  4368. const children = this.#resizersDiv.children;
  4369. if (!this.#allResizerDivs) {
  4370. this.#allResizerDivs = Array.from(children);
  4371. const boundResizerKeydown = this.#resizerKeydown.bind(this);
  4372. const boundResizerBlur = this.#resizerBlur.bind(this);
  4373. const signal = this._uiManager._signal;
  4374. for (const div of this.#allResizerDivs) {
  4375. const name = div.getAttribute("data-resizer-name");
  4376. div.setAttribute("role", "spinbutton");
  4377. div.addEventListener("keydown", boundResizerKeydown, {
  4378. signal
  4379. });
  4380. div.addEventListener("blur", boundResizerBlur, {
  4381. signal
  4382. });
  4383. div.addEventListener("focus", this.#resizerFocus.bind(this, name), {
  4384. signal
  4385. });
  4386. div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  4387. }
  4388. }
  4389. const first = this.#allResizerDivs[0];
  4390. let firstPosition = 0;
  4391. for (const div of children) {
  4392. if (div === first) {
  4393. break;
  4394. }
  4395. firstPosition++;
  4396. }
  4397. const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
  4398. if (nextFirstPosition !== firstPosition) {
  4399. if (nextFirstPosition < firstPosition) {
  4400. for (let i = 0; i < firstPosition - nextFirstPosition; i++) {
  4401. this.#resizersDiv.append(this.#resizersDiv.firstChild);
  4402. }
  4403. } else if (nextFirstPosition > firstPosition) {
  4404. for (let i = 0; i < nextFirstPosition - firstPosition; i++) {
  4405. this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
  4406. }
  4407. }
  4408. let i = 0;
  4409. for (const child of children) {
  4410. const div = this.#allResizerDivs[i++];
  4411. const name = div.getAttribute("data-resizer-name");
  4412. child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  4413. }
  4414. }
  4415. this.#setResizerTabIndex(0);
  4416. this.#isResizerEnabledForKeyboard = true;
  4417. this.#resizersDiv.firstChild.focus({
  4418. focusVisible: true
  4419. });
  4420. event.preventDefault();
  4421. event.stopImmediatePropagation();
  4422. }
  4423. #resizerKeydown(event) {
  4424. AnnotationEditor._resizerKeyboardManager.exec(this, event);
  4425. }
  4426. #resizerBlur(event) {
  4427. if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
  4428. this.#stopResizing();
  4429. }
  4430. }
  4431. #resizerFocus(name) {
  4432. this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
  4433. }
  4434. #setResizerTabIndex(value) {
  4435. if (!this.#allResizerDivs) {
  4436. return;
  4437. }
  4438. for (const div of this.#allResizerDivs) {
  4439. div.tabIndex = value;
  4440. }
  4441. }
  4442. _resizeWithKeyboard(x, y) {
  4443. if (!this.#isResizerEnabledForKeyboard) {
  4444. return;
  4445. }
  4446. this.#resizerPointermove(this.#focusedResizerName, {
  4447. movementX: x,
  4448. movementY: y
  4449. });
  4450. }
  4451. #stopResizing() {
  4452. this.#isResizerEnabledForKeyboard = false;
  4453. this.#setResizerTabIndex(-1);
  4454. if (this.#savedDimensions) {
  4455. const {
  4456. savedX,
  4457. savedY,
  4458. savedWidth,
  4459. savedHeight
  4460. } = this.#savedDimensions;
  4461. this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
  4462. this.#savedDimensions = null;
  4463. }
  4464. }
  4465. _stopResizingWithKeyboard() {
  4466. this.#stopResizing();
  4467. this.div.focus();
  4468. }
  4469. select() {
  4470. this.makeResizable();
  4471. this.div?.classList.add("selectedEditor");
  4472. if (!this._editToolbar) {
  4473. this.addEditToolbar().then(() => {
  4474. if (this.div?.classList.contains("selectedEditor")) {
  4475. this._editToolbar?.show();
  4476. }
  4477. });
  4478. return;
  4479. }
  4480. this._editToolbar?.show();
  4481. this.#altText?.toggleAltTextBadge(false);
  4482. }
  4483. unselect() {
  4484. this.#resizersDiv?.classList.add("hidden");
  4485. this.div?.classList.remove("selectedEditor");
  4486. if (this.div?.contains(document.activeElement)) {
  4487. this._uiManager.currentLayer.div.focus({
  4488. preventScroll: true
  4489. });
  4490. }
  4491. this._editToolbar?.hide();
  4492. this.#altText?.toggleAltTextBadge(true);
  4493. }
  4494. updateParams(type, value) {}
  4495. disableEditing() {}
  4496. enableEditing() {}
  4497. enterInEditMode() {}
  4498. getImageForAltText() {
  4499. return null;
  4500. }
  4501. get contentDiv() {
  4502. return this.div;
  4503. }
  4504. get isEditing() {
  4505. return this.#isEditing;
  4506. }
  4507. set isEditing(value) {
  4508. this.#isEditing = value;
  4509. if (!this.parent) {
  4510. return;
  4511. }
  4512. if (value) {
  4513. this.parent.setSelected(this);
  4514. this.parent.setActiveEditor(this);
  4515. } else {
  4516. this.parent.setActiveEditor(null);
  4517. }
  4518. }
  4519. setAspectRatio(width, height) {
  4520. this.#keepAspectRatio = true;
  4521. const aspectRatio = width / height;
  4522. const {
  4523. style
  4524. } = this.div;
  4525. style.aspectRatio = aspectRatio;
  4526. style.height = "auto";
  4527. }
  4528. static get MIN_SIZE() {
  4529. return 16;
  4530. }
  4531. static canCreateNewEmptyEditor() {
  4532. return true;
  4533. }
  4534. get telemetryInitialData() {
  4535. return {
  4536. action: "added"
  4537. };
  4538. }
  4539. get telemetryFinalData() {
  4540. return null;
  4541. }
  4542. _reportTelemetry(data, mustWait = false) {
  4543. if (mustWait) {
  4544. this.#telemetryTimeouts ||= new Map();
  4545. const {
  4546. action
  4547. } = data;
  4548. let timeout = this.#telemetryTimeouts.get(action);
  4549. if (timeout) {
  4550. clearTimeout(timeout);
  4551. }
  4552. timeout = setTimeout(() => {
  4553. this._reportTelemetry(data);
  4554. this.#telemetryTimeouts.delete(action);
  4555. if (this.#telemetryTimeouts.size === 0) {
  4556. this.#telemetryTimeouts = null;
  4557. }
  4558. }, AnnotationEditor._telemetryTimeout);
  4559. this.#telemetryTimeouts.set(action, timeout);
  4560. return;
  4561. }
  4562. data.type ||= this.editorType;
  4563. this._uiManager._eventBus.dispatch("reporttelemetry", {
  4564. source: this,
  4565. details: {
  4566. type: "editing",
  4567. data
  4568. }
  4569. });
  4570. }
  4571. show(visible = this._isVisible) {
  4572. this.div.classList.toggle("hidden", !visible);
  4573. this._isVisible = visible;
  4574. }
  4575. enable() {
  4576. if (this.div) {
  4577. this.div.tabIndex = 0;
  4578. }
  4579. this.#disabled = false;
  4580. }
  4581. disable() {
  4582. if (this.div) {
  4583. this.div.tabIndex = -1;
  4584. }
  4585. this.#disabled = true;
  4586. }
  4587. renderAnnotationElement(annotation) {
  4588. let content = annotation.container.querySelector(".annotationContent");
  4589. if (!content) {
  4590. content = document.createElement("div");
  4591. content.classList.add("annotationContent", this.editorType);
  4592. annotation.container.prepend(content);
  4593. } else if (content.nodeName === "CANVAS") {
  4594. const canvas = content;
  4595. content = document.createElement("div");
  4596. content.classList.add("annotationContent", this.editorType);
  4597. canvas.before(content);
  4598. }
  4599. return content;
  4600. }
  4601. resetAnnotationElement(annotation) {
  4602. const {
  4603. firstChild
  4604. } = annotation.container;
  4605. if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
  4606. firstChild.remove();
  4607. }
  4608. }
  4609. }
  4610. class FakeEditor extends AnnotationEditor {
  4611. constructor(params) {
  4612. super(params);
  4613. this.annotationElementId = params.annotationElementId;
  4614. this.deleted = true;
  4615. }
  4616. serialize() {
  4617. return this.serializeDeleted();
  4618. }
  4619. }
  4620. ;// ./src/shared/murmurhash3.js
  4621. const SEED = 0xc3d2e1f0;
  4622. const MASK_HIGH = 0xffff0000;
  4623. const MASK_LOW = 0xffff;
  4624. class MurmurHash3_64 {
  4625. constructor(seed) {
  4626. this.h1 = seed ? seed & 0xffffffff : SEED;
  4627. this.h2 = seed ? seed & 0xffffffff : SEED;
  4628. }
  4629. update(input) {
  4630. let data, length;
  4631. if (typeof input === "string") {
  4632. data = new Uint8Array(input.length * 2);
  4633. length = 0;
  4634. for (let i = 0, ii = input.length; i < ii; i++) {
  4635. const code = input.charCodeAt(i);
  4636. if (code <= 0xff) {
  4637. data[length++] = code;
  4638. } else {
  4639. data[length++] = code >>> 8;
  4640. data[length++] = code & 0xff;
  4641. }
  4642. }
  4643. } else if (ArrayBuffer.isView(input)) {
  4644. data = input.slice();
  4645. length = data.byteLength;
  4646. } else {
  4647. throw new Error("Invalid data format, must be a string or TypedArray.");
  4648. }
  4649. const blockCounts = length >> 2;
  4650. const tailLength = length - blockCounts * 4;
  4651. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  4652. let k1 = 0,
  4653. k2 = 0;
  4654. let h1 = this.h1,
  4655. h2 = this.h2;
  4656. const C1 = 0xcc9e2d51,
  4657. C2 = 0x1b873593;
  4658. const C1_LOW = C1 & MASK_LOW,
  4659. C2_LOW = C2 & MASK_LOW;
  4660. for (let i = 0; i < blockCounts; i++) {
  4661. if (i & 1) {
  4662. k1 = dataUint32[i];
  4663. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4664. k1 = k1 << 15 | k1 >>> 17;
  4665. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4666. h1 ^= k1;
  4667. h1 = h1 << 13 | h1 >>> 19;
  4668. h1 = h1 * 5 + 0xe6546b64;
  4669. } else {
  4670. k2 = dataUint32[i];
  4671. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  4672. k2 = k2 << 15 | k2 >>> 17;
  4673. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  4674. h2 ^= k2;
  4675. h2 = h2 << 13 | h2 >>> 19;
  4676. h2 = h2 * 5 + 0xe6546b64;
  4677. }
  4678. }
  4679. k1 = 0;
  4680. switch (tailLength) {
  4681. case 3:
  4682. k1 ^= data[blockCounts * 4 + 2] << 16;
  4683. case 2:
  4684. k1 ^= data[blockCounts * 4 + 1] << 8;
  4685. case 1:
  4686. k1 ^= data[blockCounts * 4];
  4687. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4688. k1 = k1 << 15 | k1 >>> 17;
  4689. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4690. if (blockCounts & 1) {
  4691. h1 ^= k1;
  4692. } else {
  4693. h2 ^= k1;
  4694. }
  4695. }
  4696. this.h1 = h1;
  4697. this.h2 = h2;
  4698. }
  4699. hexdigest() {
  4700. let h1 = this.h1,
  4701. h2 = this.h2;
  4702. h1 ^= h2 >>> 1;
  4703. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  4704. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  4705. h1 ^= h2 >>> 1;
  4706. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  4707. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  4708. h1 ^= h2 >>> 1;
  4709. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  4710. }
  4711. }
  4712. ;// ./src/display/annotation_storage.js
  4713. const SerializableEmpty = Object.freeze({
  4714. map: null,
  4715. hash: "",
  4716. transfer: undefined
  4717. });
  4718. class AnnotationStorage {
  4719. #modified = false;
  4720. #modifiedIds = null;
  4721. #storage = new Map();
  4722. constructor() {
  4723. this.onSetModified = null;
  4724. this.onResetModified = null;
  4725. this.onAnnotationEditor = null;
  4726. }
  4727. getValue(key, defaultValue) {
  4728. const value = this.#storage.get(key);
  4729. if (value === undefined) {
  4730. return defaultValue;
  4731. }
  4732. return Object.assign(defaultValue, value);
  4733. }
  4734. getRawValue(key) {
  4735. return this.#storage.get(key);
  4736. }
  4737. remove(key) {
  4738. this.#storage.delete(key);
  4739. if (this.#storage.size === 0) {
  4740. this.resetModified();
  4741. }
  4742. if (typeof this.onAnnotationEditor === "function") {
  4743. for (const value of this.#storage.values()) {
  4744. if (value instanceof AnnotationEditor) {
  4745. return;
  4746. }
  4747. }
  4748. this.onAnnotationEditor(null);
  4749. }
  4750. }
  4751. setValue(key, value) {
  4752. const obj = this.#storage.get(key);
  4753. let modified = false;
  4754. if (obj !== undefined) {
  4755. for (const [entry, val] of Object.entries(value)) {
  4756. if (obj[entry] !== val) {
  4757. modified = true;
  4758. obj[entry] = val;
  4759. }
  4760. }
  4761. } else {
  4762. modified = true;
  4763. this.#storage.set(key, value);
  4764. }
  4765. if (modified) {
  4766. this.#setModified();
  4767. }
  4768. if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  4769. this.onAnnotationEditor(value.constructor._type);
  4770. }
  4771. }
  4772. has(key) {
  4773. return this.#storage.has(key);
  4774. }
  4775. getAll() {
  4776. return this.#storage.size > 0 ? objectFromMap(this.#storage) : null;
  4777. }
  4778. setAll(obj) {
  4779. for (const [key, val] of Object.entries(obj)) {
  4780. this.setValue(key, val);
  4781. }
  4782. }
  4783. get size() {
  4784. return this.#storage.size;
  4785. }
  4786. #setModified() {
  4787. if (!this.#modified) {
  4788. this.#modified = true;
  4789. if (typeof this.onSetModified === "function") {
  4790. this.onSetModified();
  4791. }
  4792. }
  4793. }
  4794. resetModified() {
  4795. if (this.#modified) {
  4796. this.#modified = false;
  4797. if (typeof this.onResetModified === "function") {
  4798. this.onResetModified();
  4799. }
  4800. }
  4801. }
  4802. get print() {
  4803. return new PrintAnnotationStorage(this);
  4804. }
  4805. get serializable() {
  4806. if (this.#storage.size === 0) {
  4807. return SerializableEmpty;
  4808. }
  4809. const map = new Map(),
  4810. hash = new MurmurHash3_64(),
  4811. transfer = [];
  4812. const context = Object.create(null);
  4813. let hasBitmap = false;
  4814. for (const [key, val] of this.#storage) {
  4815. const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;
  4816. if (serialized) {
  4817. map.set(key, serialized);
  4818. hash.update(`${key}:${JSON.stringify(serialized)}`);
  4819. hasBitmap ||= !!serialized.bitmap;
  4820. }
  4821. }
  4822. if (hasBitmap) {
  4823. for (const value of map.values()) {
  4824. if (value.bitmap) {
  4825. transfer.push(value.bitmap);
  4826. }
  4827. }
  4828. }
  4829. return map.size > 0 ? {
  4830. map,
  4831. hash: hash.hexdigest(),
  4832. transfer
  4833. } : SerializableEmpty;
  4834. }
  4835. get editorStats() {
  4836. let stats = null;
  4837. const typeToEditor = new Map();
  4838. for (const value of this.#storage.values()) {
  4839. if (!(value instanceof AnnotationEditor)) {
  4840. continue;
  4841. }
  4842. const editorStats = value.telemetryFinalData;
  4843. if (!editorStats) {
  4844. continue;
  4845. }
  4846. const {
  4847. type
  4848. } = editorStats;
  4849. if (!typeToEditor.has(type)) {
  4850. typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
  4851. }
  4852. stats ||= Object.create(null);
  4853. const map = stats[type] ||= new Map();
  4854. for (const [key, val] of Object.entries(editorStats)) {
  4855. if (key === "type") {
  4856. continue;
  4857. }
  4858. let counters = map.get(key);
  4859. if (!counters) {
  4860. counters = new Map();
  4861. map.set(key, counters);
  4862. }
  4863. const count = counters.get(val) ?? 0;
  4864. counters.set(val, count + 1);
  4865. }
  4866. }
  4867. for (const [type, editor] of typeToEditor) {
  4868. stats[type] = editor.computeTelemetryFinalData(stats[type]);
  4869. }
  4870. return stats;
  4871. }
  4872. resetModifiedIds() {
  4873. this.#modifiedIds = null;
  4874. }
  4875. get modifiedIds() {
  4876. if (this.#modifiedIds) {
  4877. return this.#modifiedIds;
  4878. }
  4879. const ids = [];
  4880. for (const value of this.#storage.values()) {
  4881. if (!(value instanceof AnnotationEditor) || !value.annotationElementId || !value.serialize()) {
  4882. continue;
  4883. }
  4884. ids.push(value.annotationElementId);
  4885. }
  4886. return this.#modifiedIds = {
  4887. ids: new Set(ids),
  4888. hash: ids.join(",")
  4889. };
  4890. }
  4891. }
  4892. class PrintAnnotationStorage extends AnnotationStorage {
  4893. #serializable;
  4894. constructor(parent) {
  4895. super();
  4896. const {
  4897. map,
  4898. hash,
  4899. transfer
  4900. } = parent.serializable;
  4901. const clone = structuredClone(map, transfer ? {
  4902. transfer
  4903. } : null);
  4904. this.#serializable = {
  4905. map: clone,
  4906. hash,
  4907. transfer
  4908. };
  4909. }
  4910. get print() {
  4911. unreachable("Should not call PrintAnnotationStorage.print");
  4912. }
  4913. get serializable() {
  4914. return this.#serializable;
  4915. }
  4916. get modifiedIds() {
  4917. return shadow(this, "modifiedIds", {
  4918. ids: new Set(),
  4919. hash: ""
  4920. });
  4921. }
  4922. }
  4923. ;// ./src/display/font_loader.js
  4924. class FontLoader {
  4925. #systemFonts = new Set();
  4926. constructor({
  4927. ownerDocument = globalThis.document,
  4928. styleElement = null
  4929. }) {
  4930. this._document = ownerDocument;
  4931. this.nativeFontFaces = new Set();
  4932. this.styleElement = null;
  4933. this.loadingRequests = [];
  4934. this.loadTestFontId = 0;
  4935. }
  4936. addNativeFontFace(nativeFontFace) {
  4937. this.nativeFontFaces.add(nativeFontFace);
  4938. this._document.fonts.add(nativeFontFace);
  4939. }
  4940. removeNativeFontFace(nativeFontFace) {
  4941. this.nativeFontFaces.delete(nativeFontFace);
  4942. this._document.fonts.delete(nativeFontFace);
  4943. }
  4944. insertRule(rule) {
  4945. if (!this.styleElement) {
  4946. this.styleElement = this._document.createElement("style");
  4947. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  4948. }
  4949. const styleSheet = this.styleElement.sheet;
  4950. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  4951. }
  4952. clear() {
  4953. for (const nativeFontFace of this.nativeFontFaces) {
  4954. this._document.fonts.delete(nativeFontFace);
  4955. }
  4956. this.nativeFontFaces.clear();
  4957. this.#systemFonts.clear();
  4958. if (this.styleElement) {
  4959. this.styleElement.remove();
  4960. this.styleElement = null;
  4961. }
  4962. }
  4963. async loadSystemFont({
  4964. systemFontInfo: info,
  4965. _inspectFont
  4966. }) {
  4967. if (!info || this.#systemFonts.has(info.loadedName)) {
  4968. return;
  4969. }
  4970. assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
  4971. if (this.isFontLoadingAPISupported) {
  4972. const {
  4973. loadedName,
  4974. src,
  4975. style
  4976. } = info;
  4977. const fontFace = new FontFace(loadedName, src, style);
  4978. this.addNativeFontFace(fontFace);
  4979. try {
  4980. await fontFace.load();
  4981. this.#systemFonts.add(loadedName);
  4982. _inspectFont?.(info);
  4983. } catch {
  4984. warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);
  4985. this.removeNativeFontFace(fontFace);
  4986. }
  4987. return;
  4988. }
  4989. unreachable("Not implemented: loadSystemFont without the Font Loading API.");
  4990. }
  4991. async bind(font) {
  4992. if (font.attached || font.missingFile && !font.systemFontInfo) {
  4993. return;
  4994. }
  4995. font.attached = true;
  4996. if (font.systemFontInfo) {
  4997. await this.loadSystemFont(font);
  4998. return;
  4999. }
  5000. if (this.isFontLoadingAPISupported) {
  5001. const nativeFontFace = font.createNativeFontFace();
  5002. if (nativeFontFace) {
  5003. this.addNativeFontFace(nativeFontFace);
  5004. try {
  5005. await nativeFontFace.loaded;
  5006. } catch (ex) {
  5007. warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  5008. font.disableFontFace = true;
  5009. throw ex;
  5010. }
  5011. }
  5012. return;
  5013. }
  5014. const rule = font.createFontFaceRule();
  5015. if (rule) {
  5016. this.insertRule(rule);
  5017. if (this.isSyncFontLoadingSupported) {
  5018. return;
  5019. }
  5020. await new Promise(resolve => {
  5021. const request = this._queueLoadingCallback(resolve);
  5022. this._prepareFontLoadEvent(font, request);
  5023. });
  5024. }
  5025. }
  5026. get isFontLoadingAPISupported() {
  5027. const hasFonts = !!this._document?.fonts;
  5028. return shadow(this, "isFontLoadingAPISupported", hasFonts);
  5029. }
  5030. get isSyncFontLoadingSupported() {
  5031. let supported = false;
  5032. if (isNodeJS) {
  5033. supported = true;
  5034. } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
  5035. supported = true;
  5036. }
  5037. return shadow(this, "isSyncFontLoadingSupported", supported);
  5038. }
  5039. _queueLoadingCallback(callback) {
  5040. function completeRequest() {
  5041. assert(!request.done, "completeRequest() cannot be called twice.");
  5042. request.done = true;
  5043. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  5044. const otherRequest = loadingRequests.shift();
  5045. setTimeout(otherRequest.callback, 0);
  5046. }
  5047. }
  5048. const {
  5049. loadingRequests
  5050. } = this;
  5051. const request = {
  5052. done: false,
  5053. complete: completeRequest,
  5054. callback
  5055. };
  5056. loadingRequests.push(request);
  5057. return request;
  5058. }
  5059. get _loadTestFont() {
  5060. 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==");
  5061. return shadow(this, "_loadTestFont", testFont);
  5062. }
  5063. _prepareFontLoadEvent(font, request) {
  5064. function int32(data, offset) {
  5065. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  5066. }
  5067. function spliceString(s, offset, remove, insert) {
  5068. const chunk1 = s.substring(0, offset);
  5069. const chunk2 = s.substring(offset + remove);
  5070. return chunk1 + insert + chunk2;
  5071. }
  5072. let i, ii;
  5073. const canvas = this._document.createElement("canvas");
  5074. canvas.width = 1;
  5075. canvas.height = 1;
  5076. const ctx = canvas.getContext("2d");
  5077. let called = 0;
  5078. function isFontReady(name, callback) {
  5079. if (++called > 30) {
  5080. warn("Load test font never loaded.");
  5081. callback();
  5082. return;
  5083. }
  5084. ctx.font = "30px " + name;
  5085. ctx.fillText(".", 0, 20);
  5086. const imageData = ctx.getImageData(0, 0, 1, 1);
  5087. if (imageData.data[3] > 0) {
  5088. callback();
  5089. return;
  5090. }
  5091. setTimeout(isFontReady.bind(null, name, callback));
  5092. }
  5093. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  5094. let data = this._loadTestFont;
  5095. const COMMENT_OFFSET = 976;
  5096. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  5097. const CFF_CHECKSUM_OFFSET = 16;
  5098. const XXXX_VALUE = 0x58585858;
  5099. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5100. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5101. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  5102. }
  5103. if (i < loadTestFontId.length) {
  5104. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  5105. }
  5106. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5107. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  5108. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  5109. this.insertRule(rule);
  5110. const div = this._document.createElement("div");
  5111. div.style.visibility = "hidden";
  5112. div.style.width = div.style.height = "10px";
  5113. div.style.position = "absolute";
  5114. div.style.top = div.style.left = "0px";
  5115. for (const name of [font.loadedName, loadTestFontId]) {
  5116. const span = this._document.createElement("span");
  5117. span.textContent = "Hi";
  5118. span.style.fontFamily = name;
  5119. div.append(span);
  5120. }
  5121. this._document.body.append(div);
  5122. isFontReady(loadTestFontId, () => {
  5123. div.remove();
  5124. request.complete();
  5125. });
  5126. }
  5127. }
  5128. class FontFaceObject {
  5129. constructor(translatedData, {
  5130. disableFontFace = false,
  5131. inspectFont = null
  5132. }) {
  5133. this.compiledGlyphs = Object.create(null);
  5134. for (const i in translatedData) {
  5135. this[i] = translatedData[i];
  5136. }
  5137. this.disableFontFace = disableFontFace === true;
  5138. this._inspectFont = inspectFont;
  5139. }
  5140. createNativeFontFace() {
  5141. if (!this.data || this.disableFontFace) {
  5142. return null;
  5143. }
  5144. let nativeFontFace;
  5145. if (!this.cssFontInfo) {
  5146. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5147. } else {
  5148. const css = {
  5149. weight: this.cssFontInfo.fontWeight
  5150. };
  5151. if (this.cssFontInfo.italicAngle) {
  5152. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  5153. }
  5154. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  5155. }
  5156. this._inspectFont?.(this);
  5157. return nativeFontFace;
  5158. }
  5159. createFontFaceRule() {
  5160. if (!this.data || this.disableFontFace) {
  5161. return null;
  5162. }
  5163. const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;
  5164. let rule;
  5165. if (!this.cssFontInfo) {
  5166. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  5167. } else {
  5168. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  5169. if (this.cssFontInfo.italicAngle) {
  5170. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  5171. }
  5172. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  5173. }
  5174. this._inspectFont?.(this, url);
  5175. return rule;
  5176. }
  5177. getPathGenerator(objs, character) {
  5178. if (this.compiledGlyphs[character] !== undefined) {
  5179. return this.compiledGlyphs[character];
  5180. }
  5181. let cmds;
  5182. try {
  5183. cmds = objs.get(this.loadedName + "_path_" + character);
  5184. } catch (ex) {
  5185. warn(`getPathGenerator - ignoring character: "${ex}".`);
  5186. }
  5187. if (!Array.isArray(cmds) || cmds.length === 0) {
  5188. return this.compiledGlyphs[character] = function (c, size) {};
  5189. }
  5190. const commands = [];
  5191. for (let i = 0, ii = cmds.length; i < ii;) {
  5192. switch (cmds[i++]) {
  5193. case FontRenderOps.BEZIER_CURVE_TO:
  5194. {
  5195. const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
  5196. commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f));
  5197. i += 6;
  5198. }
  5199. break;
  5200. case FontRenderOps.MOVE_TO:
  5201. {
  5202. const [a, b] = cmds.slice(i, i + 2);
  5203. commands.push(ctx => ctx.moveTo(a, b));
  5204. i += 2;
  5205. }
  5206. break;
  5207. case FontRenderOps.LINE_TO:
  5208. {
  5209. const [a, b] = cmds.slice(i, i + 2);
  5210. commands.push(ctx => ctx.lineTo(a, b));
  5211. i += 2;
  5212. }
  5213. break;
  5214. case FontRenderOps.QUADRATIC_CURVE_TO:
  5215. {
  5216. const [a, b, c, d] = cmds.slice(i, i + 4);
  5217. commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d));
  5218. i += 4;
  5219. }
  5220. break;
  5221. case FontRenderOps.RESTORE:
  5222. commands.push(ctx => ctx.restore());
  5223. break;
  5224. case FontRenderOps.SAVE:
  5225. commands.push(ctx => ctx.save());
  5226. break;
  5227. case FontRenderOps.SCALE:
  5228. assert(commands.length === 2, "Scale command is only valid at the third position.");
  5229. break;
  5230. case FontRenderOps.TRANSFORM:
  5231. {
  5232. const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
  5233. commands.push(ctx => ctx.transform(a, b, c, d, e, f));
  5234. i += 6;
  5235. }
  5236. break;
  5237. case FontRenderOps.TRANSLATE:
  5238. {
  5239. const [a, b] = cmds.slice(i, i + 2);
  5240. commands.push(ctx => ctx.translate(a, b));
  5241. i += 2;
  5242. }
  5243. break;
  5244. }
  5245. }
  5246. return this.compiledGlyphs[character] = function glyphDrawer(ctx, size) {
  5247. commands[0](ctx);
  5248. commands[1](ctx);
  5249. ctx.scale(size, -size);
  5250. for (let i = 2, ii = commands.length; i < ii; i++) {
  5251. commands[i](ctx);
  5252. }
  5253. };
  5254. }
  5255. }
  5256. ;// ./src/display/canvas_factory.js
  5257. class BaseCanvasFactory {
  5258. #enableHWA = false;
  5259. constructor({
  5260. enableHWA = false
  5261. }) {
  5262. this.#enableHWA = enableHWA;
  5263. }
  5264. create(width, height) {
  5265. if (width <= 0 || height <= 0) {
  5266. throw new Error("Invalid canvas size");
  5267. }
  5268. const canvas = this._createCanvas(width, height);
  5269. return {
  5270. canvas,
  5271. context: canvas.getContext("2d", {
  5272. willReadFrequently: !this.#enableHWA
  5273. })
  5274. };
  5275. }
  5276. reset(canvasAndContext, width, height) {
  5277. if (!canvasAndContext.canvas) {
  5278. throw new Error("Canvas is not specified");
  5279. }
  5280. if (width <= 0 || height <= 0) {
  5281. throw new Error("Invalid canvas size");
  5282. }
  5283. canvasAndContext.canvas.width = width;
  5284. canvasAndContext.canvas.height = height;
  5285. }
  5286. destroy(canvasAndContext) {
  5287. if (!canvasAndContext.canvas) {
  5288. throw new Error("Canvas is not specified");
  5289. }
  5290. canvasAndContext.canvas.width = 0;
  5291. canvasAndContext.canvas.height = 0;
  5292. canvasAndContext.canvas = null;
  5293. canvasAndContext.context = null;
  5294. }
  5295. _createCanvas(width, height) {
  5296. unreachable("Abstract method `_createCanvas` called.");
  5297. }
  5298. }
  5299. class DOMCanvasFactory extends BaseCanvasFactory {
  5300. constructor({
  5301. ownerDocument = globalThis.document,
  5302. enableHWA = false
  5303. }) {
  5304. super({
  5305. enableHWA
  5306. });
  5307. this._document = ownerDocument;
  5308. }
  5309. _createCanvas(width, height) {
  5310. const canvas = this._document.createElement("canvas");
  5311. canvas.width = width;
  5312. canvas.height = height;
  5313. return canvas;
  5314. }
  5315. }
  5316. ;// ./src/display/cmap_reader_factory.js
  5317. class BaseCMapReaderFactory {
  5318. constructor({
  5319. baseUrl = null,
  5320. isCompressed = true
  5321. }) {
  5322. this.baseUrl = baseUrl;
  5323. this.isCompressed = isCompressed;
  5324. }
  5325. async fetch({
  5326. name
  5327. }) {
  5328. if (!this.baseUrl) {
  5329. throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");
  5330. }
  5331. if (!name) {
  5332. throw new Error("CMap name must be specified.");
  5333. }
  5334. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  5335. return this._fetch(url).then(cMapData => ({
  5336. cMapData,
  5337. isCompressed: this.isCompressed
  5338. })).catch(reason => {
  5339. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  5340. });
  5341. }
  5342. async _fetch(url) {
  5343. unreachable("Abstract method `_fetch` called.");
  5344. }
  5345. }
  5346. class DOMCMapReaderFactory extends BaseCMapReaderFactory {
  5347. async _fetch(url) {
  5348. const data = await fetchData(url, this.isCompressed ? "arraybuffer" : "text");
  5349. return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data);
  5350. }
  5351. }
  5352. ;// ./src/display/filter_factory.js
  5353. class BaseFilterFactory {
  5354. addFilter(maps) {
  5355. return "none";
  5356. }
  5357. addHCMFilter(fgColor, bgColor) {
  5358. return "none";
  5359. }
  5360. addAlphaFilter(map) {
  5361. return "none";
  5362. }
  5363. addLuminosityFilter(map) {
  5364. return "none";
  5365. }
  5366. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  5367. return "none";
  5368. }
  5369. destroy(keepHCM = false) {}
  5370. }
  5371. class DOMFilterFactory extends BaseFilterFactory {
  5372. #baseUrl;
  5373. #_cache;
  5374. #_defs;
  5375. #docId;
  5376. #document;
  5377. #_hcmCache;
  5378. #id = 0;
  5379. constructor({
  5380. docId,
  5381. ownerDocument = globalThis.document
  5382. }) {
  5383. super();
  5384. this.#docId = docId;
  5385. this.#document = ownerDocument;
  5386. }
  5387. get #cache() {
  5388. return this.#_cache ||= new Map();
  5389. }
  5390. get #hcmCache() {
  5391. return this.#_hcmCache ||= new Map();
  5392. }
  5393. get #defs() {
  5394. if (!this.#_defs) {
  5395. const div = this.#document.createElement("div");
  5396. const {
  5397. style
  5398. } = div;
  5399. style.visibility = "hidden";
  5400. style.contain = "strict";
  5401. style.width = style.height = 0;
  5402. style.position = "absolute";
  5403. style.top = style.left = 0;
  5404. style.zIndex = -1;
  5405. const svg = this.#document.createElementNS(SVG_NS, "svg");
  5406. svg.setAttribute("width", 0);
  5407. svg.setAttribute("height", 0);
  5408. this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
  5409. div.append(svg);
  5410. svg.append(this.#_defs);
  5411. this.#document.body.append(div);
  5412. }
  5413. return this.#_defs;
  5414. }
  5415. #createTables(maps) {
  5416. if (maps.length === 1) {
  5417. const mapR = maps[0];
  5418. const buffer = new Array(256);
  5419. for (let i = 0; i < 256; i++) {
  5420. buffer[i] = mapR[i] / 255;
  5421. }
  5422. const table = buffer.join(",");
  5423. return [table, table, table];
  5424. }
  5425. const [mapR, mapG, mapB] = maps;
  5426. const bufferR = new Array(256);
  5427. const bufferG = new Array(256);
  5428. const bufferB = new Array(256);
  5429. for (let i = 0; i < 256; i++) {
  5430. bufferR[i] = mapR[i] / 255;
  5431. bufferG[i] = mapG[i] / 255;
  5432. bufferB[i] = mapB[i] / 255;
  5433. }
  5434. return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
  5435. }
  5436. #createUrl(id) {
  5437. if (this.#baseUrl === undefined) {
  5438. this.#baseUrl = "";
  5439. const url = this.#document.URL;
  5440. if (url !== this.#document.baseURI) {
  5441. if (isDataScheme(url)) {
  5442. warn('#createUrl: ignore "data:"-URL for performance reasons.');
  5443. } else {
  5444. this.#baseUrl = url.split("#", 1)[0];
  5445. }
  5446. }
  5447. }
  5448. return `url(${this.#baseUrl}#${id})`;
  5449. }
  5450. addFilter(maps) {
  5451. if (!maps) {
  5452. return "none";
  5453. }
  5454. let value = this.#cache.get(maps);
  5455. if (value) {
  5456. return value;
  5457. }
  5458. const [tableR, tableG, tableB] = this.#createTables(maps);
  5459. const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
  5460. value = this.#cache.get(key);
  5461. if (value) {
  5462. this.#cache.set(maps, value);
  5463. return value;
  5464. }
  5465. const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
  5466. const url = this.#createUrl(id);
  5467. this.#cache.set(maps, url);
  5468. this.#cache.set(key, url);
  5469. const filter = this.#createFilter(id);
  5470. this.#addTransferMapConversion(tableR, tableG, tableB, filter);
  5471. return url;
  5472. }
  5473. addHCMFilter(fgColor, bgColor) {
  5474. const key = `${fgColor}-${bgColor}`;
  5475. const filterName = "base";
  5476. let info = this.#hcmCache.get(filterName);
  5477. if (info?.key === key) {
  5478. return info.url;
  5479. }
  5480. if (info) {
  5481. info.filter?.remove();
  5482. info.key = key;
  5483. info.url = "none";
  5484. info.filter = null;
  5485. } else {
  5486. info = {
  5487. key,
  5488. url: "none",
  5489. filter: null
  5490. };
  5491. this.#hcmCache.set(filterName, info);
  5492. }
  5493. if (!fgColor || !bgColor) {
  5494. return info.url;
  5495. }
  5496. const fgRGB = this.#getRGB(fgColor);
  5497. fgColor = Util.makeHexColor(...fgRGB);
  5498. const bgRGB = this.#getRGB(bgColor);
  5499. bgColor = Util.makeHexColor(...bgRGB);
  5500. this.#defs.style.color = "";
  5501. if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
  5502. return info.url;
  5503. }
  5504. const map = new Array(256);
  5505. for (let i = 0; i <= 255; i++) {
  5506. const x = i / 255;
  5507. map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  5508. }
  5509. const table = map.join(",");
  5510. const id = `g_${this.#docId}_hcm_filter`;
  5511. const filter = info.filter = this.#createFilter(id);
  5512. this.#addTransferMapConversion(table, table, table, filter);
  5513. this.#addGrayConversion(filter);
  5514. const getSteps = (c, n) => {
  5515. const start = fgRGB[c] / 255;
  5516. const end = bgRGB[c] / 255;
  5517. const arr = new Array(n + 1);
  5518. for (let i = 0; i <= n; i++) {
  5519. arr[i] = start + i / n * (end - start);
  5520. }
  5521. return arr.join(",");
  5522. };
  5523. this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
  5524. info.url = this.#createUrl(id);
  5525. return info.url;
  5526. }
  5527. addAlphaFilter(map) {
  5528. let value = this.#cache.get(map);
  5529. if (value) {
  5530. return value;
  5531. }
  5532. const [tableA] = this.#createTables([map]);
  5533. const key = `alpha_${tableA}`;
  5534. value = this.#cache.get(key);
  5535. if (value) {
  5536. this.#cache.set(map, value);
  5537. return value;
  5538. }
  5539. const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
  5540. const url = this.#createUrl(id);
  5541. this.#cache.set(map, url);
  5542. this.#cache.set(key, url);
  5543. const filter = this.#createFilter(id);
  5544. this.#addTransferMapAlphaConversion(tableA, filter);
  5545. return url;
  5546. }
  5547. addLuminosityFilter(map) {
  5548. let value = this.#cache.get(map || "luminosity");
  5549. if (value) {
  5550. return value;
  5551. }
  5552. let tableA, key;
  5553. if (map) {
  5554. [tableA] = this.#createTables([map]);
  5555. key = `luminosity_${tableA}`;
  5556. } else {
  5557. key = "luminosity";
  5558. }
  5559. value = this.#cache.get(key);
  5560. if (value) {
  5561. this.#cache.set(map, value);
  5562. return value;
  5563. }
  5564. const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
  5565. const url = this.#createUrl(id);
  5566. this.#cache.set(map, url);
  5567. this.#cache.set(key, url);
  5568. const filter = this.#createFilter(id);
  5569. this.#addLuminosityConversion(filter);
  5570. if (map) {
  5571. this.#addTransferMapAlphaConversion(tableA, filter);
  5572. }
  5573. return url;
  5574. }
  5575. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  5576. const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
  5577. let info = this.#hcmCache.get(filterName);
  5578. if (info?.key === key) {
  5579. return info.url;
  5580. }
  5581. if (info) {
  5582. info.filter?.remove();
  5583. info.key = key;
  5584. info.url = "none";
  5585. info.filter = null;
  5586. } else {
  5587. info = {
  5588. key,
  5589. url: "none",
  5590. filter: null
  5591. };
  5592. this.#hcmCache.set(filterName, info);
  5593. }
  5594. if (!fgColor || !bgColor) {
  5595. return info.url;
  5596. }
  5597. const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
  5598. let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
  5599. let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
  5600. let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
  5601. if (bgGray < fgGray) {
  5602. [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
  5603. }
  5604. this.#defs.style.color = "";
  5605. const getSteps = (fg, bg, n) => {
  5606. const arr = new Array(256);
  5607. const step = (bgGray - fgGray) / n;
  5608. const newStart = fg / 255;
  5609. const newStep = (bg - fg) / (255 * n);
  5610. let prev = 0;
  5611. for (let i = 0; i <= n; i++) {
  5612. const k = Math.round(fgGray + i * step);
  5613. const value = newStart + i * newStep;
  5614. for (let j = prev; j <= k; j++) {
  5615. arr[j] = value;
  5616. }
  5617. prev = k + 1;
  5618. }
  5619. for (let i = prev; i < 256; i++) {
  5620. arr[i] = arr[prev - 1];
  5621. }
  5622. return arr.join(",");
  5623. };
  5624. const id = `g_${this.#docId}_hcm_${filterName}_filter`;
  5625. const filter = info.filter = this.#createFilter(id);
  5626. this.#addGrayConversion(filter);
  5627. this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
  5628. info.url = this.#createUrl(id);
  5629. return info.url;
  5630. }
  5631. destroy(keepHCM = false) {
  5632. if (keepHCM && this.#hcmCache.size !== 0) {
  5633. return;
  5634. }
  5635. if (this.#_defs) {
  5636. this.#_defs.parentNode.parentNode.remove();
  5637. this.#_defs = null;
  5638. }
  5639. if (this.#_cache) {
  5640. this.#_cache.clear();
  5641. this.#_cache = null;
  5642. }
  5643. this.#id = 0;
  5644. }
  5645. #addLuminosityConversion(filter) {
  5646. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  5647. feColorMatrix.setAttribute("type", "matrix");
  5648. 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");
  5649. filter.append(feColorMatrix);
  5650. }
  5651. #addGrayConversion(filter) {
  5652. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  5653. feColorMatrix.setAttribute("type", "matrix");
  5654. 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");
  5655. filter.append(feColorMatrix);
  5656. }
  5657. #createFilter(id) {
  5658. const filter = this.#document.createElementNS(SVG_NS, "filter");
  5659. filter.setAttribute("color-interpolation-filters", "sRGB");
  5660. filter.setAttribute("id", id);
  5661. this.#defs.append(filter);
  5662. return filter;
  5663. }
  5664. #appendFeFunc(feComponentTransfer, func, table) {
  5665. const feFunc = this.#document.createElementNS(SVG_NS, func);
  5666. feFunc.setAttribute("type", "discrete");
  5667. feFunc.setAttribute("tableValues", table);
  5668. feComponentTransfer.append(feFunc);
  5669. }
  5670. #addTransferMapConversion(rTable, gTable, bTable, filter) {
  5671. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  5672. filter.append(feComponentTransfer);
  5673. this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
  5674. this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
  5675. this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
  5676. }
  5677. #addTransferMapAlphaConversion(aTable, filter) {
  5678. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  5679. filter.append(feComponentTransfer);
  5680. this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
  5681. }
  5682. #getRGB(color) {
  5683. this.#defs.style.color = color;
  5684. return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
  5685. }
  5686. }
  5687. ;// ./src/display/standard_fontdata_factory.js
  5688. class BaseStandardFontDataFactory {
  5689. constructor({
  5690. baseUrl = null
  5691. }) {
  5692. this.baseUrl = baseUrl;
  5693. }
  5694. async fetch({
  5695. filename
  5696. }) {
  5697. if (!this.baseUrl) {
  5698. throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");
  5699. }
  5700. if (!filename) {
  5701. throw new Error("Font filename must be specified.");
  5702. }
  5703. const url = `${this.baseUrl}${filename}`;
  5704. return this._fetch(url).catch(reason => {
  5705. throw new Error(`Unable to load font data at: ${url}`);
  5706. });
  5707. }
  5708. async _fetch(url) {
  5709. unreachable("Abstract method `_fetch` called.");
  5710. }
  5711. }
  5712. class DOMStandardFontDataFactory extends BaseStandardFontDataFactory {
  5713. async _fetch(url) {
  5714. const data = await fetchData(url, "arraybuffer");
  5715. return new Uint8Array(data);
  5716. }
  5717. }
  5718. ;// ./src/display/node_utils.js
  5719. if (isNodeJS) {
  5720. var packageCapability = Promise.withResolvers();
  5721. var packageMap = null;
  5722. const loadPackages = async () => {
  5723. const fs = await import(/*webpackIgnore: true*/"fs"),
  5724. http = await import(/*webpackIgnore: true*/"http"),
  5725. https = await import(/*webpackIgnore: true*/"https"),
  5726. url = await import(/*webpackIgnore: true*/"url");
  5727. let canvas, path2d;
  5728. return new Map(Object.entries({
  5729. fs,
  5730. http,
  5731. https,
  5732. url,
  5733. canvas,
  5734. path2d
  5735. }));
  5736. };
  5737. loadPackages().then(map => {
  5738. packageMap = map;
  5739. packageCapability.resolve();
  5740. }, reason => {
  5741. warn(`loadPackages: ${reason}`);
  5742. packageMap = new Map();
  5743. packageCapability.resolve();
  5744. });
  5745. }
  5746. class NodePackages {
  5747. static get promise() {
  5748. return packageCapability.promise;
  5749. }
  5750. static get(name) {
  5751. return packageMap?.get(name);
  5752. }
  5753. }
  5754. async function node_utils_fetchData(url) {
  5755. const fs = NodePackages.get("fs");
  5756. const data = await fs.promises.readFile(url);
  5757. return new Uint8Array(data);
  5758. }
  5759. class NodeFilterFactory extends BaseFilterFactory {}
  5760. class NodeCanvasFactory extends BaseCanvasFactory {
  5761. _createCanvas(width, height) {
  5762. const canvas = NodePackages.get("canvas");
  5763. return canvas.createCanvas(width, height);
  5764. }
  5765. }
  5766. class NodeCMapReaderFactory extends BaseCMapReaderFactory {
  5767. async _fetch(url) {
  5768. return node_utils_fetchData(url);
  5769. }
  5770. }
  5771. class NodeStandardFontDataFactory extends BaseStandardFontDataFactory {
  5772. async _fetch(url) {
  5773. return node_utils_fetchData(url);
  5774. }
  5775. }
  5776. ;// ./src/display/pattern_helper.js
  5777. const PathType = {
  5778. FILL: "Fill",
  5779. STROKE: "Stroke",
  5780. SHADING: "Shading"
  5781. };
  5782. function applyBoundingBox(ctx, bbox) {
  5783. if (!bbox) {
  5784. return;
  5785. }
  5786. const width = bbox[2] - bbox[0];
  5787. const height = bbox[3] - bbox[1];
  5788. const region = new Path2D();
  5789. region.rect(bbox[0], bbox[1], width, height);
  5790. ctx.clip(region);
  5791. }
  5792. class BaseShadingPattern {
  5793. getPattern() {
  5794. unreachable("Abstract method `getPattern` called.");
  5795. }
  5796. }
  5797. class RadialAxialShadingPattern extends BaseShadingPattern {
  5798. constructor(IR) {
  5799. super();
  5800. this._type = IR[1];
  5801. this._bbox = IR[2];
  5802. this._colorStops = IR[3];
  5803. this._p0 = IR[4];
  5804. this._p1 = IR[5];
  5805. this._r0 = IR[6];
  5806. this._r1 = IR[7];
  5807. this.matrix = null;
  5808. }
  5809. _createGradient(ctx) {
  5810. let grad;
  5811. if (this._type === "axial") {
  5812. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  5813. } else if (this._type === "radial") {
  5814. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  5815. }
  5816. for (const colorStop of this._colorStops) {
  5817. grad.addColorStop(colorStop[0], colorStop[1]);
  5818. }
  5819. return grad;
  5820. }
  5821. getPattern(ctx, owner, inverse, pathType) {
  5822. let pattern;
  5823. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  5824. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
  5825. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  5826. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  5827. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);
  5828. const tmpCtx = tmpCanvas.context;
  5829. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5830. tmpCtx.beginPath();
  5831. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  5832. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  5833. inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  5834. tmpCtx.transform(...owner.baseTransform);
  5835. if (this.matrix) {
  5836. tmpCtx.transform(...this.matrix);
  5837. }
  5838. applyBoundingBox(tmpCtx, this._bbox);
  5839. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  5840. tmpCtx.fill();
  5841. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  5842. const domMatrix = new DOMMatrix(inverse);
  5843. pattern.setTransform(domMatrix);
  5844. } else {
  5845. applyBoundingBox(ctx, this._bbox);
  5846. pattern = this._createGradient(ctx);
  5847. }
  5848. return pattern;
  5849. }
  5850. }
  5851. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5852. const coords = context.coords,
  5853. colors = context.colors;
  5854. const bytes = data.data,
  5855. rowSize = data.width * 4;
  5856. let tmp;
  5857. if (coords[p1 + 1] > coords[p2 + 1]) {
  5858. tmp = p1;
  5859. p1 = p2;
  5860. p2 = tmp;
  5861. tmp = c1;
  5862. c1 = c2;
  5863. c2 = tmp;
  5864. }
  5865. if (coords[p2 + 1] > coords[p3 + 1]) {
  5866. tmp = p2;
  5867. p2 = p3;
  5868. p3 = tmp;
  5869. tmp = c2;
  5870. c2 = c3;
  5871. c3 = tmp;
  5872. }
  5873. if (coords[p1 + 1] > coords[p2 + 1]) {
  5874. tmp = p1;
  5875. p1 = p2;
  5876. p2 = tmp;
  5877. tmp = c1;
  5878. c1 = c2;
  5879. c2 = tmp;
  5880. }
  5881. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5882. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5883. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5884. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5885. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5886. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5887. if (y1 >= y3) {
  5888. return;
  5889. }
  5890. const c1r = colors[c1],
  5891. c1g = colors[c1 + 1],
  5892. c1b = colors[c1 + 2];
  5893. const c2r = colors[c2],
  5894. c2g = colors[c2 + 1],
  5895. c2b = colors[c2 + 2];
  5896. const c3r = colors[c3],
  5897. c3g = colors[c3 + 1],
  5898. c3b = colors[c3 + 2];
  5899. const minY = Math.round(y1),
  5900. maxY = Math.round(y3);
  5901. let xa, car, cag, cab;
  5902. let xb, cbr, cbg, cbb;
  5903. for (let y = minY; y <= maxY; y++) {
  5904. if (y < y2) {
  5905. const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);
  5906. xa = x1 - (x1 - x2) * k;
  5907. car = c1r - (c1r - c2r) * k;
  5908. cag = c1g - (c1g - c2g) * k;
  5909. cab = c1b - (c1b - c2b) * k;
  5910. } else {
  5911. let k;
  5912. if (y > y3) {
  5913. k = 1;
  5914. } else if (y2 === y3) {
  5915. k = 0;
  5916. } else {
  5917. k = (y2 - y) / (y2 - y3);
  5918. }
  5919. xa = x2 - (x2 - x3) * k;
  5920. car = c2r - (c2r - c3r) * k;
  5921. cag = c2g - (c2g - c3g) * k;
  5922. cab = c2b - (c2b - c3b) * k;
  5923. }
  5924. let k;
  5925. if (y < y1) {
  5926. k = 0;
  5927. } else if (y > y3) {
  5928. k = 1;
  5929. } else {
  5930. k = (y1 - y) / (y1 - y3);
  5931. }
  5932. xb = x1 - (x1 - x3) * k;
  5933. cbr = c1r - (c1r - c3r) * k;
  5934. cbg = c1g - (c1g - c3g) * k;
  5935. cbb = c1b - (c1b - c3b) * k;
  5936. const x1_ = Math.round(Math.min(xa, xb));
  5937. const x2_ = Math.round(Math.max(xa, xb));
  5938. let j = rowSize * y + x1_ * 4;
  5939. for (let x = x1_; x <= x2_; x++) {
  5940. k = (xa - x) / (xa - xb);
  5941. if (k < 0) {
  5942. k = 0;
  5943. } else if (k > 1) {
  5944. k = 1;
  5945. }
  5946. bytes[j++] = car - (car - cbr) * k | 0;
  5947. bytes[j++] = cag - (cag - cbg) * k | 0;
  5948. bytes[j++] = cab - (cab - cbb) * k | 0;
  5949. bytes[j++] = 255;
  5950. }
  5951. }
  5952. }
  5953. function drawFigure(data, figure, context) {
  5954. const ps = figure.coords;
  5955. const cs = figure.colors;
  5956. let i, ii;
  5957. switch (figure.type) {
  5958. case "lattice":
  5959. const verticesPerRow = figure.verticesPerRow;
  5960. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  5961. const cols = verticesPerRow - 1;
  5962. for (i = 0; i < rows; i++) {
  5963. let q = i * verticesPerRow;
  5964. for (let j = 0; j < cols; j++, q++) {
  5965. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5966. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5967. }
  5968. }
  5969. break;
  5970. case "triangles":
  5971. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5972. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  5973. }
  5974. break;
  5975. default:
  5976. throw new Error("illegal figure");
  5977. }
  5978. }
  5979. class MeshShadingPattern extends BaseShadingPattern {
  5980. constructor(IR) {
  5981. super();
  5982. this._coords = IR[2];
  5983. this._colors = IR[3];
  5984. this._figures = IR[4];
  5985. this._bounds = IR[5];
  5986. this._bbox = IR[7];
  5987. this._background = IR[8];
  5988. this.matrix = null;
  5989. }
  5990. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  5991. const EXPECTED_SCALE = 1.1;
  5992. const MAX_PATTERN_SIZE = 3000;
  5993. const BORDER_SIZE = 2;
  5994. const offsetX = Math.floor(this._bounds[0]);
  5995. const offsetY = Math.floor(this._bounds[1]);
  5996. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  5997. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  5998. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5999. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6000. const scaleX = boundsWidth / width;
  6001. const scaleY = boundsHeight / height;
  6002. const context = {
  6003. coords: this._coords,
  6004. colors: this._colors,
  6005. offsetX: -offsetX,
  6006. offsetY: -offsetY,
  6007. scaleX: 1 / scaleX,
  6008. scaleY: 1 / scaleY
  6009. };
  6010. const paddedWidth = width + BORDER_SIZE * 2;
  6011. const paddedHeight = height + BORDER_SIZE * 2;
  6012. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);
  6013. const tmpCtx = tmpCanvas.context;
  6014. const data = tmpCtx.createImageData(width, height);
  6015. if (backgroundColor) {
  6016. const bytes = data.data;
  6017. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  6018. bytes[i] = backgroundColor[0];
  6019. bytes[i + 1] = backgroundColor[1];
  6020. bytes[i + 2] = backgroundColor[2];
  6021. bytes[i + 3] = 255;
  6022. }
  6023. }
  6024. for (const figure of this._figures) {
  6025. drawFigure(data, figure, context);
  6026. }
  6027. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6028. const canvas = tmpCanvas.canvas;
  6029. return {
  6030. canvas,
  6031. offsetX: offsetX - BORDER_SIZE * scaleX,
  6032. offsetY: offsetY - BORDER_SIZE * scaleY,
  6033. scaleX,
  6034. scaleY
  6035. };
  6036. }
  6037. getPattern(ctx, owner, inverse, pathType) {
  6038. applyBoundingBox(ctx, this._bbox);
  6039. let scale;
  6040. if (pathType === PathType.SHADING) {
  6041. scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx));
  6042. } else {
  6043. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  6044. if (this.matrix) {
  6045. const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6046. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  6047. }
  6048. }
  6049. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  6050. if (pathType !== PathType.SHADING) {
  6051. ctx.setTransform(...owner.baseTransform);
  6052. if (this.matrix) {
  6053. ctx.transform(...this.matrix);
  6054. }
  6055. }
  6056. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6057. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6058. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  6059. }
  6060. }
  6061. class DummyShadingPattern extends BaseShadingPattern {
  6062. getPattern() {
  6063. return "hotpink";
  6064. }
  6065. }
  6066. function getShadingPattern(IR) {
  6067. switch (IR[0]) {
  6068. case "RadialAxial":
  6069. return new RadialAxialShadingPattern(IR);
  6070. case "Mesh":
  6071. return new MeshShadingPattern(IR);
  6072. case "Dummy":
  6073. return new DummyShadingPattern();
  6074. }
  6075. throw new Error(`Unknown IR type: ${IR[0]}`);
  6076. }
  6077. const PaintType = {
  6078. COLORED: 1,
  6079. UNCOLORED: 2
  6080. };
  6081. class TilingPattern {
  6082. static MAX_PATTERN_SIZE = 3000;
  6083. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6084. this.operatorList = IR[2];
  6085. this.matrix = IR[3];
  6086. this.bbox = IR[4];
  6087. this.xstep = IR[5];
  6088. this.ystep = IR[6];
  6089. this.paintType = IR[7];
  6090. this.tilingType = IR[8];
  6091. this.color = color;
  6092. this.ctx = ctx;
  6093. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6094. this.baseTransform = baseTransform;
  6095. }
  6096. createPatternCanvas(owner) {
  6097. const {
  6098. bbox,
  6099. operatorList,
  6100. paintType,
  6101. tilingType,
  6102. color,
  6103. canvasGraphicsFactory
  6104. } = this;
  6105. let {
  6106. xstep,
  6107. ystep
  6108. } = this;
  6109. xstep = Math.abs(xstep);
  6110. ystep = Math.abs(ystep);
  6111. info("TilingType: " + tilingType);
  6112. const x0 = bbox[0],
  6113. y0 = bbox[1],
  6114. x1 = bbox[2],
  6115. y1 = bbox[3];
  6116. const width = x1 - x0;
  6117. const height = y1 - y0;
  6118. const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6119. const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  6120. const combinedScaleX = matrixScale[0] * curMatrixScale[0];
  6121. const combinedScaleY = matrixScale[1] * curMatrixScale[1];
  6122. let canvasWidth = width,
  6123. canvasHeight = height,
  6124. redrawHorizontally = false,
  6125. redrawVertically = false;
  6126. const xScaledStep = Math.ceil(xstep * combinedScaleX);
  6127. const yScaledStep = Math.ceil(ystep * combinedScaleY);
  6128. const xScaledWidth = Math.ceil(width * combinedScaleX);
  6129. const yScaledHeight = Math.ceil(height * combinedScaleY);
  6130. if (xScaledStep >= xScaledWidth) {
  6131. canvasWidth = xstep;
  6132. } else {
  6133. redrawHorizontally = true;
  6134. }
  6135. if (yScaledStep >= yScaledHeight) {
  6136. canvasHeight = ystep;
  6137. } else {
  6138. redrawVertically = true;
  6139. }
  6140. const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  6141. const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  6142. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);
  6143. const tmpCtx = tmpCanvas.context;
  6144. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6145. graphics.groupLevel = owner.groupLevel;
  6146. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  6147. tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);
  6148. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  6149. tmpCtx.save();
  6150. this.clipBbox(graphics, x0, y0, x1, y1);
  6151. graphics.baseTransform = getCurrentTransform(graphics.ctx);
  6152. graphics.executeOperatorList(operatorList);
  6153. graphics.endDrawing();
  6154. tmpCtx.restore();
  6155. if (redrawHorizontally || redrawVertically) {
  6156. const image = tmpCanvas.canvas;
  6157. if (redrawHorizontally) {
  6158. canvasWidth = xstep;
  6159. }
  6160. if (redrawVertically) {
  6161. canvasHeight = ystep;
  6162. }
  6163. const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  6164. const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  6165. const xSize = dimx2.size;
  6166. const ySize = dimy2.size;
  6167. const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);
  6168. const tmpCtx2 = tmpCanvas2.context;
  6169. const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;
  6170. const jj = redrawVertically ? Math.floor(height / ystep) : 0;
  6171. for (let i = 0; i <= ii; i++) {
  6172. for (let j = 0; j <= jj; j++) {
  6173. tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize);
  6174. }
  6175. }
  6176. return {
  6177. canvas: tmpCanvas2.canvas,
  6178. scaleX: dimx2.scale,
  6179. scaleY: dimy2.scale,
  6180. offsetX: x0,
  6181. offsetY: y0
  6182. };
  6183. }
  6184. return {
  6185. canvas: tmpCanvas.canvas,
  6186. scaleX: dimx.scale,
  6187. scaleY: dimy.scale,
  6188. offsetX: x0,
  6189. offsetY: y0
  6190. };
  6191. }
  6192. getSizeAndScale(step, realOutputSize, scale) {
  6193. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  6194. let size = Math.ceil(step * scale);
  6195. if (size >= maxSize) {
  6196. size = maxSize;
  6197. } else {
  6198. scale = size / step;
  6199. }
  6200. return {
  6201. scale,
  6202. size
  6203. };
  6204. }
  6205. clipBbox(graphics, x0, y0, x1, y1) {
  6206. const bboxWidth = x1 - x0;
  6207. const bboxHeight = y1 - y0;
  6208. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6209. graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]);
  6210. graphics.clip();
  6211. graphics.endPath();
  6212. }
  6213. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  6214. const context = graphics.ctx,
  6215. current = graphics.current;
  6216. switch (paintType) {
  6217. case PaintType.COLORED:
  6218. const ctx = this.ctx;
  6219. context.fillStyle = ctx.fillStyle;
  6220. context.strokeStyle = ctx.strokeStyle;
  6221. current.fillColor = ctx.fillStyle;
  6222. current.strokeColor = ctx.strokeStyle;
  6223. break;
  6224. case PaintType.UNCOLORED:
  6225. const cssColor = Util.makeHexColor(color[0], color[1], color[2]);
  6226. context.fillStyle = cssColor;
  6227. context.strokeStyle = cssColor;
  6228. current.fillColor = cssColor;
  6229. current.strokeColor = cssColor;
  6230. break;
  6231. default:
  6232. throw new FormatError(`Unsupported paint type: ${paintType}`);
  6233. }
  6234. }
  6235. getPattern(ctx, owner, inverse, pathType) {
  6236. let matrix = inverse;
  6237. if (pathType !== PathType.SHADING) {
  6238. matrix = Util.transform(matrix, owner.baseTransform);
  6239. if (this.matrix) {
  6240. matrix = Util.transform(matrix, this.matrix);
  6241. }
  6242. }
  6243. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  6244. let domMatrix = new DOMMatrix(matrix);
  6245. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6246. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  6247. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  6248. pattern.setTransform(domMatrix);
  6249. return pattern;
  6250. }
  6251. }
  6252. ;// ./src/shared/image_utils.js
  6253. function convertToRGBA(params) {
  6254. switch (params.kind) {
  6255. case ImageKind.GRAYSCALE_1BPP:
  6256. return convertBlackAndWhiteToRGBA(params);
  6257. case ImageKind.RGB_24BPP:
  6258. return convertRGBToRGBA(params);
  6259. }
  6260. return null;
  6261. }
  6262. function convertBlackAndWhiteToRGBA({
  6263. src,
  6264. srcPos = 0,
  6265. dest,
  6266. width,
  6267. height,
  6268. nonBlackColor = 0xffffffff,
  6269. inverseDecode = false
  6270. }) {
  6271. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  6272. const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
  6273. const widthInSource = width >> 3;
  6274. const widthRemainder = width & 7;
  6275. const srcLength = src.length;
  6276. dest = new Uint32Array(dest.buffer);
  6277. let destPos = 0;
  6278. for (let i = 0; i < height; i++) {
  6279. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  6280. const elem = srcPos < srcLength ? src[srcPos] : 255;
  6281. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  6282. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  6283. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  6284. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  6285. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  6286. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  6287. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  6288. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  6289. }
  6290. if (widthRemainder === 0) {
  6291. continue;
  6292. }
  6293. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  6294. for (let j = 0; j < widthRemainder; j++) {
  6295. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  6296. }
  6297. }
  6298. return {
  6299. srcPos,
  6300. destPos
  6301. };
  6302. }
  6303. function convertRGBToRGBA({
  6304. src,
  6305. srcPos = 0,
  6306. dest,
  6307. destPos = 0,
  6308. width,
  6309. height
  6310. }) {
  6311. let i = 0;
  6312. const len32 = src.length >> 2;
  6313. const src32 = new Uint32Array(src.buffer, srcPos, len32);
  6314. if (FeatureTest.isLittleEndian) {
  6315. for (; i < len32 - 2; i += 3, destPos += 4) {
  6316. const s1 = src32[i];
  6317. const s2 = src32[i + 1];
  6318. const s3 = src32[i + 2];
  6319. dest[destPos] = s1 | 0xff000000;
  6320. dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
  6321. dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
  6322. dest[destPos + 3] = s3 >>> 8 | 0xff000000;
  6323. }
  6324. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  6325. dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
  6326. }
  6327. } else {
  6328. for (; i < len32 - 2; i += 3, destPos += 4) {
  6329. const s1 = src32[i];
  6330. const s2 = src32[i + 1];
  6331. const s3 = src32[i + 2];
  6332. dest[destPos] = s1 | 0xff;
  6333. dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
  6334. dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
  6335. dest[destPos + 3] = s3 << 8 | 0xff;
  6336. }
  6337. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  6338. dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
  6339. }
  6340. }
  6341. return {
  6342. srcPos,
  6343. destPos
  6344. };
  6345. }
  6346. function grayToRGBA(src, dest) {
  6347. if (FeatureTest.isLittleEndian) {
  6348. for (let i = 0, ii = src.length; i < ii; i++) {
  6349. dest[i] = src[i] * 0x10101 | 0xff000000;
  6350. }
  6351. } else {
  6352. for (let i = 0, ii = src.length; i < ii; i++) {
  6353. dest[i] = src[i] * 0x1010100 | 0x000000ff;
  6354. }
  6355. }
  6356. }
  6357. ;// ./src/display/canvas.js
  6358. const MIN_FONT_SIZE = 16;
  6359. const MAX_FONT_SIZE = 100;
  6360. const EXECUTION_TIME = 15;
  6361. const EXECUTION_STEPS = 10;
  6362. const MAX_SIZE_TO_COMPILE = 1000;
  6363. const FULL_CHUNK_HEIGHT = 16;
  6364. function mirrorContextOperations(ctx, destCtx) {
  6365. if (ctx._removeMirroring) {
  6366. throw new Error("Context is already forwarding operations.");
  6367. }
  6368. ctx.__originalSave = ctx.save;
  6369. ctx.__originalRestore = ctx.restore;
  6370. ctx.__originalRotate = ctx.rotate;
  6371. ctx.__originalScale = ctx.scale;
  6372. ctx.__originalTranslate = ctx.translate;
  6373. ctx.__originalTransform = ctx.transform;
  6374. ctx.__originalSetTransform = ctx.setTransform;
  6375. ctx.__originalResetTransform = ctx.resetTransform;
  6376. ctx.__originalClip = ctx.clip;
  6377. ctx.__originalMoveTo = ctx.moveTo;
  6378. ctx.__originalLineTo = ctx.lineTo;
  6379. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  6380. ctx.__originalRect = ctx.rect;
  6381. ctx.__originalClosePath = ctx.closePath;
  6382. ctx.__originalBeginPath = ctx.beginPath;
  6383. ctx._removeMirroring = () => {
  6384. ctx.save = ctx.__originalSave;
  6385. ctx.restore = ctx.__originalRestore;
  6386. ctx.rotate = ctx.__originalRotate;
  6387. ctx.scale = ctx.__originalScale;
  6388. ctx.translate = ctx.__originalTranslate;
  6389. ctx.transform = ctx.__originalTransform;
  6390. ctx.setTransform = ctx.__originalSetTransform;
  6391. ctx.resetTransform = ctx.__originalResetTransform;
  6392. ctx.clip = ctx.__originalClip;
  6393. ctx.moveTo = ctx.__originalMoveTo;
  6394. ctx.lineTo = ctx.__originalLineTo;
  6395. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  6396. ctx.rect = ctx.__originalRect;
  6397. ctx.closePath = ctx.__originalClosePath;
  6398. ctx.beginPath = ctx.__originalBeginPath;
  6399. delete ctx._removeMirroring;
  6400. };
  6401. ctx.save = function ctxSave() {
  6402. destCtx.save();
  6403. this.__originalSave();
  6404. };
  6405. ctx.restore = function ctxRestore() {
  6406. destCtx.restore();
  6407. this.__originalRestore();
  6408. };
  6409. ctx.translate = function ctxTranslate(x, y) {
  6410. destCtx.translate(x, y);
  6411. this.__originalTranslate(x, y);
  6412. };
  6413. ctx.scale = function ctxScale(x, y) {
  6414. destCtx.scale(x, y);
  6415. this.__originalScale(x, y);
  6416. };
  6417. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6418. destCtx.transform(a, b, c, d, e, f);
  6419. this.__originalTransform(a, b, c, d, e, f);
  6420. };
  6421. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6422. destCtx.setTransform(a, b, c, d, e, f);
  6423. this.__originalSetTransform(a, b, c, d, e, f);
  6424. };
  6425. ctx.resetTransform = function ctxResetTransform() {
  6426. destCtx.resetTransform();
  6427. this.__originalResetTransform();
  6428. };
  6429. ctx.rotate = function ctxRotate(angle) {
  6430. destCtx.rotate(angle);
  6431. this.__originalRotate(angle);
  6432. };
  6433. ctx.clip = function ctxRotate(rule) {
  6434. destCtx.clip(rule);
  6435. this.__originalClip(rule);
  6436. };
  6437. ctx.moveTo = function (x, y) {
  6438. destCtx.moveTo(x, y);
  6439. this.__originalMoveTo(x, y);
  6440. };
  6441. ctx.lineTo = function (x, y) {
  6442. destCtx.lineTo(x, y);
  6443. this.__originalLineTo(x, y);
  6444. };
  6445. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  6446. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  6447. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  6448. };
  6449. ctx.rect = function (x, y, width, height) {
  6450. destCtx.rect(x, y, width, height);
  6451. this.__originalRect(x, y, width, height);
  6452. };
  6453. ctx.closePath = function () {
  6454. destCtx.closePath();
  6455. this.__originalClosePath();
  6456. };
  6457. ctx.beginPath = function () {
  6458. destCtx.beginPath();
  6459. this.__originalBeginPath();
  6460. };
  6461. }
  6462. class CachedCanvases {
  6463. constructor(canvasFactory) {
  6464. this.canvasFactory = canvasFactory;
  6465. this.cache = Object.create(null);
  6466. }
  6467. getCanvas(id, width, height) {
  6468. let canvasEntry;
  6469. if (this.cache[id] !== undefined) {
  6470. canvasEntry = this.cache[id];
  6471. this.canvasFactory.reset(canvasEntry, width, height);
  6472. } else {
  6473. canvasEntry = this.canvasFactory.create(width, height);
  6474. this.cache[id] = canvasEntry;
  6475. }
  6476. return canvasEntry;
  6477. }
  6478. delete(id) {
  6479. delete this.cache[id];
  6480. }
  6481. clear() {
  6482. for (const id in this.cache) {
  6483. const canvasEntry = this.cache[id];
  6484. this.canvasFactory.destroy(canvasEntry);
  6485. delete this.cache[id];
  6486. }
  6487. }
  6488. }
  6489. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  6490. const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);
  6491. if (b === 0 && c === 0) {
  6492. const tlX = destX * a + tx;
  6493. const rTlX = Math.round(tlX);
  6494. const tlY = destY * d + ty;
  6495. const rTlY = Math.round(tlY);
  6496. const brX = (destX + destW) * a + tx;
  6497. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  6498. const brY = (destY + destH) * d + ty;
  6499. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  6500. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  6501. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  6502. ctx.setTransform(a, b, c, d, tx, ty);
  6503. return [rWidth, rHeight];
  6504. }
  6505. if (a === 0 && d === 0) {
  6506. const tlX = destY * c + tx;
  6507. const rTlX = Math.round(tlX);
  6508. const tlY = destX * b + ty;
  6509. const rTlY = Math.round(tlY);
  6510. const brX = (destY + destH) * c + tx;
  6511. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  6512. const brY = (destX + destW) * b + ty;
  6513. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  6514. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  6515. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  6516. ctx.setTransform(a, b, c, d, tx, ty);
  6517. return [rHeight, rWidth];
  6518. }
  6519. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  6520. const scaleX = Math.hypot(a, b);
  6521. const scaleY = Math.hypot(c, d);
  6522. return [scaleX * destW, scaleY * destH];
  6523. }
  6524. function compileType3Glyph(imgData) {
  6525. const {
  6526. width,
  6527. height
  6528. } = imgData;
  6529. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  6530. return null;
  6531. }
  6532. const POINT_TO_PROCESS_LIMIT = 1000;
  6533. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6534. const width1 = width + 1;
  6535. let points = new Uint8Array(width1 * (height + 1));
  6536. let i, j, j0;
  6537. const lineSize = width + 7 & ~7;
  6538. let data = new Uint8Array(lineSize * height),
  6539. pos = 0;
  6540. for (const elem of imgData.data) {
  6541. let mask = 128;
  6542. while (mask > 0) {
  6543. data[pos++] = elem & mask ? 0 : 255;
  6544. mask >>= 1;
  6545. }
  6546. }
  6547. let count = 0;
  6548. pos = 0;
  6549. if (data[pos] !== 0) {
  6550. points[0] = 1;
  6551. ++count;
  6552. }
  6553. for (j = 1; j < width; j++) {
  6554. if (data[pos] !== data[pos + 1]) {
  6555. points[j] = data[pos] ? 2 : 1;
  6556. ++count;
  6557. }
  6558. pos++;
  6559. }
  6560. if (data[pos] !== 0) {
  6561. points[j] = 2;
  6562. ++count;
  6563. }
  6564. for (i = 1; i < height; i++) {
  6565. pos = i * lineSize;
  6566. j0 = i * width1;
  6567. if (data[pos - lineSize] !== data[pos]) {
  6568. points[j0] = data[pos] ? 1 : 8;
  6569. ++count;
  6570. }
  6571. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6572. for (j = 1; j < width; j++) {
  6573. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  6574. if (POINT_TYPES[sum]) {
  6575. points[j0 + j] = POINT_TYPES[sum];
  6576. ++count;
  6577. }
  6578. pos++;
  6579. }
  6580. if (data[pos - lineSize] !== data[pos]) {
  6581. points[j0 + j] = data[pos] ? 2 : 4;
  6582. ++count;
  6583. }
  6584. if (count > POINT_TO_PROCESS_LIMIT) {
  6585. return null;
  6586. }
  6587. }
  6588. pos = lineSize * (height - 1);
  6589. j0 = i * width1;
  6590. if (data[pos] !== 0) {
  6591. points[j0] = 8;
  6592. ++count;
  6593. }
  6594. for (j = 1; j < width; j++) {
  6595. if (data[pos] !== data[pos + 1]) {
  6596. points[j0 + j] = data[pos] ? 4 : 8;
  6597. ++count;
  6598. }
  6599. pos++;
  6600. }
  6601. if (data[pos] !== 0) {
  6602. points[j0 + j] = 4;
  6603. ++count;
  6604. }
  6605. if (count > POINT_TO_PROCESS_LIMIT) {
  6606. return null;
  6607. }
  6608. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6609. const path = new Path2D();
  6610. for (i = 0; count && i <= height; i++) {
  6611. let p = i * width1;
  6612. const end = p + width;
  6613. while (p < end && !points[p]) {
  6614. p++;
  6615. }
  6616. if (p === end) {
  6617. continue;
  6618. }
  6619. path.moveTo(p % width1, i);
  6620. const p0 = p;
  6621. let type = points[p];
  6622. do {
  6623. const step = steps[type];
  6624. do {
  6625. p += step;
  6626. } while (!points[p]);
  6627. const pp = points[p];
  6628. if (pp !== 5 && pp !== 10) {
  6629. type = pp;
  6630. points[p] = 0;
  6631. } else {
  6632. type = pp & 0x33 * type >> 4;
  6633. points[p] &= type >> 2 | type << 2;
  6634. }
  6635. path.lineTo(p % width1, p / width1 | 0);
  6636. if (!points[p]) {
  6637. --count;
  6638. }
  6639. } while (p0 !== p);
  6640. --i;
  6641. }
  6642. data = null;
  6643. points = null;
  6644. const drawOutline = function (c) {
  6645. c.save();
  6646. c.scale(1 / width, -1 / height);
  6647. c.translate(0, -height);
  6648. c.fill(path);
  6649. c.beginPath();
  6650. c.restore();
  6651. };
  6652. return drawOutline;
  6653. }
  6654. class CanvasExtraState {
  6655. constructor(width, height) {
  6656. this.alphaIsShape = false;
  6657. this.fontSize = 0;
  6658. this.fontSizeScale = 1;
  6659. this.textMatrix = IDENTITY_MATRIX;
  6660. this.textMatrixScale = 1;
  6661. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6662. this.leading = 0;
  6663. this.x = 0;
  6664. this.y = 0;
  6665. this.lineX = 0;
  6666. this.lineY = 0;
  6667. this.charSpacing = 0;
  6668. this.wordSpacing = 0;
  6669. this.textHScale = 1;
  6670. this.textRenderingMode = TextRenderingMode.FILL;
  6671. this.textRise = 0;
  6672. this.fillColor = "#000000";
  6673. this.strokeColor = "#000000";
  6674. this.patternFill = false;
  6675. this.fillAlpha = 1;
  6676. this.strokeAlpha = 1;
  6677. this.lineWidth = 1;
  6678. this.activeSMask = null;
  6679. this.transferMaps = "none";
  6680. this.startNewPathAndClipBox([0, 0, width, height]);
  6681. }
  6682. clone() {
  6683. const clone = Object.create(this);
  6684. clone.clipBox = this.clipBox.slice();
  6685. return clone;
  6686. }
  6687. setCurrentPoint(x, y) {
  6688. this.x = x;
  6689. this.y = y;
  6690. }
  6691. updatePathMinMax(transform, x, y) {
  6692. [x, y] = Util.applyTransform([x, y], transform);
  6693. this.minX = Math.min(this.minX, x);
  6694. this.minY = Math.min(this.minY, y);
  6695. this.maxX = Math.max(this.maxX, x);
  6696. this.maxY = Math.max(this.maxY, y);
  6697. }
  6698. updateRectMinMax(transform, rect) {
  6699. const p1 = Util.applyTransform(rect, transform);
  6700. const p2 = Util.applyTransform(rect.slice(2), transform);
  6701. const p3 = Util.applyTransform([rect[0], rect[3]], transform);
  6702. const p4 = Util.applyTransform([rect[2], rect[1]], transform);
  6703. this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]);
  6704. this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]);
  6705. this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]);
  6706. this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]);
  6707. }
  6708. updateScalingPathMinMax(transform, minMax) {
  6709. Util.scaleMinMax(transform, minMax);
  6710. this.minX = Math.min(this.minX, minMax[0]);
  6711. this.minY = Math.min(this.minY, minMax[1]);
  6712. this.maxX = Math.max(this.maxX, minMax[2]);
  6713. this.maxY = Math.max(this.maxY, minMax[3]);
  6714. }
  6715. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  6716. const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax);
  6717. if (minMax) {
  6718. return;
  6719. }
  6720. this.updateRectMinMax(transform, box);
  6721. }
  6722. getPathBoundingBox(pathType = PathType.FILL, transform = null) {
  6723. const box = [this.minX, this.minY, this.maxX, this.maxY];
  6724. if (pathType === PathType.STROKE) {
  6725. if (!transform) {
  6726. unreachable("Stroke bounding box must include transform.");
  6727. }
  6728. const scale = Util.singularValueDecompose2dScale(transform);
  6729. const xStrokePad = scale[0] * this.lineWidth / 2;
  6730. const yStrokePad = scale[1] * this.lineWidth / 2;
  6731. box[0] -= xStrokePad;
  6732. box[1] -= yStrokePad;
  6733. box[2] += xStrokePad;
  6734. box[3] += yStrokePad;
  6735. }
  6736. return box;
  6737. }
  6738. updateClipFromPath() {
  6739. const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
  6740. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  6741. }
  6742. isEmptyClip() {
  6743. return this.minX === Infinity;
  6744. }
  6745. startNewPathAndClipBox(box) {
  6746. this.clipBox = box;
  6747. this.minX = Infinity;
  6748. this.minY = Infinity;
  6749. this.maxX = 0;
  6750. this.maxY = 0;
  6751. }
  6752. getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
  6753. return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  6754. }
  6755. }
  6756. function putBinaryImageData(ctx, imgData) {
  6757. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  6758. ctx.putImageData(imgData, 0, 0);
  6759. return;
  6760. }
  6761. const height = imgData.height,
  6762. width = imgData.width;
  6763. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6764. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6765. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6766. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6767. let srcPos = 0,
  6768. destPos;
  6769. const src = imgData.data;
  6770. const dest = chunkImgData.data;
  6771. let i, j, thisChunkHeight, elemsInThisChunk;
  6772. if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
  6773. const srcLength = src.byteLength;
  6774. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  6775. const dest32DataLength = dest32.length;
  6776. const fullSrcDiff = width + 7 >> 3;
  6777. const white = 0xffffffff;
  6778. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  6779. for (i = 0; i < totalChunks; i++) {
  6780. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6781. destPos = 0;
  6782. for (j = 0; j < thisChunkHeight; j++) {
  6783. const srcDiff = srcLength - srcPos;
  6784. let k = 0;
  6785. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6786. const kEndUnrolled = kEnd & ~7;
  6787. let mask = 0;
  6788. let srcByte = 0;
  6789. for (; k < kEndUnrolled; k += 8) {
  6790. srcByte = src[srcPos++];
  6791. dest32[destPos++] = srcByte & 128 ? white : black;
  6792. dest32[destPos++] = srcByte & 64 ? white : black;
  6793. dest32[destPos++] = srcByte & 32 ? white : black;
  6794. dest32[destPos++] = srcByte & 16 ? white : black;
  6795. dest32[destPos++] = srcByte & 8 ? white : black;
  6796. dest32[destPos++] = srcByte & 4 ? white : black;
  6797. dest32[destPos++] = srcByte & 2 ? white : black;
  6798. dest32[destPos++] = srcByte & 1 ? white : black;
  6799. }
  6800. for (; k < kEnd; k++) {
  6801. if (mask === 0) {
  6802. srcByte = src[srcPos++];
  6803. mask = 128;
  6804. }
  6805. dest32[destPos++] = srcByte & mask ? white : black;
  6806. mask >>= 1;
  6807. }
  6808. }
  6809. while (destPos < dest32DataLength) {
  6810. dest32[destPos++] = 0;
  6811. }
  6812. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6813. }
  6814. } else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
  6815. j = 0;
  6816. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6817. for (i = 0; i < fullChunks; i++) {
  6818. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6819. srcPos += elemsInThisChunk;
  6820. ctx.putImageData(chunkImgData, 0, j);
  6821. j += FULL_CHUNK_HEIGHT;
  6822. }
  6823. if (i < totalChunks) {
  6824. elemsInThisChunk = width * partialChunkHeight * 4;
  6825. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6826. ctx.putImageData(chunkImgData, 0, j);
  6827. }
  6828. } else if (imgData.kind === util_ImageKind.RGB_24BPP) {
  6829. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6830. elemsInThisChunk = width * thisChunkHeight;
  6831. for (i = 0; i < totalChunks; i++) {
  6832. if (i >= fullChunks) {
  6833. thisChunkHeight = partialChunkHeight;
  6834. elemsInThisChunk = width * thisChunkHeight;
  6835. }
  6836. destPos = 0;
  6837. for (j = elemsInThisChunk; j--;) {
  6838. dest[destPos++] = src[srcPos++];
  6839. dest[destPos++] = src[srcPos++];
  6840. dest[destPos++] = src[srcPos++];
  6841. dest[destPos++] = 255;
  6842. }
  6843. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6844. }
  6845. } else {
  6846. throw new Error(`bad image kind: ${imgData.kind}`);
  6847. }
  6848. }
  6849. function putBinaryImageMask(ctx, imgData) {
  6850. if (imgData.bitmap) {
  6851. ctx.drawImage(imgData.bitmap, 0, 0);
  6852. return;
  6853. }
  6854. const height = imgData.height,
  6855. width = imgData.width;
  6856. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6857. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6858. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6859. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6860. let srcPos = 0;
  6861. const src = imgData.data;
  6862. const dest = chunkImgData.data;
  6863. for (let i = 0; i < totalChunks; i++) {
  6864. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6865. ({
  6866. srcPos
  6867. } = convertBlackAndWhiteToRGBA({
  6868. src,
  6869. srcPos,
  6870. dest,
  6871. width,
  6872. height: thisChunkHeight,
  6873. nonBlackColor: 0
  6874. }));
  6875. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6876. }
  6877. }
  6878. function copyCtxState(sourceCtx, destCtx) {
  6879. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
  6880. for (const property of properties) {
  6881. if (sourceCtx[property] !== undefined) {
  6882. destCtx[property] = sourceCtx[property];
  6883. }
  6884. }
  6885. if (sourceCtx.setLineDash !== undefined) {
  6886. destCtx.setLineDash(sourceCtx.getLineDash());
  6887. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6888. }
  6889. }
  6890. function resetCtxToDefault(ctx) {
  6891. ctx.strokeStyle = ctx.fillStyle = "#000000";
  6892. ctx.fillRule = "nonzero";
  6893. ctx.globalAlpha = 1;
  6894. ctx.lineWidth = 1;
  6895. ctx.lineCap = "butt";
  6896. ctx.lineJoin = "miter";
  6897. ctx.miterLimit = 10;
  6898. ctx.globalCompositeOperation = "source-over";
  6899. ctx.font = "10px sans-serif";
  6900. if (ctx.setLineDash !== undefined) {
  6901. ctx.setLineDash([]);
  6902. ctx.lineDashOffset = 0;
  6903. }
  6904. if (!isNodeJS) {
  6905. const {
  6906. filter
  6907. } = ctx;
  6908. if (filter !== "none" && filter !== "") {
  6909. ctx.filter = "none";
  6910. }
  6911. }
  6912. }
  6913. function getImageSmoothingEnabled(transform, interpolate) {
  6914. if (interpolate) {
  6915. return true;
  6916. }
  6917. const scale = Util.singularValueDecompose2dScale(transform);
  6918. scale[0] = Math.fround(scale[0]);
  6919. scale[1] = Math.fround(scale[1]);
  6920. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS);
  6921. return scale[0] <= actualScale && scale[1] <= actualScale;
  6922. }
  6923. const LINE_CAP_STYLES = ["butt", "round", "square"];
  6924. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  6925. const NORMAL_CLIP = {};
  6926. const EO_CLIP = {};
  6927. class CanvasGraphics {
  6928. constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
  6929. optionalContentConfig,
  6930. markedContentStack = null
  6931. }, annotationCanvasMap, pageColors) {
  6932. this.ctx = canvasCtx;
  6933. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  6934. this.stateStack = [];
  6935. this.pendingClip = null;
  6936. this.pendingEOFill = false;
  6937. this.res = null;
  6938. this.xobjs = null;
  6939. this.commonObjs = commonObjs;
  6940. this.objs = objs;
  6941. this.canvasFactory = canvasFactory;
  6942. this.filterFactory = filterFactory;
  6943. this.groupStack = [];
  6944. this.processingType3 = null;
  6945. this.baseTransform = null;
  6946. this.baseTransformStack = [];
  6947. this.groupLevel = 0;
  6948. this.smaskStack = [];
  6949. this.smaskCounter = 0;
  6950. this.tempSMask = null;
  6951. this.suspendedCtx = null;
  6952. this.contentVisible = true;
  6953. this.markedContentStack = markedContentStack || [];
  6954. this.optionalContentConfig = optionalContentConfig;
  6955. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  6956. this.cachedPatterns = new Map();
  6957. this.annotationCanvasMap = annotationCanvasMap;
  6958. this.viewportScale = 1;
  6959. this.outputScaleX = 1;
  6960. this.outputScaleY = 1;
  6961. this.pageColors = pageColors;
  6962. this._cachedScaleForStroking = [-1, 0];
  6963. this._cachedGetSinglePixelWidth = null;
  6964. this._cachedBitmapsMap = new Map();
  6965. }
  6966. getObject(data, fallback = null) {
  6967. if (typeof data === "string") {
  6968. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  6969. }
  6970. return fallback;
  6971. }
  6972. beginDrawing({
  6973. transform,
  6974. viewport,
  6975. transparency = false,
  6976. background = null
  6977. }) {
  6978. const width = this.ctx.canvas.width;
  6979. const height = this.ctx.canvas.height;
  6980. const savedFillStyle = this.ctx.fillStyle;
  6981. this.ctx.fillStyle = background || "#ffffff";
  6982. this.ctx.fillRect(0, 0, width, height);
  6983. this.ctx.fillStyle = savedFillStyle;
  6984. if (transparency) {
  6985. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  6986. this.compositeCtx = this.ctx;
  6987. this.transparentCanvas = transparentCanvas.canvas;
  6988. this.ctx = transparentCanvas.context;
  6989. this.ctx.save();
  6990. this.ctx.transform(...getCurrentTransform(this.compositeCtx));
  6991. }
  6992. this.ctx.save();
  6993. resetCtxToDefault(this.ctx);
  6994. if (transform) {
  6995. this.ctx.transform(...transform);
  6996. this.outputScaleX = transform[0];
  6997. this.outputScaleY = transform[0];
  6998. }
  6999. this.ctx.transform(...viewport.transform);
  7000. this.viewportScale = viewport.scale;
  7001. this.baseTransform = getCurrentTransform(this.ctx);
  7002. }
  7003. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  7004. const argsArray = operatorList.argsArray;
  7005. const fnArray = operatorList.fnArray;
  7006. let i = executionStartIdx || 0;
  7007. const argsArrayLen = argsArray.length;
  7008. if (argsArrayLen === i) {
  7009. return i;
  7010. }
  7011. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  7012. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  7013. let steps = 0;
  7014. const commonObjs = this.commonObjs;
  7015. const objs = this.objs;
  7016. let fnId;
  7017. while (true) {
  7018. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  7019. stepper.breakIt(i, continueCallback);
  7020. return i;
  7021. }
  7022. fnId = fnArray[i];
  7023. if (fnId !== OPS.dependency) {
  7024. this[fnId].apply(this, argsArray[i]);
  7025. } else {
  7026. for (const depObjId of argsArray[i]) {
  7027. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  7028. if (!objsPool.has(depObjId)) {
  7029. objsPool.get(depObjId, continueCallback);
  7030. return i;
  7031. }
  7032. }
  7033. }
  7034. i++;
  7035. if (i === argsArrayLen) {
  7036. return i;
  7037. }
  7038. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  7039. if (Date.now() > endTime) {
  7040. continueCallback();
  7041. return i;
  7042. }
  7043. steps = 0;
  7044. }
  7045. }
  7046. }
  7047. #restoreInitialState() {
  7048. while (this.stateStack.length || this.inSMaskMode) {
  7049. this.restore();
  7050. }
  7051. this.current.activeSMask = null;
  7052. this.ctx.restore();
  7053. if (this.transparentCanvas) {
  7054. this.ctx = this.compositeCtx;
  7055. this.ctx.save();
  7056. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7057. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  7058. this.ctx.restore();
  7059. this.transparentCanvas = null;
  7060. }
  7061. }
  7062. endDrawing() {
  7063. this.#restoreInitialState();
  7064. this.cachedCanvases.clear();
  7065. this.cachedPatterns.clear();
  7066. for (const cache of this._cachedBitmapsMap.values()) {
  7067. for (const canvas of cache.values()) {
  7068. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  7069. canvas.width = canvas.height = 0;
  7070. }
  7071. }
  7072. cache.clear();
  7073. }
  7074. this._cachedBitmapsMap.clear();
  7075. this.#drawFilter();
  7076. }
  7077. #drawFilter() {
  7078. if (this.pageColors) {
  7079. const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
  7080. if (hcmFilterId !== "none") {
  7081. const savedFilter = this.ctx.filter;
  7082. this.ctx.filter = hcmFilterId;
  7083. this.ctx.drawImage(this.ctx.canvas, 0, 0);
  7084. this.ctx.filter = savedFilter;
  7085. }
  7086. }
  7087. }
  7088. _scaleImage(img, inverseTransform) {
  7089. const width = img.width ?? img.displayWidth;
  7090. const height = img.height ?? img.displayHeight;
  7091. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  7092. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  7093. let paintWidth = width,
  7094. paintHeight = height;
  7095. let tmpCanvasId = "prescale1";
  7096. let tmpCanvas, tmpCtx;
  7097. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  7098. let newWidth = paintWidth,
  7099. newHeight = paintHeight;
  7100. if (widthScale > 2 && paintWidth > 1) {
  7101. newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
  7102. widthScale /= paintWidth / newWidth;
  7103. }
  7104. if (heightScale > 2 && paintHeight > 1) {
  7105. newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
  7106. heightScale /= paintHeight / newHeight;
  7107. }
  7108. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  7109. tmpCtx = tmpCanvas.context;
  7110. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7111. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  7112. img = tmpCanvas.canvas;
  7113. paintWidth = newWidth;
  7114. paintHeight = newHeight;
  7115. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  7116. }
  7117. return {
  7118. img,
  7119. paintWidth,
  7120. paintHeight
  7121. };
  7122. }
  7123. _createMaskCanvas(img) {
  7124. const ctx = this.ctx;
  7125. const {
  7126. width,
  7127. height
  7128. } = img;
  7129. const fillColor = this.current.fillColor;
  7130. const isPatternFill = this.current.patternFill;
  7131. const currentTransform = getCurrentTransform(ctx);
  7132. let cache, cacheKey, scaled, maskCanvas;
  7133. if ((img.bitmap || img.data) && img.count > 1) {
  7134. const mainKey = img.bitmap || img.data.buffer;
  7135. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  7136. cache = this._cachedBitmapsMap.get(mainKey);
  7137. if (!cache) {
  7138. cache = new Map();
  7139. this._cachedBitmapsMap.set(mainKey, cache);
  7140. }
  7141. const cachedImage = cache.get(cacheKey);
  7142. if (cachedImage && !isPatternFill) {
  7143. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  7144. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  7145. return {
  7146. canvas: cachedImage,
  7147. offsetX,
  7148. offsetY
  7149. };
  7150. }
  7151. scaled = cachedImage;
  7152. }
  7153. if (!scaled) {
  7154. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  7155. putBinaryImageMask(maskCanvas.context, img);
  7156. }
  7157. let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  7158. maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  7159. const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox([0, 0, width, height], maskToCanvas);
  7160. const drawnWidth = Math.round(maxX - minX) || 1;
  7161. const drawnHeight = Math.round(maxY - minY) || 1;
  7162. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  7163. const fillCtx = fillCanvas.context;
  7164. const offsetX = minX;
  7165. const offsetY = minY;
  7166. fillCtx.translate(-offsetX, -offsetY);
  7167. fillCtx.transform(...maskToCanvas);
  7168. if (!scaled) {
  7169. scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
  7170. scaled = scaled.img;
  7171. if (cache && isPatternFill) {
  7172. cache.set(cacheKey, scaled);
  7173. }
  7174. }
  7175. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
  7176. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  7177. fillCtx.globalCompositeOperation = "source-in";
  7178. const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  7179. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor;
  7180. fillCtx.fillRect(0, 0, width, height);
  7181. if (cache && !isPatternFill) {
  7182. this.cachedCanvases.delete("fillCanvas");
  7183. cache.set(cacheKey, fillCanvas.canvas);
  7184. }
  7185. return {
  7186. canvas: fillCanvas.canvas,
  7187. offsetX: Math.round(offsetX),
  7188. offsetY: Math.round(offsetY)
  7189. };
  7190. }
  7191. setLineWidth(width) {
  7192. if (width !== this.current.lineWidth) {
  7193. this._cachedScaleForStroking[0] = -1;
  7194. }
  7195. this.current.lineWidth = width;
  7196. this.ctx.lineWidth = width;
  7197. }
  7198. setLineCap(style) {
  7199. this.ctx.lineCap = LINE_CAP_STYLES[style];
  7200. }
  7201. setLineJoin(style) {
  7202. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  7203. }
  7204. setMiterLimit(limit) {
  7205. this.ctx.miterLimit = limit;
  7206. }
  7207. setDash(dashArray, dashPhase) {
  7208. const ctx = this.ctx;
  7209. if (ctx.setLineDash !== undefined) {
  7210. ctx.setLineDash(dashArray);
  7211. ctx.lineDashOffset = dashPhase;
  7212. }
  7213. }
  7214. setRenderingIntent(intent) {}
  7215. setFlatness(flatness) {}
  7216. setGState(states) {
  7217. for (const [key, value] of states) {
  7218. switch (key) {
  7219. case "LW":
  7220. this.setLineWidth(value);
  7221. break;
  7222. case "LC":
  7223. this.setLineCap(value);
  7224. break;
  7225. case "LJ":
  7226. this.setLineJoin(value);
  7227. break;
  7228. case "ML":
  7229. this.setMiterLimit(value);
  7230. break;
  7231. case "D":
  7232. this.setDash(value[0], value[1]);
  7233. break;
  7234. case "RI":
  7235. this.setRenderingIntent(value);
  7236. break;
  7237. case "FL":
  7238. this.setFlatness(value);
  7239. break;
  7240. case "Font":
  7241. this.setFont(value[0], value[1]);
  7242. break;
  7243. case "CA":
  7244. this.current.strokeAlpha = value;
  7245. break;
  7246. case "ca":
  7247. this.current.fillAlpha = value;
  7248. this.ctx.globalAlpha = value;
  7249. break;
  7250. case "BM":
  7251. this.ctx.globalCompositeOperation = value;
  7252. break;
  7253. case "SMask":
  7254. this.current.activeSMask = value ? this.tempSMask : null;
  7255. this.tempSMask = null;
  7256. this.checkSMaskState();
  7257. break;
  7258. case "TR":
  7259. this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
  7260. break;
  7261. }
  7262. }
  7263. }
  7264. get inSMaskMode() {
  7265. return !!this.suspendedCtx;
  7266. }
  7267. checkSMaskState() {
  7268. const inSMaskMode = this.inSMaskMode;
  7269. if (this.current.activeSMask && !inSMaskMode) {
  7270. this.beginSMaskMode();
  7271. } else if (!this.current.activeSMask && inSMaskMode) {
  7272. this.endSMaskMode();
  7273. }
  7274. }
  7275. beginSMaskMode() {
  7276. if (this.inSMaskMode) {
  7277. throw new Error("beginSMaskMode called while already in smask mode");
  7278. }
  7279. const drawnWidth = this.ctx.canvas.width;
  7280. const drawnHeight = this.ctx.canvas.height;
  7281. const cacheId = "smaskGroupAt" + this.groupLevel;
  7282. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  7283. this.suspendedCtx = this.ctx;
  7284. this.ctx = scratchCanvas.context;
  7285. const ctx = this.ctx;
  7286. ctx.setTransform(...getCurrentTransform(this.suspendedCtx));
  7287. copyCtxState(this.suspendedCtx, ctx);
  7288. mirrorContextOperations(ctx, this.suspendedCtx);
  7289. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  7290. }
  7291. endSMaskMode() {
  7292. if (!this.inSMaskMode) {
  7293. throw new Error("endSMaskMode called while not in smask mode");
  7294. }
  7295. this.ctx._removeMirroring();
  7296. copyCtxState(this.ctx, this.suspendedCtx);
  7297. this.ctx = this.suspendedCtx;
  7298. this.suspendedCtx = null;
  7299. }
  7300. compose(dirtyBox) {
  7301. if (!this.current.activeSMask) {
  7302. return;
  7303. }
  7304. if (!dirtyBox) {
  7305. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  7306. } else {
  7307. dirtyBox[0] = Math.floor(dirtyBox[0]);
  7308. dirtyBox[1] = Math.floor(dirtyBox[1]);
  7309. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  7310. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  7311. }
  7312. const smask = this.current.activeSMask;
  7313. const suspendedCtx = this.suspendedCtx;
  7314. this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  7315. this.ctx.save();
  7316. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7317. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  7318. this.ctx.restore();
  7319. }
  7320. composeSMask(ctx, smask, layerCtx, layerBox) {
  7321. const layerOffsetX = layerBox[0];
  7322. const layerOffsetY = layerBox[1];
  7323. const layerWidth = layerBox[2] - layerOffsetX;
  7324. const layerHeight = layerBox[3] - layerOffsetY;
  7325. if (layerWidth === 0 || layerHeight === 0) {
  7326. return;
  7327. }
  7328. this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  7329. ctx.save();
  7330. ctx.globalAlpha = 1;
  7331. ctx.globalCompositeOperation = "source-over";
  7332. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7333. ctx.drawImage(layerCtx.canvas, 0, 0);
  7334. ctx.restore();
  7335. }
  7336. genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  7337. let maskCanvas = maskCtx.canvas;
  7338. let maskX = layerOffsetX - maskOffsetX;
  7339. let maskY = layerOffsetY - maskOffsetY;
  7340. if (backdrop) {
  7341. const backdropRGB = Util.makeHexColor(...backdrop);
  7342. if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
  7343. const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
  7344. const ctx = canvas.context;
  7345. ctx.drawImage(maskCanvas, -maskX, -maskY);
  7346. ctx.globalCompositeOperation = "destination-atop";
  7347. ctx.fillStyle = backdropRGB;
  7348. ctx.fillRect(0, 0, width, height);
  7349. ctx.globalCompositeOperation = "source-over";
  7350. maskCanvas = canvas.canvas;
  7351. maskX = maskY = 0;
  7352. } else {
  7353. maskCtx.save();
  7354. maskCtx.globalAlpha = 1;
  7355. maskCtx.setTransform(1, 0, 0, 1, 0, 0);
  7356. const clip = new Path2D();
  7357. clip.rect(maskX, maskY, width, height);
  7358. maskCtx.clip(clip);
  7359. maskCtx.globalCompositeOperation = "destination-atop";
  7360. maskCtx.fillStyle = backdropRGB;
  7361. maskCtx.fillRect(maskX, maskY, width, height);
  7362. maskCtx.restore();
  7363. }
  7364. }
  7365. layerCtx.save();
  7366. layerCtx.globalAlpha = 1;
  7367. layerCtx.setTransform(1, 0, 0, 1, 0, 0);
  7368. if (subtype === "Alpha" && transferMap) {
  7369. layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
  7370. } else if (subtype === "Luminosity") {
  7371. layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
  7372. }
  7373. const clip = new Path2D();
  7374. clip.rect(layerOffsetX, layerOffsetY, width, height);
  7375. layerCtx.clip(clip);
  7376. layerCtx.globalCompositeOperation = "destination-in";
  7377. layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
  7378. layerCtx.restore();
  7379. }
  7380. save() {
  7381. if (this.inSMaskMode) {
  7382. copyCtxState(this.ctx, this.suspendedCtx);
  7383. this.suspendedCtx.save();
  7384. } else {
  7385. this.ctx.save();
  7386. }
  7387. const old = this.current;
  7388. this.stateStack.push(old);
  7389. this.current = old.clone();
  7390. }
  7391. restore() {
  7392. if (this.stateStack.length === 0 && this.inSMaskMode) {
  7393. this.endSMaskMode();
  7394. }
  7395. if (this.stateStack.length !== 0) {
  7396. this.current = this.stateStack.pop();
  7397. if (this.inSMaskMode) {
  7398. this.suspendedCtx.restore();
  7399. copyCtxState(this.suspendedCtx, this.ctx);
  7400. } else {
  7401. this.ctx.restore();
  7402. }
  7403. this.checkSMaskState();
  7404. this.pendingClip = null;
  7405. this._cachedScaleForStroking[0] = -1;
  7406. this._cachedGetSinglePixelWidth = null;
  7407. }
  7408. }
  7409. transform(a, b, c, d, e, f) {
  7410. this.ctx.transform(a, b, c, d, e, f);
  7411. this._cachedScaleForStroking[0] = -1;
  7412. this._cachedGetSinglePixelWidth = null;
  7413. }
  7414. constructPath(ops, args, minMax) {
  7415. const ctx = this.ctx;
  7416. const current = this.current;
  7417. let x = current.x,
  7418. y = current.y;
  7419. let startX, startY;
  7420. const currentTransform = getCurrentTransform(ctx);
  7421. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  7422. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  7423. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7424. switch (ops[i] | 0) {
  7425. case OPS.rectangle:
  7426. x = args[j++];
  7427. y = args[j++];
  7428. const width = args[j++];
  7429. const height = args[j++];
  7430. const xw = x + width;
  7431. const yh = y + height;
  7432. ctx.moveTo(x, y);
  7433. if (width === 0 || height === 0) {
  7434. ctx.lineTo(xw, yh);
  7435. } else {
  7436. ctx.lineTo(xw, y);
  7437. ctx.lineTo(xw, yh);
  7438. ctx.lineTo(x, yh);
  7439. }
  7440. if (!isScalingMatrix) {
  7441. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  7442. }
  7443. ctx.closePath();
  7444. break;
  7445. case OPS.moveTo:
  7446. x = args[j++];
  7447. y = args[j++];
  7448. ctx.moveTo(x, y);
  7449. if (!isScalingMatrix) {
  7450. current.updatePathMinMax(currentTransform, x, y);
  7451. }
  7452. break;
  7453. case OPS.lineTo:
  7454. x = args[j++];
  7455. y = args[j++];
  7456. ctx.lineTo(x, y);
  7457. if (!isScalingMatrix) {
  7458. current.updatePathMinMax(currentTransform, x, y);
  7459. }
  7460. break;
  7461. case OPS.curveTo:
  7462. startX = x;
  7463. startY = y;
  7464. x = args[j + 4];
  7465. y = args[j + 5];
  7466. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  7467. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  7468. j += 6;
  7469. break;
  7470. case OPS.curveTo2:
  7471. startX = x;
  7472. startY = y;
  7473. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  7474. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  7475. x = args[j + 2];
  7476. y = args[j + 3];
  7477. j += 4;
  7478. break;
  7479. case OPS.curveTo3:
  7480. startX = x;
  7481. startY = y;
  7482. x = args[j + 2];
  7483. y = args[j + 3];
  7484. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7485. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  7486. j += 4;
  7487. break;
  7488. case OPS.closePath:
  7489. ctx.closePath();
  7490. break;
  7491. }
  7492. }
  7493. if (isScalingMatrix) {
  7494. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  7495. }
  7496. current.setCurrentPoint(x, y);
  7497. }
  7498. closePath() {
  7499. this.ctx.closePath();
  7500. }
  7501. stroke(consumePath = true) {
  7502. const ctx = this.ctx;
  7503. const strokeColor = this.current.strokeColor;
  7504. ctx.globalAlpha = this.current.strokeAlpha;
  7505. if (this.contentVisible) {
  7506. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  7507. ctx.save();
  7508. ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
  7509. this.rescaleAndStroke(false);
  7510. ctx.restore();
  7511. } else {
  7512. this.rescaleAndStroke(true);
  7513. }
  7514. }
  7515. if (consumePath) {
  7516. this.consumePath(this.current.getClippedPathBoundingBox());
  7517. }
  7518. ctx.globalAlpha = this.current.fillAlpha;
  7519. }
  7520. closeStroke() {
  7521. this.closePath();
  7522. this.stroke();
  7523. }
  7524. fill(consumePath = true) {
  7525. const ctx = this.ctx;
  7526. const fillColor = this.current.fillColor;
  7527. const isPatternFill = this.current.patternFill;
  7528. let needRestore = false;
  7529. if (isPatternFill) {
  7530. ctx.save();
  7531. ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  7532. needRestore = true;
  7533. }
  7534. const intersect = this.current.getClippedPathBoundingBox();
  7535. if (this.contentVisible && intersect !== null) {
  7536. if (this.pendingEOFill) {
  7537. ctx.fill("evenodd");
  7538. this.pendingEOFill = false;
  7539. } else {
  7540. ctx.fill();
  7541. }
  7542. }
  7543. if (needRestore) {
  7544. ctx.restore();
  7545. }
  7546. if (consumePath) {
  7547. this.consumePath(intersect);
  7548. }
  7549. }
  7550. eoFill() {
  7551. this.pendingEOFill = true;
  7552. this.fill();
  7553. }
  7554. fillStroke() {
  7555. this.fill(false);
  7556. this.stroke(false);
  7557. this.consumePath();
  7558. }
  7559. eoFillStroke() {
  7560. this.pendingEOFill = true;
  7561. this.fillStroke();
  7562. }
  7563. closeFillStroke() {
  7564. this.closePath();
  7565. this.fillStroke();
  7566. }
  7567. closeEOFillStroke() {
  7568. this.pendingEOFill = true;
  7569. this.closePath();
  7570. this.fillStroke();
  7571. }
  7572. endPath() {
  7573. this.consumePath();
  7574. }
  7575. clip() {
  7576. this.pendingClip = NORMAL_CLIP;
  7577. }
  7578. eoClip() {
  7579. this.pendingClip = EO_CLIP;
  7580. }
  7581. beginText() {
  7582. this.current.textMatrix = IDENTITY_MATRIX;
  7583. this.current.textMatrixScale = 1;
  7584. this.current.x = this.current.lineX = 0;
  7585. this.current.y = this.current.lineY = 0;
  7586. }
  7587. endText() {
  7588. const paths = this.pendingTextPaths;
  7589. const ctx = this.ctx;
  7590. if (paths === undefined) {
  7591. ctx.beginPath();
  7592. return;
  7593. }
  7594. ctx.save();
  7595. ctx.beginPath();
  7596. for (const path of paths) {
  7597. ctx.setTransform(...path.transform);
  7598. ctx.translate(path.x, path.y);
  7599. path.addToPath(ctx, path.fontSize);
  7600. }
  7601. ctx.restore();
  7602. ctx.clip();
  7603. ctx.beginPath();
  7604. delete this.pendingTextPaths;
  7605. }
  7606. setCharSpacing(spacing) {
  7607. this.current.charSpacing = spacing;
  7608. }
  7609. setWordSpacing(spacing) {
  7610. this.current.wordSpacing = spacing;
  7611. }
  7612. setHScale(scale) {
  7613. this.current.textHScale = scale / 100;
  7614. }
  7615. setLeading(leading) {
  7616. this.current.leading = -leading;
  7617. }
  7618. setFont(fontRefName, size) {
  7619. const fontObj = this.commonObjs.get(fontRefName);
  7620. const current = this.current;
  7621. if (!fontObj) {
  7622. throw new Error(`Can't find font for ${fontRefName}`);
  7623. }
  7624. current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
  7625. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  7626. warn("Invalid font matrix for font " + fontRefName);
  7627. }
  7628. if (size < 0) {
  7629. size = -size;
  7630. current.fontDirection = -1;
  7631. } else {
  7632. current.fontDirection = 1;
  7633. }
  7634. this.current.font = fontObj;
  7635. this.current.fontSize = size;
  7636. if (fontObj.isType3Font) {
  7637. return;
  7638. }
  7639. const name = fontObj.loadedName || "sans-serif";
  7640. const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
  7641. let bold = "normal";
  7642. if (fontObj.black) {
  7643. bold = "900";
  7644. } else if (fontObj.bold) {
  7645. bold = "bold";
  7646. }
  7647. const italic = fontObj.italic ? "italic" : "normal";
  7648. let browserFontSize = size;
  7649. if (size < MIN_FONT_SIZE) {
  7650. browserFontSize = MIN_FONT_SIZE;
  7651. } else if (size > MAX_FONT_SIZE) {
  7652. browserFontSize = MAX_FONT_SIZE;
  7653. }
  7654. this.current.fontSizeScale = size / browserFontSize;
  7655. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  7656. }
  7657. setTextRenderingMode(mode) {
  7658. this.current.textRenderingMode = mode;
  7659. }
  7660. setTextRise(rise) {
  7661. this.current.textRise = rise;
  7662. }
  7663. moveText(x, y) {
  7664. this.current.x = this.current.lineX += x;
  7665. this.current.y = this.current.lineY += y;
  7666. }
  7667. setLeadingMoveText(x, y) {
  7668. this.setLeading(-y);
  7669. this.moveText(x, y);
  7670. }
  7671. setTextMatrix(a, b, c, d, e, f) {
  7672. this.current.textMatrix = [a, b, c, d, e, f];
  7673. this.current.textMatrixScale = Math.hypot(a, b);
  7674. this.current.x = this.current.lineX = 0;
  7675. this.current.y = this.current.lineY = 0;
  7676. }
  7677. nextLine() {
  7678. this.moveText(0, this.current.leading);
  7679. }
  7680. paintChar(character, x, y, patternTransform) {
  7681. const ctx = this.ctx;
  7682. const current = this.current;
  7683. const font = current.font;
  7684. const textRenderingMode = current.textRenderingMode;
  7685. const fontSize = current.fontSize / current.fontSizeScale;
  7686. const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7687. const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  7688. const patternFill = current.patternFill && !font.missingFile;
  7689. let addToPath;
  7690. if (font.disableFontFace || isAddToPathSet || patternFill) {
  7691. addToPath = font.getPathGenerator(this.commonObjs, character);
  7692. }
  7693. if (font.disableFontFace || patternFill) {
  7694. ctx.save();
  7695. ctx.translate(x, y);
  7696. ctx.beginPath();
  7697. addToPath(ctx, fontSize);
  7698. if (patternTransform) {
  7699. ctx.setTransform(...patternTransform);
  7700. }
  7701. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7702. ctx.fill();
  7703. }
  7704. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7705. ctx.stroke();
  7706. }
  7707. ctx.restore();
  7708. } else {
  7709. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7710. ctx.fillText(character, x, y);
  7711. }
  7712. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7713. ctx.strokeText(character, x, y);
  7714. }
  7715. }
  7716. if (isAddToPathSet) {
  7717. const paths = this.pendingTextPaths ||= [];
  7718. paths.push({
  7719. transform: getCurrentTransform(ctx),
  7720. x,
  7721. y,
  7722. fontSize,
  7723. addToPath
  7724. });
  7725. }
  7726. }
  7727. get isFontSubpixelAAEnabled() {
  7728. const {
  7729. context: ctx
  7730. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  7731. ctx.scale(1.5, 1);
  7732. ctx.fillText("I", 0, 10);
  7733. const data = ctx.getImageData(0, 0, 10, 10).data;
  7734. let enabled = false;
  7735. for (let i = 3; i < data.length; i += 4) {
  7736. if (data[i] > 0 && data[i] < 255) {
  7737. enabled = true;
  7738. break;
  7739. }
  7740. }
  7741. return shadow(this, "isFontSubpixelAAEnabled", enabled);
  7742. }
  7743. showText(glyphs) {
  7744. const current = this.current;
  7745. const font = current.font;
  7746. if (font.isType3Font) {
  7747. return this.showType3Text(glyphs);
  7748. }
  7749. const fontSize = current.fontSize;
  7750. if (fontSize === 0) {
  7751. return undefined;
  7752. }
  7753. const ctx = this.ctx;
  7754. const fontSizeScale = current.fontSizeScale;
  7755. const charSpacing = current.charSpacing;
  7756. const wordSpacing = current.wordSpacing;
  7757. const fontDirection = current.fontDirection;
  7758. const textHScale = current.textHScale * fontDirection;
  7759. const glyphsLength = glyphs.length;
  7760. const vertical = font.vertical;
  7761. const spacingDir = vertical ? 1 : -1;
  7762. const defaultVMetrics = font.defaultVMetrics;
  7763. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  7764. const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  7765. ctx.save();
  7766. ctx.transform(...current.textMatrix);
  7767. ctx.translate(current.x, current.y + current.textRise);
  7768. if (fontDirection > 0) {
  7769. ctx.scale(textHScale, -1);
  7770. } else {
  7771. ctx.scale(textHScale, 1);
  7772. }
  7773. let patternTransform;
  7774. if (current.patternFill) {
  7775. ctx.save();
  7776. const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  7777. patternTransform = getCurrentTransform(ctx);
  7778. ctx.restore();
  7779. ctx.fillStyle = pattern;
  7780. }
  7781. let lineWidth = current.lineWidth;
  7782. const scale = current.textMatrixScale;
  7783. if (scale === 0 || lineWidth === 0) {
  7784. const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7785. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7786. lineWidth = this.getSinglePixelWidth();
  7787. }
  7788. } else {
  7789. lineWidth /= scale;
  7790. }
  7791. if (fontSizeScale !== 1.0) {
  7792. ctx.scale(fontSizeScale, fontSizeScale);
  7793. lineWidth /= fontSizeScale;
  7794. }
  7795. ctx.lineWidth = lineWidth;
  7796. if (font.isInvalidPDFjsFont) {
  7797. const chars = [];
  7798. let width = 0;
  7799. for (const glyph of glyphs) {
  7800. chars.push(glyph.unicode);
  7801. width += glyph.width;
  7802. }
  7803. ctx.fillText(chars.join(""), 0, 0);
  7804. current.x += width * widthAdvanceScale * textHScale;
  7805. ctx.restore();
  7806. this.compose();
  7807. return undefined;
  7808. }
  7809. let x = 0,
  7810. i;
  7811. for (i = 0; i < glyphsLength; ++i) {
  7812. const glyph = glyphs[i];
  7813. if (typeof glyph === "number") {
  7814. x += spacingDir * glyph * fontSize / 1000;
  7815. continue;
  7816. }
  7817. let restoreNeeded = false;
  7818. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7819. const character = glyph.fontChar;
  7820. const accent = glyph.accent;
  7821. let scaledX, scaledY;
  7822. let width = glyph.width;
  7823. if (vertical) {
  7824. const vmetric = glyph.vmetric || defaultVMetrics;
  7825. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  7826. const vy = vmetric[2] * widthAdvanceScale;
  7827. width = vmetric ? -vmetric[0] : width;
  7828. scaledX = vx / fontSizeScale;
  7829. scaledY = (x + vy) / fontSizeScale;
  7830. } else {
  7831. scaledX = x / fontSizeScale;
  7832. scaledY = 0;
  7833. }
  7834. if (font.remeasure && width > 0) {
  7835. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  7836. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7837. const characterScaleX = width / measuredWidth;
  7838. restoreNeeded = true;
  7839. ctx.save();
  7840. ctx.scale(characterScaleX, 1);
  7841. scaledX /= characterScaleX;
  7842. } else if (width !== measuredWidth) {
  7843. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  7844. }
  7845. }
  7846. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  7847. if (simpleFillText && !accent) {
  7848. ctx.fillText(character, scaledX, scaledY);
  7849. } else {
  7850. this.paintChar(character, scaledX, scaledY, patternTransform);
  7851. if (accent) {
  7852. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  7853. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  7854. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  7855. }
  7856. }
  7857. }
  7858. const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
  7859. x += charWidth;
  7860. if (restoreNeeded) {
  7861. ctx.restore();
  7862. }
  7863. }
  7864. if (vertical) {
  7865. current.y -= x;
  7866. } else {
  7867. current.x += x * textHScale;
  7868. }
  7869. ctx.restore();
  7870. this.compose();
  7871. return undefined;
  7872. }
  7873. showType3Text(glyphs) {
  7874. const ctx = this.ctx;
  7875. const current = this.current;
  7876. const font = current.font;
  7877. const fontSize = current.fontSize;
  7878. const fontDirection = current.fontDirection;
  7879. const spacingDir = font.vertical ? 1 : -1;
  7880. const charSpacing = current.charSpacing;
  7881. const wordSpacing = current.wordSpacing;
  7882. const textHScale = current.textHScale * fontDirection;
  7883. const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7884. const glyphsLength = glyphs.length;
  7885. const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7886. let i, glyph, width, spacingLength;
  7887. if (isTextInvisible || fontSize === 0) {
  7888. return;
  7889. }
  7890. this._cachedScaleForStroking[0] = -1;
  7891. this._cachedGetSinglePixelWidth = null;
  7892. ctx.save();
  7893. ctx.transform(...current.textMatrix);
  7894. ctx.translate(current.x, current.y);
  7895. ctx.scale(textHScale, fontDirection);
  7896. for (i = 0; i < glyphsLength; ++i) {
  7897. glyph = glyphs[i];
  7898. if (typeof glyph === "number") {
  7899. spacingLength = spacingDir * glyph * fontSize / 1000;
  7900. this.ctx.translate(spacingLength, 0);
  7901. current.x += spacingLength * textHScale;
  7902. continue;
  7903. }
  7904. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7905. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  7906. if (!operatorList) {
  7907. warn(`Type3 character "${glyph.operatorListId}" is not available.`);
  7908. continue;
  7909. }
  7910. if (this.contentVisible) {
  7911. this.processingType3 = glyph;
  7912. this.save();
  7913. ctx.scale(fontSize, fontSize);
  7914. ctx.transform(...fontMatrix);
  7915. this.executeOperatorList(operatorList);
  7916. this.restore();
  7917. }
  7918. const transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  7919. width = transformed[0] * fontSize + spacing;
  7920. ctx.translate(width, 0);
  7921. current.x += width * textHScale;
  7922. }
  7923. ctx.restore();
  7924. this.processingType3 = null;
  7925. }
  7926. setCharWidth(xWidth, yWidth) {}
  7927. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7928. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7929. this.ctx.clip();
  7930. this.endPath();
  7931. }
  7932. getColorN_Pattern(IR) {
  7933. let pattern;
  7934. if (IR[0] === "TilingPattern") {
  7935. const color = IR[1];
  7936. const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
  7937. const canvasGraphicsFactory = {
  7938. createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  7939. optionalContentConfig: this.optionalContentConfig,
  7940. markedContentStack: this.markedContentStack
  7941. })
  7942. };
  7943. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7944. } else {
  7945. pattern = this._getPattern(IR[1], IR[2]);
  7946. }
  7947. return pattern;
  7948. }
  7949. setStrokeColorN() {
  7950. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7951. }
  7952. setFillColorN() {
  7953. this.current.fillColor = this.getColorN_Pattern(arguments);
  7954. this.current.patternFill = true;
  7955. }
  7956. setStrokeRGBColor(r, g, b) {
  7957. this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(r, g, b);
  7958. }
  7959. setStrokeTransparent() {
  7960. this.ctx.strokeStyle = this.current.strokeColor = "transparent";
  7961. }
  7962. setFillRGBColor(r, g, b) {
  7963. this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b);
  7964. this.current.patternFill = false;
  7965. }
  7966. setFillTransparent() {
  7967. this.ctx.fillStyle = this.current.fillColor = "transparent";
  7968. this.current.patternFill = false;
  7969. }
  7970. _getPattern(objId, matrix = null) {
  7971. let pattern;
  7972. if (this.cachedPatterns.has(objId)) {
  7973. pattern = this.cachedPatterns.get(objId);
  7974. } else {
  7975. pattern = getShadingPattern(this.getObject(objId));
  7976. this.cachedPatterns.set(objId, pattern);
  7977. }
  7978. if (matrix) {
  7979. pattern.matrix = matrix;
  7980. }
  7981. return pattern;
  7982. }
  7983. shadingFill(objId) {
  7984. if (!this.contentVisible) {
  7985. return;
  7986. }
  7987. const ctx = this.ctx;
  7988. this.save();
  7989. const pattern = this._getPattern(objId);
  7990. ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING);
  7991. const inv = getCurrentTransformInverse(ctx);
  7992. if (inv) {
  7993. const {
  7994. width,
  7995. height
  7996. } = ctx.canvas;
  7997. const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox([0, 0, width, height], inv);
  7998. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7999. } else {
  8000. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  8001. }
  8002. this.compose(this.current.getClippedPathBoundingBox());
  8003. this.restore();
  8004. }
  8005. beginInlineImage() {
  8006. unreachable("Should not call beginInlineImage");
  8007. }
  8008. beginImageData() {
  8009. unreachable("Should not call beginImageData");
  8010. }
  8011. paintFormXObjectBegin(matrix, bbox) {
  8012. if (!this.contentVisible) {
  8013. return;
  8014. }
  8015. this.save();
  8016. this.baseTransformStack.push(this.baseTransform);
  8017. if (matrix) {
  8018. this.transform(...matrix);
  8019. }
  8020. this.baseTransform = getCurrentTransform(this.ctx);
  8021. if (bbox) {
  8022. const width = bbox[2] - bbox[0];
  8023. const height = bbox[3] - bbox[1];
  8024. this.ctx.rect(bbox[0], bbox[1], width, height);
  8025. this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox);
  8026. this.clip();
  8027. this.endPath();
  8028. }
  8029. }
  8030. paintFormXObjectEnd() {
  8031. if (!this.contentVisible) {
  8032. return;
  8033. }
  8034. this.restore();
  8035. this.baseTransform = this.baseTransformStack.pop();
  8036. }
  8037. beginGroup(group) {
  8038. if (!this.contentVisible) {
  8039. return;
  8040. }
  8041. this.save();
  8042. if (this.inSMaskMode) {
  8043. this.endSMaskMode();
  8044. this.current.activeSMask = null;
  8045. }
  8046. const currentCtx = this.ctx;
  8047. if (!group.isolated) {
  8048. info("TODO: Support non-isolated groups.");
  8049. }
  8050. if (group.knockout) {
  8051. warn("Knockout groups not supported.");
  8052. }
  8053. const currentTransform = getCurrentTransform(currentCtx);
  8054. if (group.matrix) {
  8055. currentCtx.transform(...group.matrix);
  8056. }
  8057. if (!group.bbox) {
  8058. throw new Error("Bounding box is required.");
  8059. }
  8060. let bounds = Util.getAxialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx));
  8061. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  8062. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  8063. const offsetX = Math.floor(bounds[0]);
  8064. const offsetY = Math.floor(bounds[1]);
  8065. const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  8066. const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  8067. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  8068. let cacheId = "groupAt" + this.groupLevel;
  8069. if (group.smask) {
  8070. cacheId += "_smask_" + this.smaskCounter++ % 2;
  8071. }
  8072. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  8073. const groupCtx = scratchCanvas.context;
  8074. groupCtx.translate(-offsetX, -offsetY);
  8075. groupCtx.transform(...currentTransform);
  8076. if (group.smask) {
  8077. this.smaskStack.push({
  8078. canvas: scratchCanvas.canvas,
  8079. context: groupCtx,
  8080. offsetX,
  8081. offsetY,
  8082. subtype: group.smask.subtype,
  8083. backdrop: group.smask.backdrop,
  8084. transferMap: group.smask.transferMap || null,
  8085. startTransformInverse: null
  8086. });
  8087. } else {
  8088. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  8089. currentCtx.translate(offsetX, offsetY);
  8090. currentCtx.save();
  8091. }
  8092. copyCtxState(currentCtx, groupCtx);
  8093. this.ctx = groupCtx;
  8094. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  8095. this.groupStack.push(currentCtx);
  8096. this.groupLevel++;
  8097. }
  8098. endGroup(group) {
  8099. if (!this.contentVisible) {
  8100. return;
  8101. }
  8102. this.groupLevel--;
  8103. const groupCtx = this.ctx;
  8104. const ctx = this.groupStack.pop();
  8105. this.ctx = ctx;
  8106. this.ctx.imageSmoothingEnabled = false;
  8107. if (group.smask) {
  8108. this.tempSMask = this.smaskStack.pop();
  8109. this.restore();
  8110. } else {
  8111. this.ctx.restore();
  8112. const currentMtx = getCurrentTransform(this.ctx);
  8113. this.restore();
  8114. this.ctx.save();
  8115. this.ctx.setTransform(...currentMtx);
  8116. const dirtyBox = Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  8117. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  8118. this.ctx.restore();
  8119. this.compose(dirtyBox);
  8120. }
  8121. }
  8122. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  8123. this.#restoreInitialState();
  8124. resetCtxToDefault(this.ctx);
  8125. this.ctx.save();
  8126. this.save();
  8127. if (this.baseTransform) {
  8128. this.ctx.setTransform(...this.baseTransform);
  8129. }
  8130. if (rect) {
  8131. const width = rect[2] - rect[0];
  8132. const height = rect[3] - rect[1];
  8133. if (hasOwnCanvas && this.annotationCanvasMap) {
  8134. transform = transform.slice();
  8135. transform[4] -= rect[0];
  8136. transform[5] -= rect[1];
  8137. rect = rect.slice();
  8138. rect[0] = rect[1] = 0;
  8139. rect[2] = width;
  8140. rect[3] = height;
  8141. const [scaleX, scaleY] = Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx));
  8142. const {
  8143. viewportScale
  8144. } = this;
  8145. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  8146. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  8147. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  8148. const {
  8149. canvas,
  8150. context
  8151. } = this.annotationCanvas;
  8152. this.annotationCanvasMap.set(id, canvas);
  8153. this.annotationCanvas.savedCtx = this.ctx;
  8154. this.ctx = context;
  8155. this.ctx.save();
  8156. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  8157. resetCtxToDefault(this.ctx);
  8158. } else {
  8159. resetCtxToDefault(this.ctx);
  8160. this.endPath();
  8161. this.ctx.rect(rect[0], rect[1], width, height);
  8162. this.ctx.clip();
  8163. this.ctx.beginPath();
  8164. }
  8165. }
  8166. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  8167. this.transform(...transform);
  8168. this.transform(...matrix);
  8169. }
  8170. endAnnotation() {
  8171. if (this.annotationCanvas) {
  8172. this.ctx.restore();
  8173. this.#drawFilter();
  8174. this.ctx = this.annotationCanvas.savedCtx;
  8175. delete this.annotationCanvas.savedCtx;
  8176. delete this.annotationCanvas;
  8177. }
  8178. }
  8179. paintImageMaskXObject(img) {
  8180. if (!this.contentVisible) {
  8181. return;
  8182. }
  8183. const count = img.count;
  8184. img = this.getObject(img.data, img);
  8185. img.count = count;
  8186. const ctx = this.ctx;
  8187. const glyph = this.processingType3;
  8188. if (glyph) {
  8189. if (glyph.compiled === undefined) {
  8190. glyph.compiled = compileType3Glyph(img);
  8191. }
  8192. if (glyph.compiled) {
  8193. glyph.compiled(ctx);
  8194. return;
  8195. }
  8196. }
  8197. const mask = this._createMaskCanvas(img);
  8198. const maskCanvas = mask.canvas;
  8199. ctx.save();
  8200. ctx.setTransform(1, 0, 0, 1, 0, 0);
  8201. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  8202. ctx.restore();
  8203. this.compose();
  8204. }
  8205. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  8206. if (!this.contentVisible) {
  8207. return;
  8208. }
  8209. img = this.getObject(img.data, img);
  8210. const ctx = this.ctx;
  8211. ctx.save();
  8212. const currentTransform = getCurrentTransform(ctx);
  8213. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  8214. const mask = this._createMaskCanvas(img);
  8215. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  8216. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  8217. const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  8218. const [x, y] = Util.applyTransform([0, 0], trans);
  8219. ctx.drawImage(mask.canvas, x, y);
  8220. }
  8221. ctx.restore();
  8222. this.compose();
  8223. }
  8224. paintImageMaskXObjectGroup(images) {
  8225. if (!this.contentVisible) {
  8226. return;
  8227. }
  8228. const ctx = this.ctx;
  8229. const fillColor = this.current.fillColor;
  8230. const isPatternFill = this.current.patternFill;
  8231. for (const image of images) {
  8232. const {
  8233. data,
  8234. width,
  8235. height,
  8236. transform
  8237. } = image;
  8238. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  8239. const maskCtx = maskCanvas.context;
  8240. maskCtx.save();
  8241. const img = this.getObject(data, image);
  8242. putBinaryImageMask(maskCtx, img);
  8243. maskCtx.globalCompositeOperation = "source-in";
  8244. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor;
  8245. maskCtx.fillRect(0, 0, width, height);
  8246. maskCtx.restore();
  8247. ctx.save();
  8248. ctx.transform(...transform);
  8249. ctx.scale(1, -1);
  8250. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8251. ctx.restore();
  8252. }
  8253. this.compose();
  8254. }
  8255. paintImageXObject(objId) {
  8256. if (!this.contentVisible) {
  8257. return;
  8258. }
  8259. const imgData = this.getObject(objId);
  8260. if (!imgData) {
  8261. warn("Dependent image isn't ready yet");
  8262. return;
  8263. }
  8264. this.paintInlineImageXObject(imgData);
  8265. }
  8266. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  8267. if (!this.contentVisible) {
  8268. return;
  8269. }
  8270. const imgData = this.getObject(objId);
  8271. if (!imgData) {
  8272. warn("Dependent image isn't ready yet");
  8273. return;
  8274. }
  8275. const width = imgData.width;
  8276. const height = imgData.height;
  8277. const map = [];
  8278. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  8279. map.push({
  8280. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  8281. x: 0,
  8282. y: 0,
  8283. w: width,
  8284. h: height
  8285. });
  8286. }
  8287. this.paintInlineImageXObjectGroup(imgData, map);
  8288. }
  8289. applyTransferMapsToCanvas(ctx) {
  8290. if (this.current.transferMaps !== "none") {
  8291. ctx.filter = this.current.transferMaps;
  8292. ctx.drawImage(ctx.canvas, 0, 0);
  8293. ctx.filter = "none";
  8294. }
  8295. return ctx.canvas;
  8296. }
  8297. applyTransferMapsToBitmap(imgData) {
  8298. if (this.current.transferMaps === "none") {
  8299. return imgData.bitmap;
  8300. }
  8301. const {
  8302. bitmap,
  8303. width,
  8304. height
  8305. } = imgData;
  8306. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  8307. const tmpCtx = tmpCanvas.context;
  8308. tmpCtx.filter = this.current.transferMaps;
  8309. tmpCtx.drawImage(bitmap, 0, 0);
  8310. tmpCtx.filter = "none";
  8311. return tmpCanvas.canvas;
  8312. }
  8313. paintInlineImageXObject(imgData) {
  8314. if (!this.contentVisible) {
  8315. return;
  8316. }
  8317. const width = imgData.width;
  8318. const height = imgData.height;
  8319. const ctx = this.ctx;
  8320. this.save();
  8321. if (!isNodeJS) {
  8322. const {
  8323. filter
  8324. } = ctx;
  8325. if (filter !== "none" && filter !== "") {
  8326. ctx.filter = "none";
  8327. }
  8328. }
  8329. ctx.scale(1 / width, -1 / height);
  8330. let imgToPaint;
  8331. if (imgData.bitmap) {
  8332. imgToPaint = this.applyTransferMapsToBitmap(imgData);
  8333. } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  8334. imgToPaint = imgData;
  8335. } else {
  8336. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  8337. const tmpCtx = tmpCanvas.context;
  8338. putBinaryImageData(tmpCtx, imgData);
  8339. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  8340. }
  8341. const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
  8342. ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
  8343. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  8344. this.compose();
  8345. this.restore();
  8346. }
  8347. paintInlineImageXObjectGroup(imgData, map) {
  8348. if (!this.contentVisible) {
  8349. return;
  8350. }
  8351. const ctx = this.ctx;
  8352. let imgToPaint;
  8353. if (imgData.bitmap) {
  8354. imgToPaint = imgData.bitmap;
  8355. } else {
  8356. const w = imgData.width;
  8357. const h = imgData.height;
  8358. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  8359. const tmpCtx = tmpCanvas.context;
  8360. putBinaryImageData(tmpCtx, imgData);
  8361. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  8362. }
  8363. for (const entry of map) {
  8364. ctx.save();
  8365. ctx.transform(...entry.transform);
  8366. ctx.scale(1, -1);
  8367. drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  8368. ctx.restore();
  8369. }
  8370. this.compose();
  8371. }
  8372. paintSolidColorImageMask() {
  8373. if (!this.contentVisible) {
  8374. return;
  8375. }
  8376. this.ctx.fillRect(0, 0, 1, 1);
  8377. this.compose();
  8378. }
  8379. markPoint(tag) {}
  8380. markPointProps(tag, properties) {}
  8381. beginMarkedContent(tag) {
  8382. this.markedContentStack.push({
  8383. visible: true
  8384. });
  8385. }
  8386. beginMarkedContentProps(tag, properties) {
  8387. if (tag === "OC") {
  8388. this.markedContentStack.push({
  8389. visible: this.optionalContentConfig.isVisible(properties)
  8390. });
  8391. } else {
  8392. this.markedContentStack.push({
  8393. visible: true
  8394. });
  8395. }
  8396. this.contentVisible = this.isContentVisible();
  8397. }
  8398. endMarkedContent() {
  8399. this.markedContentStack.pop();
  8400. this.contentVisible = this.isContentVisible();
  8401. }
  8402. beginCompat() {}
  8403. endCompat() {}
  8404. consumePath(clipBox) {
  8405. const isEmpty = this.current.isEmptyClip();
  8406. if (this.pendingClip) {
  8407. this.current.updateClipFromPath();
  8408. }
  8409. if (!this.pendingClip) {
  8410. this.compose(clipBox);
  8411. }
  8412. const ctx = this.ctx;
  8413. if (this.pendingClip) {
  8414. if (!isEmpty) {
  8415. if (this.pendingClip === EO_CLIP) {
  8416. ctx.clip("evenodd");
  8417. } else {
  8418. ctx.clip();
  8419. }
  8420. }
  8421. this.pendingClip = null;
  8422. }
  8423. this.current.startNewPathAndClipBox(this.current.clipBox);
  8424. ctx.beginPath();
  8425. }
  8426. getSinglePixelWidth() {
  8427. if (!this._cachedGetSinglePixelWidth) {
  8428. const m = getCurrentTransform(this.ctx);
  8429. if (m[1] === 0 && m[2] === 0) {
  8430. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  8431. } else {
  8432. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  8433. const normX = Math.hypot(m[0], m[2]);
  8434. const normY = Math.hypot(m[1], m[3]);
  8435. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  8436. }
  8437. }
  8438. return this._cachedGetSinglePixelWidth;
  8439. }
  8440. getScaleForStroking() {
  8441. if (this._cachedScaleForStroking[0] === -1) {
  8442. const {
  8443. lineWidth
  8444. } = this.current;
  8445. const {
  8446. a,
  8447. b,
  8448. c,
  8449. d
  8450. } = this.ctx.getTransform();
  8451. let scaleX, scaleY;
  8452. if (b === 0 && c === 0) {
  8453. const normX = Math.abs(a);
  8454. const normY = Math.abs(d);
  8455. if (normX === normY) {
  8456. if (lineWidth === 0) {
  8457. scaleX = scaleY = 1 / normX;
  8458. } else {
  8459. const scaledLineWidth = normX * lineWidth;
  8460. scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
  8461. }
  8462. } else if (lineWidth === 0) {
  8463. scaleX = 1 / normX;
  8464. scaleY = 1 / normY;
  8465. } else {
  8466. const scaledXLineWidth = normX * lineWidth;
  8467. const scaledYLineWidth = normY * lineWidth;
  8468. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  8469. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  8470. }
  8471. } else {
  8472. const absDet = Math.abs(a * d - b * c);
  8473. const normX = Math.hypot(a, b);
  8474. const normY = Math.hypot(c, d);
  8475. if (lineWidth === 0) {
  8476. scaleX = normY / absDet;
  8477. scaleY = normX / absDet;
  8478. } else {
  8479. const baseArea = lineWidth * absDet;
  8480. scaleX = normY > baseArea ? normY / baseArea : 1;
  8481. scaleY = normX > baseArea ? normX / baseArea : 1;
  8482. }
  8483. }
  8484. this._cachedScaleForStroking[0] = scaleX;
  8485. this._cachedScaleForStroking[1] = scaleY;
  8486. }
  8487. return this._cachedScaleForStroking;
  8488. }
  8489. rescaleAndStroke(saveRestore) {
  8490. const {
  8491. ctx
  8492. } = this;
  8493. const {
  8494. lineWidth
  8495. } = this.current;
  8496. const [scaleX, scaleY] = this.getScaleForStroking();
  8497. ctx.lineWidth = lineWidth || 1;
  8498. if (scaleX === 1 && scaleY === 1) {
  8499. ctx.stroke();
  8500. return;
  8501. }
  8502. const dashes = ctx.getLineDash();
  8503. if (saveRestore) {
  8504. ctx.save();
  8505. }
  8506. ctx.scale(scaleX, scaleY);
  8507. if (dashes.length > 0) {
  8508. const scale = Math.max(scaleX, scaleY);
  8509. ctx.setLineDash(dashes.map(x => x / scale));
  8510. ctx.lineDashOffset /= scale;
  8511. }
  8512. ctx.stroke();
  8513. if (saveRestore) {
  8514. ctx.restore();
  8515. }
  8516. }
  8517. isContentVisible() {
  8518. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  8519. if (!this.markedContentStack[i].visible) {
  8520. return false;
  8521. }
  8522. }
  8523. return true;
  8524. }
  8525. }
  8526. for (const op in OPS) {
  8527. if (CanvasGraphics.prototype[op] !== undefined) {
  8528. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8529. }
  8530. }
  8531. ;// ./src/display/worker_options.js
  8532. class GlobalWorkerOptions {
  8533. static #port = null;
  8534. static #src = "";
  8535. static get workerPort() {
  8536. return this.#port;
  8537. }
  8538. static set workerPort(val) {
  8539. if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) {
  8540. throw new Error("Invalid `workerPort` type.");
  8541. }
  8542. this.#port = val;
  8543. }
  8544. static get workerSrc() {
  8545. return this.#src;
  8546. }
  8547. static set workerSrc(val) {
  8548. if (typeof val !== "string") {
  8549. throw new Error("Invalid `workerSrc` type.");
  8550. }
  8551. this.#src = val;
  8552. }
  8553. }
  8554. ;// ./src/shared/message_handler.js
  8555. const CallbackKind = {
  8556. UNKNOWN: 0,
  8557. DATA: 1,
  8558. ERROR: 2
  8559. };
  8560. const StreamKind = {
  8561. UNKNOWN: 0,
  8562. CANCEL: 1,
  8563. CANCEL_COMPLETE: 2,
  8564. CLOSE: 3,
  8565. ENQUEUE: 4,
  8566. ERROR: 5,
  8567. PULL: 6,
  8568. PULL_COMPLETE: 7,
  8569. START_COMPLETE: 8
  8570. };
  8571. function wrapReason(reason) {
  8572. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  8573. unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  8574. }
  8575. switch (reason.name) {
  8576. case "AbortException":
  8577. return new AbortException(reason.message);
  8578. case "MissingPDFException":
  8579. return new MissingPDFException(reason.message);
  8580. case "PasswordException":
  8581. return new PasswordException(reason.message, reason.code);
  8582. case "UnexpectedResponseException":
  8583. return new UnexpectedResponseException(reason.message, reason.status);
  8584. case "UnknownErrorException":
  8585. return new UnknownErrorException(reason.message, reason.details);
  8586. default:
  8587. return new UnknownErrorException(reason.message, reason.toString());
  8588. }
  8589. }
  8590. class MessageHandler {
  8591. #messageAC = new AbortController();
  8592. constructor(sourceName, targetName, comObj) {
  8593. this.sourceName = sourceName;
  8594. this.targetName = targetName;
  8595. this.comObj = comObj;
  8596. this.callbackId = 1;
  8597. this.streamId = 1;
  8598. this.streamSinks = Object.create(null);
  8599. this.streamControllers = Object.create(null);
  8600. this.callbackCapabilities = Object.create(null);
  8601. this.actionHandler = Object.create(null);
  8602. comObj.addEventListener("message", this.#onMessage.bind(this), {
  8603. signal: this.#messageAC.signal
  8604. });
  8605. }
  8606. #onMessage({
  8607. data
  8608. }) {
  8609. if (data.targetName !== this.sourceName) {
  8610. return;
  8611. }
  8612. if (data.stream) {
  8613. this.#processStreamMessage(data);
  8614. return;
  8615. }
  8616. if (data.callback) {
  8617. const callbackId = data.callbackId;
  8618. const capability = this.callbackCapabilities[callbackId];
  8619. if (!capability) {
  8620. throw new Error(`Cannot resolve callback ${callbackId}`);
  8621. }
  8622. delete this.callbackCapabilities[callbackId];
  8623. if (data.callback === CallbackKind.DATA) {
  8624. capability.resolve(data.data);
  8625. } else if (data.callback === CallbackKind.ERROR) {
  8626. capability.reject(wrapReason(data.reason));
  8627. } else {
  8628. throw new Error("Unexpected callback case");
  8629. }
  8630. return;
  8631. }
  8632. const action = this.actionHandler[data.action];
  8633. if (!action) {
  8634. throw new Error(`Unknown action from worker: ${data.action}`);
  8635. }
  8636. if (data.callbackId) {
  8637. const sourceName = this.sourceName,
  8638. targetName = data.sourceName,
  8639. comObj = this.comObj;
  8640. new Promise(function (resolve) {
  8641. resolve(action(data.data));
  8642. }).then(function (result) {
  8643. comObj.postMessage({
  8644. sourceName,
  8645. targetName,
  8646. callback: CallbackKind.DATA,
  8647. callbackId: data.callbackId,
  8648. data: result
  8649. });
  8650. }, function (reason) {
  8651. comObj.postMessage({
  8652. sourceName,
  8653. targetName,
  8654. callback: CallbackKind.ERROR,
  8655. callbackId: data.callbackId,
  8656. reason: wrapReason(reason)
  8657. });
  8658. });
  8659. return;
  8660. }
  8661. if (data.streamId) {
  8662. this.#createStreamSink(data);
  8663. return;
  8664. }
  8665. action(data.data);
  8666. }
  8667. on(actionName, handler) {
  8668. const ah = this.actionHandler;
  8669. if (ah[actionName]) {
  8670. throw new Error(`There is already an actionName called "${actionName}"`);
  8671. }
  8672. ah[actionName] = handler;
  8673. }
  8674. send(actionName, data, transfers) {
  8675. this.comObj.postMessage({
  8676. sourceName: this.sourceName,
  8677. targetName: this.targetName,
  8678. action: actionName,
  8679. data
  8680. }, transfers);
  8681. }
  8682. sendWithPromise(actionName, data, transfers) {
  8683. const callbackId = this.callbackId++;
  8684. const capability = Promise.withResolvers();
  8685. this.callbackCapabilities[callbackId] = capability;
  8686. try {
  8687. this.comObj.postMessage({
  8688. sourceName: this.sourceName,
  8689. targetName: this.targetName,
  8690. action: actionName,
  8691. callbackId,
  8692. data
  8693. }, transfers);
  8694. } catch (ex) {
  8695. capability.reject(ex);
  8696. }
  8697. return capability.promise;
  8698. }
  8699. sendWithStream(actionName, data, queueingStrategy, transfers) {
  8700. const streamId = this.streamId++,
  8701. sourceName = this.sourceName,
  8702. targetName = this.targetName,
  8703. comObj = this.comObj;
  8704. return new ReadableStream({
  8705. start: controller => {
  8706. const startCapability = Promise.withResolvers();
  8707. this.streamControllers[streamId] = {
  8708. controller,
  8709. startCall: startCapability,
  8710. pullCall: null,
  8711. cancelCall: null,
  8712. isClosed: false
  8713. };
  8714. comObj.postMessage({
  8715. sourceName,
  8716. targetName,
  8717. action: actionName,
  8718. streamId,
  8719. data,
  8720. desiredSize: controller.desiredSize
  8721. }, transfers);
  8722. return startCapability.promise;
  8723. },
  8724. pull: controller => {
  8725. const pullCapability = Promise.withResolvers();
  8726. this.streamControllers[streamId].pullCall = pullCapability;
  8727. comObj.postMessage({
  8728. sourceName,
  8729. targetName,
  8730. stream: StreamKind.PULL,
  8731. streamId,
  8732. desiredSize: controller.desiredSize
  8733. });
  8734. return pullCapability.promise;
  8735. },
  8736. cancel: reason => {
  8737. assert(reason instanceof Error, "cancel must have a valid reason");
  8738. const cancelCapability = Promise.withResolvers();
  8739. this.streamControllers[streamId].cancelCall = cancelCapability;
  8740. this.streamControllers[streamId].isClosed = true;
  8741. comObj.postMessage({
  8742. sourceName,
  8743. targetName,
  8744. stream: StreamKind.CANCEL,
  8745. streamId,
  8746. reason: wrapReason(reason)
  8747. });
  8748. return cancelCapability.promise;
  8749. }
  8750. }, queueingStrategy);
  8751. }
  8752. #createStreamSink(data) {
  8753. const streamId = data.streamId,
  8754. sourceName = this.sourceName,
  8755. targetName = data.sourceName,
  8756. comObj = this.comObj;
  8757. const self = this,
  8758. action = this.actionHandler[data.action];
  8759. const streamSink = {
  8760. enqueue(chunk, size = 1, transfers) {
  8761. if (this.isCancelled) {
  8762. return;
  8763. }
  8764. const lastDesiredSize = this.desiredSize;
  8765. this.desiredSize -= size;
  8766. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  8767. this.sinkCapability = Promise.withResolvers();
  8768. this.ready = this.sinkCapability.promise;
  8769. }
  8770. comObj.postMessage({
  8771. sourceName,
  8772. targetName,
  8773. stream: StreamKind.ENQUEUE,
  8774. streamId,
  8775. chunk
  8776. }, transfers);
  8777. },
  8778. close() {
  8779. if (this.isCancelled) {
  8780. return;
  8781. }
  8782. this.isCancelled = true;
  8783. comObj.postMessage({
  8784. sourceName,
  8785. targetName,
  8786. stream: StreamKind.CLOSE,
  8787. streamId
  8788. });
  8789. delete self.streamSinks[streamId];
  8790. },
  8791. error(reason) {
  8792. assert(reason instanceof Error, "error must have a valid reason");
  8793. if (this.isCancelled) {
  8794. return;
  8795. }
  8796. this.isCancelled = true;
  8797. comObj.postMessage({
  8798. sourceName,
  8799. targetName,
  8800. stream: StreamKind.ERROR,
  8801. streamId,
  8802. reason: wrapReason(reason)
  8803. });
  8804. },
  8805. sinkCapability: Promise.withResolvers(),
  8806. onPull: null,
  8807. onCancel: null,
  8808. isCancelled: false,
  8809. desiredSize: data.desiredSize,
  8810. ready: null
  8811. };
  8812. streamSink.sinkCapability.resolve();
  8813. streamSink.ready = streamSink.sinkCapability.promise;
  8814. this.streamSinks[streamId] = streamSink;
  8815. new Promise(function (resolve) {
  8816. resolve(action(data.data, streamSink));
  8817. }).then(function () {
  8818. comObj.postMessage({
  8819. sourceName,
  8820. targetName,
  8821. stream: StreamKind.START_COMPLETE,
  8822. streamId,
  8823. success: true
  8824. });
  8825. }, function (reason) {
  8826. comObj.postMessage({
  8827. sourceName,
  8828. targetName,
  8829. stream: StreamKind.START_COMPLETE,
  8830. streamId,
  8831. reason: wrapReason(reason)
  8832. });
  8833. });
  8834. }
  8835. #processStreamMessage(data) {
  8836. const streamId = data.streamId,
  8837. sourceName = this.sourceName,
  8838. targetName = data.sourceName,
  8839. comObj = this.comObj;
  8840. const streamController = this.streamControllers[streamId],
  8841. streamSink = this.streamSinks[streamId];
  8842. switch (data.stream) {
  8843. case StreamKind.START_COMPLETE:
  8844. if (data.success) {
  8845. streamController.startCall.resolve();
  8846. } else {
  8847. streamController.startCall.reject(wrapReason(data.reason));
  8848. }
  8849. break;
  8850. case StreamKind.PULL_COMPLETE:
  8851. if (data.success) {
  8852. streamController.pullCall.resolve();
  8853. } else {
  8854. streamController.pullCall.reject(wrapReason(data.reason));
  8855. }
  8856. break;
  8857. case StreamKind.PULL:
  8858. if (!streamSink) {
  8859. comObj.postMessage({
  8860. sourceName,
  8861. targetName,
  8862. stream: StreamKind.PULL_COMPLETE,
  8863. streamId,
  8864. success: true
  8865. });
  8866. break;
  8867. }
  8868. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  8869. streamSink.sinkCapability.resolve();
  8870. }
  8871. streamSink.desiredSize = data.desiredSize;
  8872. new Promise(function (resolve) {
  8873. resolve(streamSink.onPull?.());
  8874. }).then(function () {
  8875. comObj.postMessage({
  8876. sourceName,
  8877. targetName,
  8878. stream: StreamKind.PULL_COMPLETE,
  8879. streamId,
  8880. success: true
  8881. });
  8882. }, function (reason) {
  8883. comObj.postMessage({
  8884. sourceName,
  8885. targetName,
  8886. stream: StreamKind.PULL_COMPLETE,
  8887. streamId,
  8888. reason: wrapReason(reason)
  8889. });
  8890. });
  8891. break;
  8892. case StreamKind.ENQUEUE:
  8893. assert(streamController, "enqueue should have stream controller");
  8894. if (streamController.isClosed) {
  8895. break;
  8896. }
  8897. streamController.controller.enqueue(data.chunk);
  8898. break;
  8899. case StreamKind.CLOSE:
  8900. assert(streamController, "close should have stream controller");
  8901. if (streamController.isClosed) {
  8902. break;
  8903. }
  8904. streamController.isClosed = true;
  8905. streamController.controller.close();
  8906. this.#deleteStreamController(streamController, streamId);
  8907. break;
  8908. case StreamKind.ERROR:
  8909. assert(streamController, "error should have stream controller");
  8910. streamController.controller.error(wrapReason(data.reason));
  8911. this.#deleteStreamController(streamController, streamId);
  8912. break;
  8913. case StreamKind.CANCEL_COMPLETE:
  8914. if (data.success) {
  8915. streamController.cancelCall.resolve();
  8916. } else {
  8917. streamController.cancelCall.reject(wrapReason(data.reason));
  8918. }
  8919. this.#deleteStreamController(streamController, streamId);
  8920. break;
  8921. case StreamKind.CANCEL:
  8922. if (!streamSink) {
  8923. break;
  8924. }
  8925. new Promise(function (resolve) {
  8926. resolve(streamSink.onCancel?.(wrapReason(data.reason)));
  8927. }).then(function () {
  8928. comObj.postMessage({
  8929. sourceName,
  8930. targetName,
  8931. stream: StreamKind.CANCEL_COMPLETE,
  8932. streamId,
  8933. success: true
  8934. });
  8935. }, function (reason) {
  8936. comObj.postMessage({
  8937. sourceName,
  8938. targetName,
  8939. stream: StreamKind.CANCEL_COMPLETE,
  8940. streamId,
  8941. reason: wrapReason(reason)
  8942. });
  8943. });
  8944. streamSink.sinkCapability.reject(wrapReason(data.reason));
  8945. streamSink.isCancelled = true;
  8946. delete this.streamSinks[streamId];
  8947. break;
  8948. default:
  8949. throw new Error("Unexpected stream case");
  8950. }
  8951. }
  8952. async #deleteStreamController(streamController, streamId) {
  8953. await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
  8954. delete this.streamControllers[streamId];
  8955. }
  8956. destroy() {
  8957. this.#messageAC?.abort();
  8958. this.#messageAC = null;
  8959. }
  8960. }
  8961. ;// ./src/display/metadata.js
  8962. class Metadata {
  8963. #metadataMap;
  8964. #data;
  8965. constructor({
  8966. parsedData,
  8967. rawData
  8968. }) {
  8969. this.#metadataMap = parsedData;
  8970. this.#data = rawData;
  8971. }
  8972. getRaw() {
  8973. return this.#data;
  8974. }
  8975. get(name) {
  8976. return this.#metadataMap.get(name) ?? null;
  8977. }
  8978. getAll() {
  8979. return objectFromMap(this.#metadataMap);
  8980. }
  8981. has(name) {
  8982. return this.#metadataMap.has(name);
  8983. }
  8984. }
  8985. ;// ./src/display/optional_content_config.js
  8986. const INTERNAL = Symbol("INTERNAL");
  8987. class OptionalContentGroup {
  8988. #isDisplay = false;
  8989. #isPrint = false;
  8990. #userSet = false;
  8991. #visible = true;
  8992. constructor(renderingIntent, {
  8993. name,
  8994. intent,
  8995. usage,
  8996. rbGroups
  8997. }) {
  8998. this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
  8999. this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  9000. this.name = name;
  9001. this.intent = intent;
  9002. this.usage = usage;
  9003. this.rbGroups = rbGroups;
  9004. }
  9005. get visible() {
  9006. if (this.#userSet) {
  9007. return this.#visible;
  9008. }
  9009. if (!this.#visible) {
  9010. return false;
  9011. }
  9012. const {
  9013. print,
  9014. view
  9015. } = this.usage;
  9016. if (this.#isDisplay) {
  9017. return view?.viewState !== "OFF";
  9018. } else if (this.#isPrint) {
  9019. return print?.printState !== "OFF";
  9020. }
  9021. return true;
  9022. }
  9023. _setVisible(internal, visible, userSet = false) {
  9024. if (internal !== INTERNAL) {
  9025. unreachable("Internal method `_setVisible` called.");
  9026. }
  9027. this.#userSet = userSet;
  9028. this.#visible = visible;
  9029. }
  9030. }
  9031. class OptionalContentConfig {
  9032. #cachedGetHash = null;
  9033. #groups = new Map();
  9034. #initialHash = null;
  9035. #order = null;
  9036. constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
  9037. this.renderingIntent = renderingIntent;
  9038. this.name = null;
  9039. this.creator = null;
  9040. if (data === null) {
  9041. return;
  9042. }
  9043. this.name = data.name;
  9044. this.creator = data.creator;
  9045. this.#order = data.order;
  9046. for (const group of data.groups) {
  9047. this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
  9048. }
  9049. if (data.baseState === "OFF") {
  9050. for (const group of this.#groups.values()) {
  9051. group._setVisible(INTERNAL, false);
  9052. }
  9053. }
  9054. for (const on of data.on) {
  9055. this.#groups.get(on)._setVisible(INTERNAL, true);
  9056. }
  9057. for (const off of data.off) {
  9058. this.#groups.get(off)._setVisible(INTERNAL, false);
  9059. }
  9060. this.#initialHash = this.getHash();
  9061. }
  9062. #evaluateVisibilityExpression(array) {
  9063. const length = array.length;
  9064. if (length < 2) {
  9065. return true;
  9066. }
  9067. const operator = array[0];
  9068. for (let i = 1; i < length; i++) {
  9069. const element = array[i];
  9070. let state;
  9071. if (Array.isArray(element)) {
  9072. state = this.#evaluateVisibilityExpression(element);
  9073. } else if (this.#groups.has(element)) {
  9074. state = this.#groups.get(element).visible;
  9075. } else {
  9076. warn(`Optional content group not found: ${element}`);
  9077. return true;
  9078. }
  9079. switch (operator) {
  9080. case "And":
  9081. if (!state) {
  9082. return false;
  9083. }
  9084. break;
  9085. case "Or":
  9086. if (state) {
  9087. return true;
  9088. }
  9089. break;
  9090. case "Not":
  9091. return !state;
  9092. default:
  9093. return true;
  9094. }
  9095. }
  9096. return operator === "And";
  9097. }
  9098. isVisible(group) {
  9099. if (this.#groups.size === 0) {
  9100. return true;
  9101. }
  9102. if (!group) {
  9103. info("Optional content group not defined.");
  9104. return true;
  9105. }
  9106. if (group.type === "OCG") {
  9107. if (!this.#groups.has(group.id)) {
  9108. warn(`Optional content group not found: ${group.id}`);
  9109. return true;
  9110. }
  9111. return this.#groups.get(group.id).visible;
  9112. } else if (group.type === "OCMD") {
  9113. if (group.expression) {
  9114. return this.#evaluateVisibilityExpression(group.expression);
  9115. }
  9116. if (!group.policy || group.policy === "AnyOn") {
  9117. for (const id of group.ids) {
  9118. if (!this.#groups.has(id)) {
  9119. warn(`Optional content group not found: ${id}`);
  9120. return true;
  9121. }
  9122. if (this.#groups.get(id).visible) {
  9123. return true;
  9124. }
  9125. }
  9126. return false;
  9127. } else if (group.policy === "AllOn") {
  9128. for (const id of group.ids) {
  9129. if (!this.#groups.has(id)) {
  9130. warn(`Optional content group not found: ${id}`);
  9131. return true;
  9132. }
  9133. if (!this.#groups.get(id).visible) {
  9134. return false;
  9135. }
  9136. }
  9137. return true;
  9138. } else if (group.policy === "AnyOff") {
  9139. for (const id of group.ids) {
  9140. if (!this.#groups.has(id)) {
  9141. warn(`Optional content group not found: ${id}`);
  9142. return true;
  9143. }
  9144. if (!this.#groups.get(id).visible) {
  9145. return true;
  9146. }
  9147. }
  9148. return false;
  9149. } else if (group.policy === "AllOff") {
  9150. for (const id of group.ids) {
  9151. if (!this.#groups.has(id)) {
  9152. warn(`Optional content group not found: ${id}`);
  9153. return true;
  9154. }
  9155. if (this.#groups.get(id).visible) {
  9156. return false;
  9157. }
  9158. }
  9159. return true;
  9160. }
  9161. warn(`Unknown optional content policy ${group.policy}.`);
  9162. return true;
  9163. }
  9164. warn(`Unknown group type ${group.type}.`);
  9165. return true;
  9166. }
  9167. setVisibility(id, visible = true, preserveRB = true) {
  9168. const group = this.#groups.get(id);
  9169. if (!group) {
  9170. warn(`Optional content group not found: ${id}`);
  9171. return;
  9172. }
  9173. if (preserveRB && visible && group.rbGroups.length) {
  9174. for (const rbGroup of group.rbGroups) {
  9175. for (const otherId of rbGroup) {
  9176. if (otherId !== id) {
  9177. this.#groups.get(otherId)?._setVisible(INTERNAL, false, true);
  9178. }
  9179. }
  9180. }
  9181. }
  9182. group._setVisible(INTERNAL, !!visible, true);
  9183. this.#cachedGetHash = null;
  9184. }
  9185. setOCGState({
  9186. state,
  9187. preserveRB
  9188. }) {
  9189. let operator;
  9190. for (const elem of state) {
  9191. switch (elem) {
  9192. case "ON":
  9193. case "OFF":
  9194. case "Toggle":
  9195. operator = elem;
  9196. continue;
  9197. }
  9198. const group = this.#groups.get(elem);
  9199. if (!group) {
  9200. continue;
  9201. }
  9202. switch (operator) {
  9203. case "ON":
  9204. this.setVisibility(elem, true, preserveRB);
  9205. break;
  9206. case "OFF":
  9207. this.setVisibility(elem, false, preserveRB);
  9208. break;
  9209. case "Toggle":
  9210. this.setVisibility(elem, !group.visible, preserveRB);
  9211. break;
  9212. }
  9213. }
  9214. this.#cachedGetHash = null;
  9215. }
  9216. get hasInitialVisibility() {
  9217. return this.#initialHash === null || this.getHash() === this.#initialHash;
  9218. }
  9219. getOrder() {
  9220. if (!this.#groups.size) {
  9221. return null;
  9222. }
  9223. if (this.#order) {
  9224. return this.#order.slice();
  9225. }
  9226. return [...this.#groups.keys()];
  9227. }
  9228. getGroups() {
  9229. return this.#groups.size > 0 ? objectFromMap(this.#groups) : null;
  9230. }
  9231. getGroup(id) {
  9232. return this.#groups.get(id) || null;
  9233. }
  9234. getHash() {
  9235. if (this.#cachedGetHash !== null) {
  9236. return this.#cachedGetHash;
  9237. }
  9238. const hash = new MurmurHash3_64();
  9239. for (const [id, group] of this.#groups) {
  9240. hash.update(`${id}:${group.visible}`);
  9241. }
  9242. return this.#cachedGetHash = hash.hexdigest();
  9243. }
  9244. }
  9245. ;// ./src/display/transport_stream.js
  9246. class PDFDataTransportStream {
  9247. constructor(pdfDataRangeTransport, {
  9248. disableRange = false,
  9249. disableStream = false
  9250. }) {
  9251. assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  9252. const {
  9253. length,
  9254. initialData,
  9255. progressiveDone,
  9256. contentDispositionFilename
  9257. } = pdfDataRangeTransport;
  9258. this._queuedChunks = [];
  9259. this._progressiveDone = progressiveDone;
  9260. this._contentDispositionFilename = contentDispositionFilename;
  9261. if (initialData?.length > 0) {
  9262. const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
  9263. this._queuedChunks.push(buffer);
  9264. }
  9265. this._pdfDataRangeTransport = pdfDataRangeTransport;
  9266. this._isStreamingSupported = !disableStream;
  9267. this._isRangeSupported = !disableRange;
  9268. this._contentLength = length;
  9269. this._fullRequestReader = null;
  9270. this._rangeReaders = [];
  9271. pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  9272. this._onReceiveData({
  9273. begin,
  9274. chunk
  9275. });
  9276. });
  9277. pdfDataRangeTransport.addProgressListener((loaded, total) => {
  9278. this._onProgress({
  9279. loaded,
  9280. total
  9281. });
  9282. });
  9283. pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  9284. this._onReceiveData({
  9285. chunk
  9286. });
  9287. });
  9288. pdfDataRangeTransport.addProgressiveDoneListener(() => {
  9289. this._onProgressiveDone();
  9290. });
  9291. pdfDataRangeTransport.transportReady();
  9292. }
  9293. _onReceiveData({
  9294. begin,
  9295. chunk
  9296. }) {
  9297. const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
  9298. if (begin === undefined) {
  9299. if (this._fullRequestReader) {
  9300. this._fullRequestReader._enqueue(buffer);
  9301. } else {
  9302. this._queuedChunks.push(buffer);
  9303. }
  9304. } else {
  9305. const found = this._rangeReaders.some(function (rangeReader) {
  9306. if (rangeReader._begin !== begin) {
  9307. return false;
  9308. }
  9309. rangeReader._enqueue(buffer);
  9310. return true;
  9311. });
  9312. assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  9313. }
  9314. }
  9315. get _progressiveDataLength() {
  9316. return this._fullRequestReader?._loaded ?? 0;
  9317. }
  9318. _onProgress(evt) {
  9319. if (evt.total === undefined) {
  9320. this._rangeReaders[0]?.onProgress?.({
  9321. loaded: evt.loaded
  9322. });
  9323. } else {
  9324. this._fullRequestReader?.onProgress?.({
  9325. loaded: evt.loaded,
  9326. total: evt.total
  9327. });
  9328. }
  9329. }
  9330. _onProgressiveDone() {
  9331. this._fullRequestReader?.progressiveDone();
  9332. this._progressiveDone = true;
  9333. }
  9334. _removeRangeReader(reader) {
  9335. const i = this._rangeReaders.indexOf(reader);
  9336. if (i >= 0) {
  9337. this._rangeReaders.splice(i, 1);
  9338. }
  9339. }
  9340. getFullReader() {
  9341. assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  9342. const queuedChunks = this._queuedChunks;
  9343. this._queuedChunks = null;
  9344. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  9345. }
  9346. getRangeReader(begin, end) {
  9347. if (end <= this._progressiveDataLength) {
  9348. return null;
  9349. }
  9350. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  9351. this._pdfDataRangeTransport.requestDataRange(begin, end);
  9352. this._rangeReaders.push(reader);
  9353. return reader;
  9354. }
  9355. cancelAllRequests(reason) {
  9356. this._fullRequestReader?.cancel(reason);
  9357. for (const reader of this._rangeReaders.slice(0)) {
  9358. reader.cancel(reason);
  9359. }
  9360. this._pdfDataRangeTransport.abort();
  9361. }
  9362. }
  9363. class PDFDataTransportStreamReader {
  9364. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  9365. this._stream = stream;
  9366. this._done = progressiveDone || false;
  9367. this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
  9368. this._queuedChunks = queuedChunks || [];
  9369. this._loaded = 0;
  9370. for (const chunk of this._queuedChunks) {
  9371. this._loaded += chunk.byteLength;
  9372. }
  9373. this._requests = [];
  9374. this._headersReady = Promise.resolve();
  9375. stream._fullRequestReader = this;
  9376. this.onProgress = null;
  9377. }
  9378. _enqueue(chunk) {
  9379. if (this._done) {
  9380. return;
  9381. }
  9382. if (this._requests.length > 0) {
  9383. const requestCapability = this._requests.shift();
  9384. requestCapability.resolve({
  9385. value: chunk,
  9386. done: false
  9387. });
  9388. } else {
  9389. this._queuedChunks.push(chunk);
  9390. }
  9391. this._loaded += chunk.byteLength;
  9392. }
  9393. get headersReady() {
  9394. return this._headersReady;
  9395. }
  9396. get filename() {
  9397. return this._filename;
  9398. }
  9399. get isRangeSupported() {
  9400. return this._stream._isRangeSupported;
  9401. }
  9402. get isStreamingSupported() {
  9403. return this._stream._isStreamingSupported;
  9404. }
  9405. get contentLength() {
  9406. return this._stream._contentLength;
  9407. }
  9408. async read() {
  9409. if (this._queuedChunks.length > 0) {
  9410. const chunk = this._queuedChunks.shift();
  9411. return {
  9412. value: chunk,
  9413. done: false
  9414. };
  9415. }
  9416. if (this._done) {
  9417. return {
  9418. value: undefined,
  9419. done: true
  9420. };
  9421. }
  9422. const requestCapability = Promise.withResolvers();
  9423. this._requests.push(requestCapability);
  9424. return requestCapability.promise;
  9425. }
  9426. cancel(reason) {
  9427. this._done = true;
  9428. for (const requestCapability of this._requests) {
  9429. requestCapability.resolve({
  9430. value: undefined,
  9431. done: true
  9432. });
  9433. }
  9434. this._requests.length = 0;
  9435. }
  9436. progressiveDone() {
  9437. if (this._done) {
  9438. return;
  9439. }
  9440. this._done = true;
  9441. }
  9442. }
  9443. class PDFDataTransportStreamRangeReader {
  9444. constructor(stream, begin, end) {
  9445. this._stream = stream;
  9446. this._begin = begin;
  9447. this._end = end;
  9448. this._queuedChunk = null;
  9449. this._requests = [];
  9450. this._done = false;
  9451. this.onProgress = null;
  9452. }
  9453. _enqueue(chunk) {
  9454. if (this._done) {
  9455. return;
  9456. }
  9457. if (this._requests.length === 0) {
  9458. this._queuedChunk = chunk;
  9459. } else {
  9460. const requestsCapability = this._requests.shift();
  9461. requestsCapability.resolve({
  9462. value: chunk,
  9463. done: false
  9464. });
  9465. for (const requestCapability of this._requests) {
  9466. requestCapability.resolve({
  9467. value: undefined,
  9468. done: true
  9469. });
  9470. }
  9471. this._requests.length = 0;
  9472. }
  9473. this._done = true;
  9474. this._stream._removeRangeReader(this);
  9475. }
  9476. get isStreamingSupported() {
  9477. return false;
  9478. }
  9479. async read() {
  9480. if (this._queuedChunk) {
  9481. const chunk = this._queuedChunk;
  9482. this._queuedChunk = null;
  9483. return {
  9484. value: chunk,
  9485. done: false
  9486. };
  9487. }
  9488. if (this._done) {
  9489. return {
  9490. value: undefined,
  9491. done: true
  9492. };
  9493. }
  9494. const requestCapability = Promise.withResolvers();
  9495. this._requests.push(requestCapability);
  9496. return requestCapability.promise;
  9497. }
  9498. cancel(reason) {
  9499. this._done = true;
  9500. for (const requestCapability of this._requests) {
  9501. requestCapability.resolve({
  9502. value: undefined,
  9503. done: true
  9504. });
  9505. }
  9506. this._requests.length = 0;
  9507. this._stream._removeRangeReader(this);
  9508. }
  9509. }
  9510. ;// ./src/display/content_disposition.js
  9511. function getFilenameFromContentDispositionHeader(contentDisposition) {
  9512. let needsEncodingFixup = true;
  9513. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  9514. if (tmp) {
  9515. tmp = tmp[1];
  9516. let filename = rfc2616unquote(tmp);
  9517. filename = unescape(filename);
  9518. filename = rfc5987decode(filename);
  9519. filename = rfc2047decode(filename);
  9520. return fixupEncoding(filename);
  9521. }
  9522. tmp = rfc2231getparam(contentDisposition);
  9523. if (tmp) {
  9524. const filename = rfc2047decode(tmp);
  9525. return fixupEncoding(filename);
  9526. }
  9527. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  9528. if (tmp) {
  9529. tmp = tmp[1];
  9530. let filename = rfc2616unquote(tmp);
  9531. filename = rfc2047decode(filename);
  9532. return fixupEncoding(filename);
  9533. }
  9534. function toParamRegExp(attributePattern, flags) {
  9535. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  9536. }
  9537. function textdecode(encoding, value) {
  9538. if (encoding) {
  9539. if (!/^[\x00-\xFF]+$/.test(value)) {
  9540. return value;
  9541. }
  9542. try {
  9543. const decoder = new TextDecoder(encoding, {
  9544. fatal: true
  9545. });
  9546. const buffer = stringToBytes(value);
  9547. value = decoder.decode(buffer);
  9548. needsEncodingFixup = false;
  9549. } catch {}
  9550. }
  9551. return value;
  9552. }
  9553. function fixupEncoding(value) {
  9554. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  9555. value = textdecode("utf-8", value);
  9556. if (needsEncodingFixup) {
  9557. value = textdecode("iso-8859-1", value);
  9558. }
  9559. }
  9560. return value;
  9561. }
  9562. function rfc2231getparam(contentDispositionStr) {
  9563. const matches = [];
  9564. let match;
  9565. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  9566. while ((match = iter.exec(contentDispositionStr)) !== null) {
  9567. let [, n, quot, part] = match;
  9568. n = parseInt(n, 10);
  9569. if (n in matches) {
  9570. if (n === 0) {
  9571. break;
  9572. }
  9573. continue;
  9574. }
  9575. matches[n] = [quot, part];
  9576. }
  9577. const parts = [];
  9578. for (let n = 0; n < matches.length; ++n) {
  9579. if (!(n in matches)) {
  9580. break;
  9581. }
  9582. let [quot, part] = matches[n];
  9583. part = rfc2616unquote(part);
  9584. if (quot) {
  9585. part = unescape(part);
  9586. if (n === 0) {
  9587. part = rfc5987decode(part);
  9588. }
  9589. }
  9590. parts.push(part);
  9591. }
  9592. return parts.join("");
  9593. }
  9594. function rfc2616unquote(value) {
  9595. if (value.startsWith('"')) {
  9596. const parts = value.slice(1).split('\\"');
  9597. for (let i = 0; i < parts.length; ++i) {
  9598. const quotindex = parts[i].indexOf('"');
  9599. if (quotindex !== -1) {
  9600. parts[i] = parts[i].slice(0, quotindex);
  9601. parts.length = i + 1;
  9602. }
  9603. parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
  9604. }
  9605. value = parts.join('"');
  9606. }
  9607. return value;
  9608. }
  9609. function rfc5987decode(extvalue) {
  9610. const encodingend = extvalue.indexOf("'");
  9611. if (encodingend === -1) {
  9612. return extvalue;
  9613. }
  9614. const encoding = extvalue.slice(0, encodingend);
  9615. const langvalue = extvalue.slice(encodingend + 1);
  9616. const value = langvalue.replace(/^[^']*'/, "");
  9617. return textdecode(encoding, value);
  9618. }
  9619. function rfc2047decode(value) {
  9620. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  9621. return value;
  9622. }
  9623. return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  9624. if (encoding === "q" || encoding === "Q") {
  9625. text = text.replaceAll("_", " ");
  9626. text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  9627. return String.fromCharCode(parseInt(hex, 16));
  9628. });
  9629. return textdecode(charset, text);
  9630. }
  9631. try {
  9632. text = atob(text);
  9633. } catch {}
  9634. return textdecode(charset, text);
  9635. });
  9636. }
  9637. return "";
  9638. }
  9639. ;// ./src/display/network_utils.js
  9640. function createHeaders(isHttp, httpHeaders) {
  9641. const headers = new Headers();
  9642. if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {
  9643. return headers;
  9644. }
  9645. for (const key in httpHeaders) {
  9646. const val = httpHeaders[key];
  9647. if (val !== undefined) {
  9648. headers.append(key, val);
  9649. }
  9650. }
  9651. return headers;
  9652. }
  9653. function validateRangeRequestCapabilities({
  9654. responseHeaders,
  9655. isHttp,
  9656. rangeChunkSize,
  9657. disableRange
  9658. }) {
  9659. const returnValues = {
  9660. allowRangeRequests: false,
  9661. suggestedLength: undefined
  9662. };
  9663. const length = parseInt(responseHeaders.get("Content-Length"), 10);
  9664. if (!Number.isInteger(length)) {
  9665. return returnValues;
  9666. }
  9667. returnValues.suggestedLength = length;
  9668. if (length <= 2 * rangeChunkSize) {
  9669. return returnValues;
  9670. }
  9671. if (disableRange || !isHttp) {
  9672. return returnValues;
  9673. }
  9674. if (responseHeaders.get("Accept-Ranges") !== "bytes") {
  9675. return returnValues;
  9676. }
  9677. const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";
  9678. if (contentEncoding !== "identity") {
  9679. return returnValues;
  9680. }
  9681. returnValues.allowRangeRequests = true;
  9682. return returnValues;
  9683. }
  9684. function extractFilenameFromHeader(responseHeaders) {
  9685. const contentDisposition = responseHeaders.get("Content-Disposition");
  9686. if (contentDisposition) {
  9687. let filename = getFilenameFromContentDispositionHeader(contentDisposition);
  9688. if (filename.includes("%")) {
  9689. try {
  9690. filename = decodeURIComponent(filename);
  9691. } catch {}
  9692. }
  9693. if (isPdfFile(filename)) {
  9694. return filename;
  9695. }
  9696. }
  9697. return null;
  9698. }
  9699. function createResponseStatusError(status, url) {
  9700. if (status === 404 || status === 0 && url.startsWith("file:")) {
  9701. return new MissingPDFException('Missing PDF "' + url + '".');
  9702. }
  9703. return new UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  9704. }
  9705. function validateResponseStatus(status) {
  9706. return status === 200 || status === 206;
  9707. }
  9708. ;// ./src/display/fetch_stream.js
  9709. function createFetchOptions(headers, withCredentials, abortController) {
  9710. return {
  9711. method: "GET",
  9712. headers,
  9713. signal: abortController.signal,
  9714. mode: "cors",
  9715. credentials: withCredentials ? "include" : "same-origin",
  9716. redirect: "follow"
  9717. };
  9718. }
  9719. function getArrayBuffer(val) {
  9720. if (val instanceof Uint8Array) {
  9721. return val.buffer;
  9722. }
  9723. if (val instanceof ArrayBuffer) {
  9724. return val;
  9725. }
  9726. warn(`getArrayBuffer - unexpected data format: ${val}`);
  9727. return new Uint8Array(val).buffer;
  9728. }
  9729. class PDFFetchStream {
  9730. constructor(source) {
  9731. this.source = source;
  9732. this.isHttp = /^https?:/i.test(source.url);
  9733. this.headers = createHeaders(this.isHttp, source.httpHeaders);
  9734. this._fullRequestReader = null;
  9735. this._rangeRequestReaders = [];
  9736. }
  9737. get _progressiveDataLength() {
  9738. return this._fullRequestReader?._loaded ?? 0;
  9739. }
  9740. getFullReader() {
  9741. assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  9742. this._fullRequestReader = new PDFFetchStreamReader(this);
  9743. return this._fullRequestReader;
  9744. }
  9745. getRangeReader(begin, end) {
  9746. if (end <= this._progressiveDataLength) {
  9747. return null;
  9748. }
  9749. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  9750. this._rangeRequestReaders.push(reader);
  9751. return reader;
  9752. }
  9753. cancelAllRequests(reason) {
  9754. this._fullRequestReader?.cancel(reason);
  9755. for (const reader of this._rangeRequestReaders.slice(0)) {
  9756. reader.cancel(reason);
  9757. }
  9758. }
  9759. }
  9760. class PDFFetchStreamReader {
  9761. constructor(stream) {
  9762. this._stream = stream;
  9763. this._reader = null;
  9764. this._loaded = 0;
  9765. this._filename = null;
  9766. const source = stream.source;
  9767. this._withCredentials = source.withCredentials || false;
  9768. this._contentLength = source.length;
  9769. this._headersCapability = Promise.withResolvers();
  9770. this._disableRange = source.disableRange || false;
  9771. this._rangeChunkSize = source.rangeChunkSize;
  9772. if (!this._rangeChunkSize && !this._disableRange) {
  9773. this._disableRange = true;
  9774. }
  9775. this._abortController = new AbortController();
  9776. this._isStreamingSupported = !source.disableStream;
  9777. this._isRangeSupported = !source.disableRange;
  9778. const headers = new Headers(stream.headers);
  9779. const url = source.url;
  9780. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  9781. if (!validateResponseStatus(response.status)) {
  9782. throw createResponseStatusError(response.status, url);
  9783. }
  9784. this._reader = response.body.getReader();
  9785. this._headersCapability.resolve();
  9786. const responseHeaders = response.headers;
  9787. const {
  9788. allowRangeRequests,
  9789. suggestedLength
  9790. } = validateRangeRequestCapabilities({
  9791. responseHeaders,
  9792. isHttp: stream.isHttp,
  9793. rangeChunkSize: this._rangeChunkSize,
  9794. disableRange: this._disableRange
  9795. });
  9796. this._isRangeSupported = allowRangeRequests;
  9797. this._contentLength = suggestedLength || this._contentLength;
  9798. this._filename = extractFilenameFromHeader(responseHeaders);
  9799. if (!this._isStreamingSupported && this._isRangeSupported) {
  9800. this.cancel(new AbortException("Streaming is disabled."));
  9801. }
  9802. }).catch(this._headersCapability.reject);
  9803. this.onProgress = null;
  9804. }
  9805. get headersReady() {
  9806. return this._headersCapability.promise;
  9807. }
  9808. get filename() {
  9809. return this._filename;
  9810. }
  9811. get contentLength() {
  9812. return this._contentLength;
  9813. }
  9814. get isRangeSupported() {
  9815. return this._isRangeSupported;
  9816. }
  9817. get isStreamingSupported() {
  9818. return this._isStreamingSupported;
  9819. }
  9820. async read() {
  9821. await this._headersCapability.promise;
  9822. const {
  9823. value,
  9824. done
  9825. } = await this._reader.read();
  9826. if (done) {
  9827. return {
  9828. value,
  9829. done
  9830. };
  9831. }
  9832. this._loaded += value.byteLength;
  9833. this.onProgress?.({
  9834. loaded: this._loaded,
  9835. total: this._contentLength
  9836. });
  9837. return {
  9838. value: getArrayBuffer(value),
  9839. done: false
  9840. };
  9841. }
  9842. cancel(reason) {
  9843. this._reader?.cancel(reason);
  9844. this._abortController.abort();
  9845. }
  9846. }
  9847. class PDFFetchStreamRangeReader {
  9848. constructor(stream, begin, end) {
  9849. this._stream = stream;
  9850. this._reader = null;
  9851. this._loaded = 0;
  9852. const source = stream.source;
  9853. this._withCredentials = source.withCredentials || false;
  9854. this._readCapability = Promise.withResolvers();
  9855. this._isStreamingSupported = !source.disableStream;
  9856. this._abortController = new AbortController();
  9857. const headers = new Headers(stream.headers);
  9858. headers.append("Range", `bytes=${begin}-${end - 1}`);
  9859. const url = source.url;
  9860. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  9861. if (!validateResponseStatus(response.status)) {
  9862. throw createResponseStatusError(response.status, url);
  9863. }
  9864. this._readCapability.resolve();
  9865. this._reader = response.body.getReader();
  9866. }).catch(this._readCapability.reject);
  9867. this.onProgress = null;
  9868. }
  9869. get isStreamingSupported() {
  9870. return this._isStreamingSupported;
  9871. }
  9872. async read() {
  9873. await this._readCapability.promise;
  9874. const {
  9875. value,
  9876. done
  9877. } = await this._reader.read();
  9878. if (done) {
  9879. return {
  9880. value,
  9881. done
  9882. };
  9883. }
  9884. this._loaded += value.byteLength;
  9885. this.onProgress?.({
  9886. loaded: this._loaded
  9887. });
  9888. return {
  9889. value: getArrayBuffer(value),
  9890. done: false
  9891. };
  9892. }
  9893. cancel(reason) {
  9894. this._reader?.cancel(reason);
  9895. this._abortController.abort();
  9896. }
  9897. }
  9898. ;// ./src/display/network.js
  9899. const OK_RESPONSE = 200;
  9900. const PARTIAL_CONTENT_RESPONSE = 206;
  9901. function network_getArrayBuffer(xhr) {
  9902. const data = xhr.response;
  9903. if (typeof data !== "string") {
  9904. return data;
  9905. }
  9906. return stringToBytes(data).buffer;
  9907. }
  9908. class NetworkManager {
  9909. constructor({
  9910. url,
  9911. httpHeaders,
  9912. withCredentials
  9913. }) {
  9914. this.url = url;
  9915. this.isHttp = /^https?:/i.test(url);
  9916. this.headers = createHeaders(this.isHttp, httpHeaders);
  9917. this.withCredentials = withCredentials || false;
  9918. this.currXhrId = 0;
  9919. this.pendingRequests = Object.create(null);
  9920. }
  9921. requestRange(begin, end, listeners) {
  9922. const args = {
  9923. begin,
  9924. end
  9925. };
  9926. for (const prop in listeners) {
  9927. args[prop] = listeners[prop];
  9928. }
  9929. return this.request(args);
  9930. }
  9931. requestFull(listeners) {
  9932. return this.request(listeners);
  9933. }
  9934. request(args) {
  9935. const xhr = new XMLHttpRequest();
  9936. const xhrId = this.currXhrId++;
  9937. const pendingRequest = this.pendingRequests[xhrId] = {
  9938. xhr
  9939. };
  9940. xhr.open("GET", this.url);
  9941. xhr.withCredentials = this.withCredentials;
  9942. for (const [key, val] of this.headers) {
  9943. xhr.setRequestHeader(key, val);
  9944. }
  9945. if (this.isHttp && "begin" in args && "end" in args) {
  9946. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  9947. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  9948. } else {
  9949. pendingRequest.expectedStatus = OK_RESPONSE;
  9950. }
  9951. xhr.responseType = "arraybuffer";
  9952. if (args.onError) {
  9953. xhr.onerror = function (evt) {
  9954. args.onError(xhr.status);
  9955. };
  9956. }
  9957. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  9958. xhr.onprogress = this.onProgress.bind(this, xhrId);
  9959. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  9960. pendingRequest.onDone = args.onDone;
  9961. pendingRequest.onError = args.onError;
  9962. pendingRequest.onProgress = args.onProgress;
  9963. xhr.send(null);
  9964. return xhrId;
  9965. }
  9966. onProgress(xhrId, evt) {
  9967. const pendingRequest = this.pendingRequests[xhrId];
  9968. if (!pendingRequest) {
  9969. return;
  9970. }
  9971. pendingRequest.onProgress?.(evt);
  9972. }
  9973. onStateChange(xhrId, evt) {
  9974. const pendingRequest = this.pendingRequests[xhrId];
  9975. if (!pendingRequest) {
  9976. return;
  9977. }
  9978. const xhr = pendingRequest.xhr;
  9979. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  9980. pendingRequest.onHeadersReceived();
  9981. delete pendingRequest.onHeadersReceived;
  9982. }
  9983. if (xhr.readyState !== 4) {
  9984. return;
  9985. }
  9986. if (!(xhrId in this.pendingRequests)) {
  9987. return;
  9988. }
  9989. delete this.pendingRequests[xhrId];
  9990. if (xhr.status === 0 && this.isHttp) {
  9991. pendingRequest.onError?.(xhr.status);
  9992. return;
  9993. }
  9994. const xhrStatus = xhr.status || OK_RESPONSE;
  9995. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  9996. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  9997. pendingRequest.onError?.(xhr.status);
  9998. return;
  9999. }
  10000. const chunk = network_getArrayBuffer(xhr);
  10001. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  10002. const rangeHeader = xhr.getResponseHeader("Content-Range");
  10003. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  10004. pendingRequest.onDone({
  10005. begin: parseInt(matches[1], 10),
  10006. chunk
  10007. });
  10008. } else if (chunk) {
  10009. pendingRequest.onDone({
  10010. begin: 0,
  10011. chunk
  10012. });
  10013. } else {
  10014. pendingRequest.onError?.(xhr.status);
  10015. }
  10016. }
  10017. getRequestXhr(xhrId) {
  10018. return this.pendingRequests[xhrId].xhr;
  10019. }
  10020. isPendingRequest(xhrId) {
  10021. return xhrId in this.pendingRequests;
  10022. }
  10023. abortRequest(xhrId) {
  10024. const xhr = this.pendingRequests[xhrId].xhr;
  10025. delete this.pendingRequests[xhrId];
  10026. xhr.abort();
  10027. }
  10028. }
  10029. class PDFNetworkStream {
  10030. constructor(source) {
  10031. this._source = source;
  10032. this._manager = new NetworkManager(source);
  10033. this._rangeChunkSize = source.rangeChunkSize;
  10034. this._fullRequestReader = null;
  10035. this._rangeRequestReaders = [];
  10036. }
  10037. _onRangeRequestReaderClosed(reader) {
  10038. const i = this._rangeRequestReaders.indexOf(reader);
  10039. if (i >= 0) {
  10040. this._rangeRequestReaders.splice(i, 1);
  10041. }
  10042. }
  10043. getFullReader() {
  10044. assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  10045. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  10046. return this._fullRequestReader;
  10047. }
  10048. getRangeReader(begin, end) {
  10049. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  10050. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  10051. this._rangeRequestReaders.push(reader);
  10052. return reader;
  10053. }
  10054. cancelAllRequests(reason) {
  10055. this._fullRequestReader?.cancel(reason);
  10056. for (const reader of this._rangeRequestReaders.slice(0)) {
  10057. reader.cancel(reason);
  10058. }
  10059. }
  10060. }
  10061. class PDFNetworkStreamFullRequestReader {
  10062. constructor(manager, source) {
  10063. this._manager = manager;
  10064. const args = {
  10065. onHeadersReceived: this._onHeadersReceived.bind(this),
  10066. onDone: this._onDone.bind(this),
  10067. onError: this._onError.bind(this),
  10068. onProgress: this._onProgress.bind(this)
  10069. };
  10070. this._url = source.url;
  10071. this._fullRequestId = manager.requestFull(args);
  10072. this._headersCapability = Promise.withResolvers();
  10073. this._disableRange = source.disableRange || false;
  10074. this._contentLength = source.length;
  10075. this._rangeChunkSize = source.rangeChunkSize;
  10076. if (!this._rangeChunkSize && !this._disableRange) {
  10077. this._disableRange = true;
  10078. }
  10079. this._isStreamingSupported = false;
  10080. this._isRangeSupported = false;
  10081. this._cachedChunks = [];
  10082. this._requests = [];
  10083. this._done = false;
  10084. this._storedError = undefined;
  10085. this._filename = null;
  10086. this.onProgress = null;
  10087. }
  10088. _onHeadersReceived() {
  10089. const fullRequestXhrId = this._fullRequestId;
  10090. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  10091. const responseHeaders = new Headers(fullRequestXhr.getAllResponseHeaders().trim().split(/[\r\n]+/).map(x => {
  10092. const [key, ...val] = x.split(": ");
  10093. return [key, val.join(": ")];
  10094. }));
  10095. const {
  10096. allowRangeRequests,
  10097. suggestedLength
  10098. } = validateRangeRequestCapabilities({
  10099. responseHeaders,
  10100. isHttp: this._manager.isHttp,
  10101. rangeChunkSize: this._rangeChunkSize,
  10102. disableRange: this._disableRange
  10103. });
  10104. if (allowRangeRequests) {
  10105. this._isRangeSupported = true;
  10106. }
  10107. this._contentLength = suggestedLength || this._contentLength;
  10108. this._filename = extractFilenameFromHeader(responseHeaders);
  10109. if (this._isRangeSupported) {
  10110. this._manager.abortRequest(fullRequestXhrId);
  10111. }
  10112. this._headersCapability.resolve();
  10113. }
  10114. _onDone(data) {
  10115. if (data) {
  10116. if (this._requests.length > 0) {
  10117. const requestCapability = this._requests.shift();
  10118. requestCapability.resolve({
  10119. value: data.chunk,
  10120. done: false
  10121. });
  10122. } else {
  10123. this._cachedChunks.push(data.chunk);
  10124. }
  10125. }
  10126. this._done = true;
  10127. if (this._cachedChunks.length > 0) {
  10128. return;
  10129. }
  10130. for (const requestCapability of this._requests) {
  10131. requestCapability.resolve({
  10132. value: undefined,
  10133. done: true
  10134. });
  10135. }
  10136. this._requests.length = 0;
  10137. }
  10138. _onError(status) {
  10139. this._storedError = createResponseStatusError(status, this._url);
  10140. this._headersCapability.reject(this._storedError);
  10141. for (const requestCapability of this._requests) {
  10142. requestCapability.reject(this._storedError);
  10143. }
  10144. this._requests.length = 0;
  10145. this._cachedChunks.length = 0;
  10146. }
  10147. _onProgress(evt) {
  10148. this.onProgress?.({
  10149. loaded: evt.loaded,
  10150. total: evt.lengthComputable ? evt.total : this._contentLength
  10151. });
  10152. }
  10153. get filename() {
  10154. return this._filename;
  10155. }
  10156. get isRangeSupported() {
  10157. return this._isRangeSupported;
  10158. }
  10159. get isStreamingSupported() {
  10160. return this._isStreamingSupported;
  10161. }
  10162. get contentLength() {
  10163. return this._contentLength;
  10164. }
  10165. get headersReady() {
  10166. return this._headersCapability.promise;
  10167. }
  10168. async read() {
  10169. if (this._storedError) {
  10170. throw this._storedError;
  10171. }
  10172. if (this._cachedChunks.length > 0) {
  10173. const chunk = this._cachedChunks.shift();
  10174. return {
  10175. value: chunk,
  10176. done: false
  10177. };
  10178. }
  10179. if (this._done) {
  10180. return {
  10181. value: undefined,
  10182. done: true
  10183. };
  10184. }
  10185. const requestCapability = Promise.withResolvers();
  10186. this._requests.push(requestCapability);
  10187. return requestCapability.promise;
  10188. }
  10189. cancel(reason) {
  10190. this._done = true;
  10191. this._headersCapability.reject(reason);
  10192. for (const requestCapability of this._requests) {
  10193. requestCapability.resolve({
  10194. value: undefined,
  10195. done: true
  10196. });
  10197. }
  10198. this._requests.length = 0;
  10199. if (this._manager.isPendingRequest(this._fullRequestId)) {
  10200. this._manager.abortRequest(this._fullRequestId);
  10201. }
  10202. this._fullRequestReader = null;
  10203. }
  10204. }
  10205. class PDFNetworkStreamRangeRequestReader {
  10206. constructor(manager, begin, end) {
  10207. this._manager = manager;
  10208. const args = {
  10209. onDone: this._onDone.bind(this),
  10210. onError: this._onError.bind(this),
  10211. onProgress: this._onProgress.bind(this)
  10212. };
  10213. this._url = manager.url;
  10214. this._requestId = manager.requestRange(begin, end, args);
  10215. this._requests = [];
  10216. this._queuedChunk = null;
  10217. this._done = false;
  10218. this._storedError = undefined;
  10219. this.onProgress = null;
  10220. this.onClosed = null;
  10221. }
  10222. _close() {
  10223. this.onClosed?.(this);
  10224. }
  10225. _onDone(data) {
  10226. const chunk = data.chunk;
  10227. if (this._requests.length > 0) {
  10228. const requestCapability = this._requests.shift();
  10229. requestCapability.resolve({
  10230. value: chunk,
  10231. done: false
  10232. });
  10233. } else {
  10234. this._queuedChunk = chunk;
  10235. }
  10236. this._done = true;
  10237. for (const requestCapability of this._requests) {
  10238. requestCapability.resolve({
  10239. value: undefined,
  10240. done: true
  10241. });
  10242. }
  10243. this._requests.length = 0;
  10244. this._close();
  10245. }
  10246. _onError(status) {
  10247. this._storedError = createResponseStatusError(status, this._url);
  10248. for (const requestCapability of this._requests) {
  10249. requestCapability.reject(this._storedError);
  10250. }
  10251. this._requests.length = 0;
  10252. this._queuedChunk = null;
  10253. }
  10254. _onProgress(evt) {
  10255. if (!this.isStreamingSupported) {
  10256. this.onProgress?.({
  10257. loaded: evt.loaded
  10258. });
  10259. }
  10260. }
  10261. get isStreamingSupported() {
  10262. return false;
  10263. }
  10264. async read() {
  10265. if (this._storedError) {
  10266. throw this._storedError;
  10267. }
  10268. if (this._queuedChunk !== null) {
  10269. const chunk = this._queuedChunk;
  10270. this._queuedChunk = null;
  10271. return {
  10272. value: chunk,
  10273. done: false
  10274. };
  10275. }
  10276. if (this._done) {
  10277. return {
  10278. value: undefined,
  10279. done: true
  10280. };
  10281. }
  10282. const requestCapability = Promise.withResolvers();
  10283. this._requests.push(requestCapability);
  10284. return requestCapability.promise;
  10285. }
  10286. cancel(reason) {
  10287. this._done = true;
  10288. for (const requestCapability of this._requests) {
  10289. requestCapability.resolve({
  10290. value: undefined,
  10291. done: true
  10292. });
  10293. }
  10294. this._requests.length = 0;
  10295. if (this._manager.isPendingRequest(this._requestId)) {
  10296. this._manager.abortRequest(this._requestId);
  10297. }
  10298. this._close();
  10299. }
  10300. }
  10301. ;// ./src/display/node_stream.js
  10302. const urlRegex = /^[a-z][a-z0-9\-+.]+:/i;
  10303. function parseUrlOrPath(sourceUrl) {
  10304. if (urlRegex.test(sourceUrl)) {
  10305. return new URL(sourceUrl);
  10306. }
  10307. const url = NodePackages.get("url");
  10308. return new URL(url.pathToFileURL(sourceUrl));
  10309. }
  10310. function createRequest(url, headers, callback) {
  10311. if (url.protocol === "http:") {
  10312. const http = NodePackages.get("http");
  10313. return http.request(url, {
  10314. headers
  10315. }, callback);
  10316. }
  10317. const https = NodePackages.get("https");
  10318. return https.request(url, {
  10319. headers
  10320. }, callback);
  10321. }
  10322. class PDFNodeStream {
  10323. constructor(source) {
  10324. this.source = source;
  10325. this.url = parseUrlOrPath(source.url);
  10326. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  10327. this.isFsUrl = this.url.protocol === "file:";
  10328. this.headers = createHeaders(this.isHttp, source.httpHeaders);
  10329. this._fullRequestReader = null;
  10330. this._rangeRequestReaders = [];
  10331. }
  10332. get _progressiveDataLength() {
  10333. return this._fullRequestReader?._loaded ?? 0;
  10334. }
  10335. getFullReader() {
  10336. assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  10337. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  10338. return this._fullRequestReader;
  10339. }
  10340. getRangeReader(start, end) {
  10341. if (end <= this._progressiveDataLength) {
  10342. return null;
  10343. }
  10344. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  10345. this._rangeRequestReaders.push(rangeReader);
  10346. return rangeReader;
  10347. }
  10348. cancelAllRequests(reason) {
  10349. this._fullRequestReader?.cancel(reason);
  10350. for (const reader of this._rangeRequestReaders.slice(0)) {
  10351. reader.cancel(reason);
  10352. }
  10353. }
  10354. }
  10355. class BaseFullReader {
  10356. constructor(stream) {
  10357. this._url = stream.url;
  10358. this._done = false;
  10359. this._storedError = null;
  10360. this.onProgress = null;
  10361. const source = stream.source;
  10362. this._contentLength = source.length;
  10363. this._loaded = 0;
  10364. this._filename = null;
  10365. this._disableRange = source.disableRange || false;
  10366. this._rangeChunkSize = source.rangeChunkSize;
  10367. if (!this._rangeChunkSize && !this._disableRange) {
  10368. this._disableRange = true;
  10369. }
  10370. this._isStreamingSupported = !source.disableStream;
  10371. this._isRangeSupported = !source.disableRange;
  10372. this._readableStream = null;
  10373. this._readCapability = Promise.withResolvers();
  10374. this._headersCapability = Promise.withResolvers();
  10375. }
  10376. get headersReady() {
  10377. return this._headersCapability.promise;
  10378. }
  10379. get filename() {
  10380. return this._filename;
  10381. }
  10382. get contentLength() {
  10383. return this._contentLength;
  10384. }
  10385. get isRangeSupported() {
  10386. return this._isRangeSupported;
  10387. }
  10388. get isStreamingSupported() {
  10389. return this._isStreamingSupported;
  10390. }
  10391. async read() {
  10392. await this._readCapability.promise;
  10393. if (this._done) {
  10394. return {
  10395. value: undefined,
  10396. done: true
  10397. };
  10398. }
  10399. if (this._storedError) {
  10400. throw this._storedError;
  10401. }
  10402. const chunk = this._readableStream.read();
  10403. if (chunk === null) {
  10404. this._readCapability = Promise.withResolvers();
  10405. return this.read();
  10406. }
  10407. this._loaded += chunk.length;
  10408. this.onProgress?.({
  10409. loaded: this._loaded,
  10410. total: this._contentLength
  10411. });
  10412. const buffer = new Uint8Array(chunk).buffer;
  10413. return {
  10414. value: buffer,
  10415. done: false
  10416. };
  10417. }
  10418. cancel(reason) {
  10419. if (!this._readableStream) {
  10420. this._error(reason);
  10421. return;
  10422. }
  10423. this._readableStream.destroy(reason);
  10424. }
  10425. _error(reason) {
  10426. this._storedError = reason;
  10427. this._readCapability.resolve();
  10428. }
  10429. _setReadableStream(readableStream) {
  10430. this._readableStream = readableStream;
  10431. readableStream.on("readable", () => {
  10432. this._readCapability.resolve();
  10433. });
  10434. readableStream.on("end", () => {
  10435. readableStream.destroy();
  10436. this._done = true;
  10437. this._readCapability.resolve();
  10438. });
  10439. readableStream.on("error", reason => {
  10440. this._error(reason);
  10441. });
  10442. if (!this._isStreamingSupported && this._isRangeSupported) {
  10443. this._error(new AbortException("streaming is disabled"));
  10444. }
  10445. if (this._storedError) {
  10446. this._readableStream.destroy(this._storedError);
  10447. }
  10448. }
  10449. }
  10450. class BaseRangeReader {
  10451. constructor(stream) {
  10452. this._url = stream.url;
  10453. this._done = false;
  10454. this._storedError = null;
  10455. this.onProgress = null;
  10456. this._loaded = 0;
  10457. this._readableStream = null;
  10458. this._readCapability = Promise.withResolvers();
  10459. const source = stream.source;
  10460. this._isStreamingSupported = !source.disableStream;
  10461. }
  10462. get isStreamingSupported() {
  10463. return this._isStreamingSupported;
  10464. }
  10465. async read() {
  10466. await this._readCapability.promise;
  10467. if (this._done) {
  10468. return {
  10469. value: undefined,
  10470. done: true
  10471. };
  10472. }
  10473. if (this._storedError) {
  10474. throw this._storedError;
  10475. }
  10476. const chunk = this._readableStream.read();
  10477. if (chunk === null) {
  10478. this._readCapability = Promise.withResolvers();
  10479. return this.read();
  10480. }
  10481. this._loaded += chunk.length;
  10482. this.onProgress?.({
  10483. loaded: this._loaded
  10484. });
  10485. const buffer = new Uint8Array(chunk).buffer;
  10486. return {
  10487. value: buffer,
  10488. done: false
  10489. };
  10490. }
  10491. cancel(reason) {
  10492. if (!this._readableStream) {
  10493. this._error(reason);
  10494. return;
  10495. }
  10496. this._readableStream.destroy(reason);
  10497. }
  10498. _error(reason) {
  10499. this._storedError = reason;
  10500. this._readCapability.resolve();
  10501. }
  10502. _setReadableStream(readableStream) {
  10503. this._readableStream = readableStream;
  10504. readableStream.on("readable", () => {
  10505. this._readCapability.resolve();
  10506. });
  10507. readableStream.on("end", () => {
  10508. readableStream.destroy();
  10509. this._done = true;
  10510. this._readCapability.resolve();
  10511. });
  10512. readableStream.on("error", reason => {
  10513. this._error(reason);
  10514. });
  10515. if (this._storedError) {
  10516. this._readableStream.destroy(this._storedError);
  10517. }
  10518. }
  10519. }
  10520. class PDFNodeStreamFullReader extends BaseFullReader {
  10521. constructor(stream) {
  10522. super(stream);
  10523. const headers = Object.fromEntries(stream.headers);
  10524. const handleResponse = response => {
  10525. if (response.statusCode === 404) {
  10526. const error = new MissingPDFException(`Missing PDF "${this._url}".`);
  10527. this._storedError = error;
  10528. this._headersCapability.reject(error);
  10529. return;
  10530. }
  10531. this._headersCapability.resolve();
  10532. this._setReadableStream(response);
  10533. const responseHeaders = new Headers(this._readableStream.headers);
  10534. const {
  10535. allowRangeRequests,
  10536. suggestedLength
  10537. } = validateRangeRequestCapabilities({
  10538. responseHeaders,
  10539. isHttp: stream.isHttp,
  10540. rangeChunkSize: this._rangeChunkSize,
  10541. disableRange: this._disableRange
  10542. });
  10543. this._isRangeSupported = allowRangeRequests;
  10544. this._contentLength = suggestedLength || this._contentLength;
  10545. this._filename = extractFilenameFromHeader(responseHeaders);
  10546. };
  10547. this._request = createRequest(this._url, headers, handleResponse);
  10548. this._request.on("error", reason => {
  10549. this._storedError = reason;
  10550. this._headersCapability.reject(reason);
  10551. });
  10552. this._request.end();
  10553. }
  10554. }
  10555. class PDFNodeStreamRangeReader extends BaseRangeReader {
  10556. constructor(stream, start, end) {
  10557. super(stream);
  10558. const headers = Object.fromEntries(stream.headers);
  10559. headers.Range = `bytes=${start}-${end - 1}`;
  10560. const handleResponse = response => {
  10561. if (response.statusCode === 404) {
  10562. const error = new MissingPDFException(`Missing PDF "${this._url}".`);
  10563. this._storedError = error;
  10564. return;
  10565. }
  10566. this._setReadableStream(response);
  10567. };
  10568. this._request = createRequest(this._url, headers, handleResponse);
  10569. this._request.on("error", reason => {
  10570. this._storedError = reason;
  10571. });
  10572. this._request.end();
  10573. }
  10574. }
  10575. class PDFNodeStreamFsFullReader extends BaseFullReader {
  10576. constructor(stream) {
  10577. super(stream);
  10578. const fs = NodePackages.get("fs");
  10579. fs.promises.lstat(this._url).then(stat => {
  10580. this._contentLength = stat.size;
  10581. this._setReadableStream(fs.createReadStream(this._url));
  10582. this._headersCapability.resolve();
  10583. }, error => {
  10584. if (error.code === "ENOENT") {
  10585. error = new MissingPDFException(`Missing PDF "${this._url}".`);
  10586. }
  10587. this._storedError = error;
  10588. this._headersCapability.reject(error);
  10589. });
  10590. }
  10591. }
  10592. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  10593. constructor(stream, start, end) {
  10594. super(stream);
  10595. const fs = NodePackages.get("fs");
  10596. this._setReadableStream(fs.createReadStream(this._url, {
  10597. start,
  10598. end: end - 1
  10599. }));
  10600. }
  10601. }
  10602. ;// ./src/display/text_layer.js
  10603. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  10604. const DEFAULT_FONT_SIZE = 30;
  10605. const DEFAULT_FONT_ASCENT = 0.8;
  10606. class TextLayer {
  10607. #capability = Promise.withResolvers();
  10608. #container = null;
  10609. #disableProcessItems = false;
  10610. #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  10611. #lang = null;
  10612. #layoutTextParams = null;
  10613. #pageHeight = 0;
  10614. #pageWidth = 0;
  10615. #reader = null;
  10616. #rootContainer = null;
  10617. #rotation = 0;
  10618. #scale = 0;
  10619. #styleCache = Object.create(null);
  10620. #textContentItemsStr = [];
  10621. #textContentSource = null;
  10622. #textDivs = [];
  10623. #textDivProperties = new WeakMap();
  10624. #transform = null;
  10625. static #ascentCache = new Map();
  10626. static #canvasContexts = new Map();
  10627. static #canvasCtxFonts = new WeakMap();
  10628. static #minFontSize = null;
  10629. static #pendingTextLayers = new Set();
  10630. constructor({
  10631. textContentSource,
  10632. container,
  10633. viewport
  10634. }) {
  10635. if (textContentSource instanceof ReadableStream) {
  10636. this.#textContentSource = textContentSource;
  10637. } else if (typeof textContentSource === "object") {
  10638. this.#textContentSource = new ReadableStream({
  10639. start(controller) {
  10640. controller.enqueue(textContentSource);
  10641. controller.close();
  10642. }
  10643. });
  10644. } else {
  10645. throw new Error('No "textContentSource" parameter specified.');
  10646. }
  10647. this.#container = this.#rootContainer = container;
  10648. this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  10649. this.#rotation = viewport.rotation;
  10650. this.#layoutTextParams = {
  10651. div: null,
  10652. properties: null,
  10653. ctx: null
  10654. };
  10655. const {
  10656. pageWidth,
  10657. pageHeight,
  10658. pageX,
  10659. pageY
  10660. } = viewport.rawDims;
  10661. this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
  10662. this.#pageWidth = pageWidth;
  10663. this.#pageHeight = pageHeight;
  10664. TextLayer.#ensureMinFontSizeComputed();
  10665. setLayerDimensions(container, viewport);
  10666. this.#capability.promise.finally(() => {
  10667. TextLayer.#pendingTextLayers.delete(this);
  10668. this.#layoutTextParams = null;
  10669. this.#styleCache = null;
  10670. }).catch(() => {});
  10671. }
  10672. static get fontFamilyMap() {
  10673. const {
  10674. isWindows,
  10675. isFirefox
  10676. } = util_FeatureTest.platform;
  10677. return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));
  10678. }
  10679. render() {
  10680. const pump = () => {
  10681. this.#reader.read().then(({
  10682. value,
  10683. done
  10684. }) => {
  10685. if (done) {
  10686. this.#capability.resolve();
  10687. return;
  10688. }
  10689. this.#lang ??= value.lang;
  10690. Object.assign(this.#styleCache, value.styles);
  10691. this.#processItems(value.items);
  10692. pump();
  10693. }, this.#capability.reject);
  10694. };
  10695. this.#reader = this.#textContentSource.getReader();
  10696. TextLayer.#pendingTextLayers.add(this);
  10697. pump();
  10698. return this.#capability.promise;
  10699. }
  10700. update({
  10701. viewport,
  10702. onBefore = null
  10703. }) {
  10704. const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  10705. const rotation = viewport.rotation;
  10706. if (rotation !== this.#rotation) {
  10707. onBefore?.();
  10708. this.#rotation = rotation;
  10709. setLayerDimensions(this.#rootContainer, {
  10710. rotation
  10711. });
  10712. }
  10713. if (scale !== this.#scale) {
  10714. onBefore?.();
  10715. this.#scale = scale;
  10716. const params = {
  10717. div: null,
  10718. properties: null,
  10719. ctx: TextLayer.#getCtx(this.#lang)
  10720. };
  10721. for (const div of this.#textDivs) {
  10722. params.properties = this.#textDivProperties.get(div);
  10723. params.div = div;
  10724. this.#layout(params);
  10725. }
  10726. }
  10727. }
  10728. cancel() {
  10729. const abortEx = new AbortException("TextLayer task cancelled.");
  10730. this.#reader?.cancel(abortEx).catch(() => {});
  10731. this.#reader = null;
  10732. this.#capability.reject(abortEx);
  10733. }
  10734. get textDivs() {
  10735. return this.#textDivs;
  10736. }
  10737. get textContentItemsStr() {
  10738. return this.#textContentItemsStr;
  10739. }
  10740. #processItems(items) {
  10741. if (this.#disableProcessItems) {
  10742. return;
  10743. }
  10744. this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);
  10745. const textDivs = this.#textDivs,
  10746. textContentItemsStr = this.#textContentItemsStr;
  10747. for (const item of items) {
  10748. if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
  10749. warn("Ignoring additional textDivs for performance reasons.");
  10750. this.#disableProcessItems = true;
  10751. return;
  10752. }
  10753. if (item.str === undefined) {
  10754. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  10755. const parent = this.#container;
  10756. this.#container = document.createElement("span");
  10757. this.#container.classList.add("markedContent");
  10758. if (item.id !== null) {
  10759. this.#container.setAttribute("id", `${item.id}`);
  10760. }
  10761. parent.append(this.#container);
  10762. } else if (item.type === "endMarkedContent") {
  10763. this.#container = this.#container.parentNode;
  10764. }
  10765. continue;
  10766. }
  10767. textContentItemsStr.push(item.str);
  10768. this.#appendText(item);
  10769. }
  10770. }
  10771. #appendText(geom) {
  10772. const textDiv = document.createElement("span");
  10773. const textDivProperties = {
  10774. angle: 0,
  10775. canvasWidth: 0,
  10776. hasText: geom.str !== "",
  10777. hasEOL: geom.hasEOL,
  10778. fontSize: 0
  10779. };
  10780. this.#textDivs.push(textDiv);
  10781. const tx = Util.transform(this.#transform, geom.transform);
  10782. let angle = Math.atan2(tx[1], tx[0]);
  10783. const style = this.#styleCache[geom.fontName];
  10784. if (style.vertical) {
  10785. angle += Math.PI / 2;
  10786. }
  10787. let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
  10788. fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
  10789. const fontHeight = Math.hypot(tx[2], tx[3]);
  10790. const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, this.#lang);
  10791. let left, top;
  10792. if (angle === 0) {
  10793. left = tx[4];
  10794. top = tx[5] - fontAscent;
  10795. } else {
  10796. left = tx[4] + fontAscent * Math.sin(angle);
  10797. top = tx[5] - fontAscent * Math.cos(angle);
  10798. }
  10799. const scaleFactorStr = "calc(var(--scale-factor)*";
  10800. const divStyle = textDiv.style;
  10801. if (this.#container === this.#rootContainer) {
  10802. divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
  10803. divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
  10804. } else {
  10805. divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
  10806. divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  10807. }
  10808. divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;
  10809. divStyle.fontFamily = fontFamily;
  10810. textDivProperties.fontSize = fontHeight;
  10811. textDiv.setAttribute("role", "presentation");
  10812. textDiv.textContent = geom.str;
  10813. textDiv.dir = geom.dir;
  10814. if (this.#fontInspectorEnabled) {
  10815. textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
  10816. }
  10817. if (angle !== 0) {
  10818. textDivProperties.angle = angle * (180 / Math.PI);
  10819. }
  10820. let shouldScaleText = false;
  10821. if (geom.str.length > 1) {
  10822. shouldScaleText = true;
  10823. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  10824. const absScaleX = Math.abs(geom.transform[0]),
  10825. absScaleY = Math.abs(geom.transform[3]);
  10826. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  10827. shouldScaleText = true;
  10828. }
  10829. }
  10830. if (shouldScaleText) {
  10831. textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  10832. }
  10833. this.#textDivProperties.set(textDiv, textDivProperties);
  10834. this.#layoutTextParams.div = textDiv;
  10835. this.#layoutTextParams.properties = textDivProperties;
  10836. this.#layout(this.#layoutTextParams);
  10837. if (textDivProperties.hasText) {
  10838. this.#container.append(textDiv);
  10839. }
  10840. if (textDivProperties.hasEOL) {
  10841. const br = document.createElement("br");
  10842. br.setAttribute("role", "presentation");
  10843. this.#container.append(br);
  10844. }
  10845. }
  10846. #layout(params) {
  10847. const {
  10848. div,
  10849. properties,
  10850. ctx
  10851. } = params;
  10852. const {
  10853. style
  10854. } = div;
  10855. let transform = "";
  10856. if (TextLayer.#minFontSize > 1) {
  10857. transform = `scale(${1 / TextLayer.#minFontSize})`;
  10858. }
  10859. if (properties.canvasWidth !== 0 && properties.hasText) {
  10860. const {
  10861. fontFamily
  10862. } = style;
  10863. const {
  10864. canvasWidth,
  10865. fontSize
  10866. } = properties;
  10867. TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);
  10868. const {
  10869. width
  10870. } = ctx.measureText(div.textContent);
  10871. if (width > 0) {
  10872. transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`;
  10873. }
  10874. }
  10875. if (properties.angle !== 0) {
  10876. transform = `rotate(${properties.angle}deg) ${transform}`;
  10877. }
  10878. if (transform.length > 0) {
  10879. style.transform = transform;
  10880. }
  10881. }
  10882. static cleanup() {
  10883. if (this.#pendingTextLayers.size > 0) {
  10884. return;
  10885. }
  10886. this.#ascentCache.clear();
  10887. for (const {
  10888. canvas
  10889. } of this.#canvasContexts.values()) {
  10890. canvas.remove();
  10891. }
  10892. this.#canvasContexts.clear();
  10893. }
  10894. static #getCtx(lang = null) {
  10895. let ctx = this.#canvasContexts.get(lang ||= "");
  10896. if (!ctx) {
  10897. const canvas = document.createElement("canvas");
  10898. canvas.className = "hiddenCanvasElement";
  10899. canvas.lang = lang;
  10900. document.body.append(canvas);
  10901. ctx = canvas.getContext("2d", {
  10902. alpha: false,
  10903. willReadFrequently: true
  10904. });
  10905. this.#canvasContexts.set(lang, ctx);
  10906. this.#canvasCtxFonts.set(ctx, {
  10907. size: 0,
  10908. family: ""
  10909. });
  10910. }
  10911. return ctx;
  10912. }
  10913. static #ensureCtxFont(ctx, size, family) {
  10914. const cached = this.#canvasCtxFonts.get(ctx);
  10915. if (size === cached.size && family === cached.family) {
  10916. return;
  10917. }
  10918. ctx.font = `${size}px ${family}`;
  10919. cached.size = size;
  10920. cached.family = family;
  10921. }
  10922. static #ensureMinFontSizeComputed() {
  10923. if (this.#minFontSize !== null) {
  10924. return;
  10925. }
  10926. const div = document.createElement("div");
  10927. div.style.opacity = 0;
  10928. div.style.lineHeight = 1;
  10929. div.style.fontSize = "1px";
  10930. div.style.position = "absolute";
  10931. div.textContent = "X";
  10932. document.body.append(div);
  10933. this.#minFontSize = div.getBoundingClientRect().height;
  10934. div.remove();
  10935. }
  10936. static #getAscent(fontFamily, lang) {
  10937. const cachedAscent = this.#ascentCache.get(fontFamily);
  10938. if (cachedAscent) {
  10939. return cachedAscent;
  10940. }
  10941. const ctx = this.#getCtx(lang);
  10942. ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
  10943. this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);
  10944. const metrics = ctx.measureText("");
  10945. let ascent = metrics.fontBoundingBoxAscent;
  10946. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  10947. if (ascent) {
  10948. const ratio = ascent / (ascent + descent);
  10949. this.#ascentCache.set(fontFamily, ratio);
  10950. ctx.canvas.width = ctx.canvas.height = 0;
  10951. return ratio;
  10952. }
  10953. ctx.strokeStyle = "red";
  10954. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  10955. ctx.strokeText("g", 0, 0);
  10956. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  10957. descent = 0;
  10958. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  10959. if (pixels[i] > 0) {
  10960. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  10961. break;
  10962. }
  10963. }
  10964. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  10965. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  10966. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  10967. ascent = 0;
  10968. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  10969. if (pixels[i] > 0) {
  10970. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  10971. break;
  10972. }
  10973. }
  10974. ctx.canvas.width = ctx.canvas.height = 0;
  10975. const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT;
  10976. this.#ascentCache.set(fontFamily, ratio);
  10977. return ratio;
  10978. }
  10979. }
  10980. ;// ./src/display/xfa_text.js
  10981. class XfaText {
  10982. static textContent(xfa) {
  10983. const items = [];
  10984. const output = {
  10985. items,
  10986. styles: Object.create(null)
  10987. };
  10988. function walk(node) {
  10989. if (!node) {
  10990. return;
  10991. }
  10992. let str = null;
  10993. const name = node.name;
  10994. if (name === "#text") {
  10995. str = node.value;
  10996. } else if (!XfaText.shouldBuildText(name)) {
  10997. return;
  10998. } else if (node?.attributes?.textContent) {
  10999. str = node.attributes.textContent;
  11000. } else if (node.value) {
  11001. str = node.value;
  11002. }
  11003. if (str !== null) {
  11004. items.push({
  11005. str
  11006. });
  11007. }
  11008. if (!node.children) {
  11009. return;
  11010. }
  11011. for (const child of node.children) {
  11012. walk(child);
  11013. }
  11014. }
  11015. walk(xfa);
  11016. return output;
  11017. }
  11018. static shouldBuildText(name) {
  11019. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  11020. }
  11021. }
  11022. ;// ./src/display/api.js
  11023. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  11024. const RENDERING_CANCELLED_TIMEOUT = 100;
  11025. const DELAYED_CLEANUP_TIMEOUT = 5000;
  11026. const DefaultCanvasFactory = isNodeJS ? NodeCanvasFactory : DOMCanvasFactory;
  11027. const DefaultCMapReaderFactory = isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory;
  11028. const DefaultFilterFactory = isNodeJS ? NodeFilterFactory : DOMFilterFactory;
  11029. const DefaultStandardFontDataFactory = isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory;
  11030. function getDocument(src = {}) {
  11031. if (typeof src === "string" || src instanceof URL) {
  11032. src = {
  11033. url: src
  11034. };
  11035. } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
  11036. src = {
  11037. data: src
  11038. };
  11039. }
  11040. const task = new PDFDocumentLoadingTask();
  11041. const {
  11042. docId
  11043. } = task;
  11044. const url = src.url ? getUrlProp(src.url) : null;
  11045. const data = src.data ? getDataProp(src.data) : null;
  11046. const httpHeaders = src.httpHeaders || null;
  11047. const withCredentials = src.withCredentials === true;
  11048. const password = src.password ?? null;
  11049. const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  11050. const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
  11051. let worker = src.worker instanceof PDFWorker ? src.worker : null;
  11052. const verbosity = src.verbosity;
  11053. const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
  11054. const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
  11055. const cMapPacked = src.cMapPacked !== false;
  11056. const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
  11057. const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
  11058. const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
  11059. const ignoreErrors = src.stopAtErrors !== true;
  11060. const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  11061. const isEvalSupported = src.isEvalSupported !== false;
  11062. const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
  11063. const isChrome = typeof src.isChrome === "boolean" ? src.isChrome : !util_FeatureTest.platform.isFirefox && typeof window !== "undefined" && !!window?.chrome;
  11064. const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
  11065. const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
  11066. const fontExtraProperties = src.fontExtraProperties === true;
  11067. const enableXfa = src.enableXfa === true;
  11068. const ownerDocument = src.ownerDocument || globalThis.document;
  11069. const disableRange = src.disableRange === true;
  11070. const disableStream = src.disableStream === true;
  11071. const disableAutoFetch = src.disableAutoFetch === true;
  11072. const pdfBug = src.pdfBug === true;
  11073. const CanvasFactory = src.CanvasFactory || DefaultCanvasFactory;
  11074. const FilterFactory = src.FilterFactory || DefaultFilterFactory;
  11075. const enableHWA = src.enableHWA === true;
  11076. const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  11077. const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
  11078. const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI);
  11079. if (src.canvasFactory) {
  11080. deprecated("`canvasFactory`-instance option, please use `CanvasFactory` instead.");
  11081. }
  11082. if (src.filterFactory) {
  11083. deprecated("`filterFactory`-instance option, please use `FilterFactory` instead.");
  11084. }
  11085. const styleElement = null;
  11086. setVerbosityLevel(verbosity);
  11087. const transportFactory = {
  11088. canvasFactory: new CanvasFactory({
  11089. ownerDocument,
  11090. enableHWA
  11091. }),
  11092. filterFactory: new FilterFactory({
  11093. docId,
  11094. ownerDocument
  11095. }),
  11096. cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({
  11097. baseUrl: cMapUrl,
  11098. isCompressed: cMapPacked
  11099. }),
  11100. standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({
  11101. baseUrl: standardFontDataUrl
  11102. })
  11103. };
  11104. if (!worker) {
  11105. const workerParams = {
  11106. verbosity,
  11107. port: GlobalWorkerOptions.workerPort
  11108. };
  11109. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  11110. task._worker = worker;
  11111. }
  11112. const docParams = {
  11113. docId,
  11114. apiVersion: "4.8.69",
  11115. data,
  11116. password,
  11117. disableAutoFetch,
  11118. rangeChunkSize,
  11119. length,
  11120. docBaseUrl,
  11121. enableXfa,
  11122. evaluatorOptions: {
  11123. maxImageSize,
  11124. disableFontFace,
  11125. ignoreErrors,
  11126. isEvalSupported,
  11127. isOffscreenCanvasSupported,
  11128. isChrome,
  11129. canvasMaxAreaInBytes,
  11130. fontExtraProperties,
  11131. useSystemFonts,
  11132. cMapUrl: useWorkerFetch ? cMapUrl : null,
  11133. standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
  11134. }
  11135. };
  11136. const transportParams = {
  11137. disableFontFace,
  11138. fontExtraProperties,
  11139. ownerDocument,
  11140. pdfBug,
  11141. styleElement,
  11142. loadingParams: {
  11143. disableAutoFetch,
  11144. enableXfa
  11145. }
  11146. };
  11147. worker.promise.then(function () {
  11148. if (task.destroyed) {
  11149. throw new Error("Loading aborted");
  11150. }
  11151. if (worker.destroyed) {
  11152. throw new Error("Worker was destroyed");
  11153. }
  11154. const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
  11155. let networkStream;
  11156. if (rangeTransport) {
  11157. networkStream = new PDFDataTransportStream(rangeTransport, {
  11158. disableRange,
  11159. disableStream
  11160. });
  11161. } else if (!data) {
  11162. if (!url) {
  11163. throw new Error("getDocument - no `url` parameter provided.");
  11164. }
  11165. let NetworkStream;
  11166. if (isNodeJS) {
  11167. const isFetchSupported = typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype;
  11168. NetworkStream = isFetchSupported && isValidFetchUrl(url) ? PDFFetchStream : PDFNodeStream;
  11169. } else {
  11170. NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : PDFNetworkStream;
  11171. }
  11172. networkStream = new NetworkStream({
  11173. url,
  11174. length,
  11175. httpHeaders,
  11176. withCredentials,
  11177. rangeChunkSize,
  11178. disableRange,
  11179. disableStream
  11180. });
  11181. }
  11182. return workerIdPromise.then(workerId => {
  11183. if (task.destroyed) {
  11184. throw new Error("Loading aborted");
  11185. }
  11186. if (worker.destroyed) {
  11187. throw new Error("Worker was destroyed");
  11188. }
  11189. const messageHandler = new MessageHandler(docId, workerId, worker.port);
  11190. const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
  11191. task._transport = transport;
  11192. messageHandler.send("Ready", null);
  11193. });
  11194. }).catch(task._capability.reject);
  11195. return task;
  11196. }
  11197. function getUrlProp(val) {
  11198. if (val instanceof URL) {
  11199. return val.href;
  11200. }
  11201. try {
  11202. return new URL(val, window.location).href;
  11203. } catch {
  11204. if (isNodeJS && typeof val === "string") {
  11205. return val;
  11206. }
  11207. }
  11208. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  11209. }
  11210. function getDataProp(val) {
  11211. if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
  11212. throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
  11213. }
  11214. if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
  11215. return val;
  11216. }
  11217. if (typeof val === "string") {
  11218. return stringToBytes(val);
  11219. }
  11220. if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) {
  11221. return new Uint8Array(val);
  11222. }
  11223. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  11224. }
  11225. function isRefProxy(ref) {
  11226. return typeof ref === "object" && Number.isInteger(ref?.num) && ref.num >= 0 && Number.isInteger(ref?.gen) && ref.gen >= 0;
  11227. }
  11228. class PDFDocumentLoadingTask {
  11229. static #docId = 0;
  11230. constructor() {
  11231. this._capability = Promise.withResolvers();
  11232. this._transport = null;
  11233. this._worker = null;
  11234. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  11235. this.destroyed = false;
  11236. this.onPassword = null;
  11237. this.onProgress = null;
  11238. }
  11239. get promise() {
  11240. return this._capability.promise;
  11241. }
  11242. async destroy() {
  11243. this.destroyed = true;
  11244. try {
  11245. if (this._worker?.port) {
  11246. this._worker._pendingDestroy = true;
  11247. }
  11248. await this._transport?.destroy();
  11249. } catch (ex) {
  11250. if (this._worker?.port) {
  11251. delete this._worker._pendingDestroy;
  11252. }
  11253. throw ex;
  11254. }
  11255. this._transport = null;
  11256. if (this._worker) {
  11257. this._worker.destroy();
  11258. this._worker = null;
  11259. }
  11260. }
  11261. }
  11262. class PDFDataRangeTransport {
  11263. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  11264. this.length = length;
  11265. this.initialData = initialData;
  11266. this.progressiveDone = progressiveDone;
  11267. this.contentDispositionFilename = contentDispositionFilename;
  11268. this._rangeListeners = [];
  11269. this._progressListeners = [];
  11270. this._progressiveReadListeners = [];
  11271. this._progressiveDoneListeners = [];
  11272. this._readyCapability = Promise.withResolvers();
  11273. }
  11274. addRangeListener(listener) {
  11275. this._rangeListeners.push(listener);
  11276. }
  11277. addProgressListener(listener) {
  11278. this._progressListeners.push(listener);
  11279. }
  11280. addProgressiveReadListener(listener) {
  11281. this._progressiveReadListeners.push(listener);
  11282. }
  11283. addProgressiveDoneListener(listener) {
  11284. this._progressiveDoneListeners.push(listener);
  11285. }
  11286. onDataRange(begin, chunk) {
  11287. for (const listener of this._rangeListeners) {
  11288. listener(begin, chunk);
  11289. }
  11290. }
  11291. onDataProgress(loaded, total) {
  11292. this._readyCapability.promise.then(() => {
  11293. for (const listener of this._progressListeners) {
  11294. listener(loaded, total);
  11295. }
  11296. });
  11297. }
  11298. onDataProgressiveRead(chunk) {
  11299. this._readyCapability.promise.then(() => {
  11300. for (const listener of this._progressiveReadListeners) {
  11301. listener(chunk);
  11302. }
  11303. });
  11304. }
  11305. onDataProgressiveDone() {
  11306. this._readyCapability.promise.then(() => {
  11307. for (const listener of this._progressiveDoneListeners) {
  11308. listener();
  11309. }
  11310. });
  11311. }
  11312. transportReady() {
  11313. this._readyCapability.resolve();
  11314. }
  11315. requestDataRange(begin, end) {
  11316. unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
  11317. }
  11318. abort() {}
  11319. }
  11320. class PDFDocumentProxy {
  11321. constructor(pdfInfo, transport) {
  11322. this._pdfInfo = pdfInfo;
  11323. this._transport = transport;
  11324. }
  11325. get annotationStorage() {
  11326. return this._transport.annotationStorage;
  11327. }
  11328. get canvasFactory() {
  11329. return this._transport.canvasFactory;
  11330. }
  11331. get filterFactory() {
  11332. return this._transport.filterFactory;
  11333. }
  11334. get numPages() {
  11335. return this._pdfInfo.numPages;
  11336. }
  11337. get fingerprints() {
  11338. return this._pdfInfo.fingerprints;
  11339. }
  11340. get isPureXfa() {
  11341. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  11342. }
  11343. get allXfaHtml() {
  11344. return this._transport._htmlForXfa;
  11345. }
  11346. getPage(pageNumber) {
  11347. return this._transport.getPage(pageNumber);
  11348. }
  11349. getPageIndex(ref) {
  11350. return this._transport.getPageIndex(ref);
  11351. }
  11352. getDestinations() {
  11353. return this._transport.getDestinations();
  11354. }
  11355. getDestination(id) {
  11356. return this._transport.getDestination(id);
  11357. }
  11358. getPageLabels() {
  11359. return this._transport.getPageLabels();
  11360. }
  11361. getPageLayout() {
  11362. return this._transport.getPageLayout();
  11363. }
  11364. getPageMode() {
  11365. return this._transport.getPageMode();
  11366. }
  11367. getViewerPreferences() {
  11368. return this._transport.getViewerPreferences();
  11369. }
  11370. getOpenAction() {
  11371. return this._transport.getOpenAction();
  11372. }
  11373. getAttachments() {
  11374. return this._transport.getAttachments();
  11375. }
  11376. getJSActions() {
  11377. return this._transport.getDocJSActions();
  11378. }
  11379. getOutline() {
  11380. return this._transport.getOutline();
  11381. }
  11382. getOptionalContentConfig({
  11383. intent = "display"
  11384. } = {}) {
  11385. const {
  11386. renderingIntent
  11387. } = this._transport.getRenderingIntent(intent);
  11388. return this._transport.getOptionalContentConfig(renderingIntent);
  11389. }
  11390. getPermissions() {
  11391. return this._transport.getPermissions();
  11392. }
  11393. getMetadata() {
  11394. return this._transport.getMetadata();
  11395. }
  11396. getMarkInfo() {
  11397. return this._transport.getMarkInfo();
  11398. }
  11399. getData() {
  11400. return this._transport.getData();
  11401. }
  11402. saveDocument() {
  11403. return this._transport.saveDocument();
  11404. }
  11405. getDownloadInfo() {
  11406. return this._transport.downloadInfoCapability.promise;
  11407. }
  11408. cleanup(keepLoadedFonts = false) {
  11409. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  11410. }
  11411. destroy() {
  11412. return this.loadingTask.destroy();
  11413. }
  11414. cachedPageNumber(ref) {
  11415. return this._transport.cachedPageNumber(ref);
  11416. }
  11417. get loadingParams() {
  11418. return this._transport.loadingParams;
  11419. }
  11420. get loadingTask() {
  11421. return this._transport.loadingTask;
  11422. }
  11423. getFieldObjects() {
  11424. return this._transport.getFieldObjects();
  11425. }
  11426. hasJSActions() {
  11427. return this._transport.hasJSActions();
  11428. }
  11429. getCalculationOrderIds() {
  11430. return this._transport.getCalculationOrderIds();
  11431. }
  11432. }
  11433. class PDFPageProxy {
  11434. #delayedCleanupTimeout = null;
  11435. #pendingCleanup = false;
  11436. constructor(pageIndex, pageInfo, transport, pdfBug = false) {
  11437. this._pageIndex = pageIndex;
  11438. this._pageInfo = pageInfo;
  11439. this._transport = transport;
  11440. this._stats = pdfBug ? new StatTimer() : null;
  11441. this._pdfBug = pdfBug;
  11442. this.commonObjs = transport.commonObjs;
  11443. this.objs = new PDFObjects();
  11444. this._maybeCleanupAfterRender = false;
  11445. this._intentStates = new Map();
  11446. this.destroyed = false;
  11447. }
  11448. get pageNumber() {
  11449. return this._pageIndex + 1;
  11450. }
  11451. get rotate() {
  11452. return this._pageInfo.rotate;
  11453. }
  11454. get ref() {
  11455. return this._pageInfo.ref;
  11456. }
  11457. get userUnit() {
  11458. return this._pageInfo.userUnit;
  11459. }
  11460. get view() {
  11461. return this._pageInfo.view;
  11462. }
  11463. getViewport({
  11464. scale,
  11465. rotation = this.rotate,
  11466. offsetX = 0,
  11467. offsetY = 0,
  11468. dontFlip = false
  11469. } = {}) {
  11470. return new PageViewport({
  11471. viewBox: this.view,
  11472. scale,
  11473. rotation,
  11474. offsetX,
  11475. offsetY,
  11476. dontFlip
  11477. });
  11478. }
  11479. getAnnotations({
  11480. intent = "display"
  11481. } = {}) {
  11482. const {
  11483. renderingIntent
  11484. } = this._transport.getRenderingIntent(intent);
  11485. return this._transport.getAnnotations(this._pageIndex, renderingIntent);
  11486. }
  11487. getJSActions() {
  11488. return this._transport.getPageJSActions(this._pageIndex);
  11489. }
  11490. get filterFactory() {
  11491. return this._transport.filterFactory;
  11492. }
  11493. get isPureXfa() {
  11494. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  11495. }
  11496. async getXfa() {
  11497. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  11498. }
  11499. render({
  11500. canvasContext,
  11501. viewport,
  11502. intent = "display",
  11503. annotationMode = AnnotationMode.ENABLE,
  11504. transform = null,
  11505. background = null,
  11506. optionalContentConfigPromise = null,
  11507. annotationCanvasMap = null,
  11508. pageColors = null,
  11509. printAnnotationStorage = null,
  11510. isEditing = false
  11511. }) {
  11512. this._stats?.time("Overall");
  11513. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);
  11514. const {
  11515. renderingIntent,
  11516. cacheKey
  11517. } = intentArgs;
  11518. this.#pendingCleanup = false;
  11519. this.#abortDelayedCleanup();
  11520. optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
  11521. let intentState = this._intentStates.get(cacheKey);
  11522. if (!intentState) {
  11523. intentState = Object.create(null);
  11524. this._intentStates.set(cacheKey, intentState);
  11525. }
  11526. if (intentState.streamReaderCancelTimeout) {
  11527. clearTimeout(intentState.streamReaderCancelTimeout);
  11528. intentState.streamReaderCancelTimeout = null;
  11529. }
  11530. const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  11531. if (!intentState.displayReadyCapability) {
  11532. intentState.displayReadyCapability = Promise.withResolvers();
  11533. intentState.operatorList = {
  11534. fnArray: [],
  11535. argsArray: [],
  11536. lastChunk: false,
  11537. separateAnnots: null
  11538. };
  11539. this._stats?.time("Page Request");
  11540. this._pumpOperatorList(intentArgs);
  11541. }
  11542. const complete = error => {
  11543. intentState.renderTasks.delete(internalRenderTask);
  11544. if (this._maybeCleanupAfterRender || intentPrint) {
  11545. this.#pendingCleanup = true;
  11546. }
  11547. this.#tryCleanup(!intentPrint);
  11548. if (error) {
  11549. internalRenderTask.capability.reject(error);
  11550. this._abortOperatorList({
  11551. intentState,
  11552. reason: error instanceof Error ? error : new Error(error)
  11553. });
  11554. } else {
  11555. internalRenderTask.capability.resolve();
  11556. }
  11557. if (this._stats) {
  11558. this._stats.timeEnd("Rendering");
  11559. this._stats.timeEnd("Overall");
  11560. if (globalThis.Stats?.enabled) {
  11561. globalThis.Stats.add(this.pageNumber, this._stats);
  11562. }
  11563. }
  11564. };
  11565. const internalRenderTask = new InternalRenderTask({
  11566. callback: complete,
  11567. params: {
  11568. canvasContext,
  11569. viewport,
  11570. transform,
  11571. background
  11572. },
  11573. objs: this.objs,
  11574. commonObjs: this.commonObjs,
  11575. annotationCanvasMap,
  11576. operatorList: intentState.operatorList,
  11577. pageIndex: this._pageIndex,
  11578. canvasFactory: this._transport.canvasFactory,
  11579. filterFactory: this._transport.filterFactory,
  11580. useRequestAnimationFrame: !intentPrint,
  11581. pdfBug: this._pdfBug,
  11582. pageColors
  11583. });
  11584. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  11585. const renderTask = internalRenderTask.task;
  11586. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  11587. if (this.destroyed) {
  11588. complete();
  11589. return;
  11590. }
  11591. this._stats?.time("Rendering");
  11592. if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
  11593. throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods.");
  11594. }
  11595. internalRenderTask.initializeGraphics({
  11596. transparency,
  11597. optionalContentConfig
  11598. });
  11599. internalRenderTask.operatorListChanged();
  11600. }).catch(complete);
  11601. return renderTask;
  11602. }
  11603. getOperatorList({
  11604. intent = "display",
  11605. annotationMode = AnnotationMode.ENABLE,
  11606. printAnnotationStorage = null,
  11607. isEditing = false
  11608. } = {}) {
  11609. function operatorListChanged() {
  11610. if (intentState.operatorList.lastChunk) {
  11611. intentState.opListReadCapability.resolve(intentState.operatorList);
  11612. intentState.renderTasks.delete(opListTask);
  11613. }
  11614. }
  11615. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);
  11616. let intentState = this._intentStates.get(intentArgs.cacheKey);
  11617. if (!intentState) {
  11618. intentState = Object.create(null);
  11619. this._intentStates.set(intentArgs.cacheKey, intentState);
  11620. }
  11621. let opListTask;
  11622. if (!intentState.opListReadCapability) {
  11623. opListTask = Object.create(null);
  11624. opListTask.operatorListChanged = operatorListChanged;
  11625. intentState.opListReadCapability = Promise.withResolvers();
  11626. (intentState.renderTasks ||= new Set()).add(opListTask);
  11627. intentState.operatorList = {
  11628. fnArray: [],
  11629. argsArray: [],
  11630. lastChunk: false,
  11631. separateAnnots: null
  11632. };
  11633. this._stats?.time("Page Request");
  11634. this._pumpOperatorList(intentArgs);
  11635. }
  11636. return intentState.opListReadCapability.promise;
  11637. }
  11638. streamTextContent({
  11639. includeMarkedContent = false,
  11640. disableNormalization = false
  11641. } = {}) {
  11642. const TEXT_CONTENT_CHUNK_SIZE = 100;
  11643. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  11644. pageIndex: this._pageIndex,
  11645. includeMarkedContent: includeMarkedContent === true,
  11646. disableNormalization: disableNormalization === true
  11647. }, {
  11648. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  11649. size(textContent) {
  11650. return textContent.items.length;
  11651. }
  11652. });
  11653. }
  11654. getTextContent(params = {}) {
  11655. if (this._transport._htmlForXfa) {
  11656. return this.getXfa().then(xfa => XfaText.textContent(xfa));
  11657. }
  11658. const readableStream = this.streamTextContent(params);
  11659. return new Promise(function (resolve, reject) {
  11660. function pump() {
  11661. reader.read().then(function ({
  11662. value,
  11663. done
  11664. }) {
  11665. if (done) {
  11666. resolve(textContent);
  11667. return;
  11668. }
  11669. textContent.lang ??= value.lang;
  11670. Object.assign(textContent.styles, value.styles);
  11671. textContent.items.push(...value.items);
  11672. pump();
  11673. }, reject);
  11674. }
  11675. const reader = readableStream.getReader();
  11676. const textContent = {
  11677. items: [],
  11678. styles: Object.create(null),
  11679. lang: null
  11680. };
  11681. pump();
  11682. });
  11683. }
  11684. getStructTree() {
  11685. return this._transport.getStructTree(this._pageIndex);
  11686. }
  11687. _destroy() {
  11688. this.destroyed = true;
  11689. const waitOn = [];
  11690. for (const intentState of this._intentStates.values()) {
  11691. this._abortOperatorList({
  11692. intentState,
  11693. reason: new Error("Page was destroyed."),
  11694. force: true
  11695. });
  11696. if (intentState.opListReadCapability) {
  11697. continue;
  11698. }
  11699. for (const internalRenderTask of intentState.renderTasks) {
  11700. waitOn.push(internalRenderTask.completed);
  11701. internalRenderTask.cancel();
  11702. }
  11703. }
  11704. this.objs.clear();
  11705. this.#pendingCleanup = false;
  11706. this.#abortDelayedCleanup();
  11707. return Promise.all(waitOn);
  11708. }
  11709. cleanup(resetStats = false) {
  11710. this.#pendingCleanup = true;
  11711. const success = this.#tryCleanup(false);
  11712. if (resetStats && success) {
  11713. this._stats &&= new StatTimer();
  11714. }
  11715. return success;
  11716. }
  11717. #tryCleanup(delayed = false) {
  11718. this.#abortDelayedCleanup();
  11719. if (!this.#pendingCleanup || this.destroyed) {
  11720. return false;
  11721. }
  11722. if (delayed) {
  11723. this.#delayedCleanupTimeout = setTimeout(() => {
  11724. this.#delayedCleanupTimeout = null;
  11725. this.#tryCleanup(false);
  11726. }, DELAYED_CLEANUP_TIMEOUT);
  11727. return false;
  11728. }
  11729. for (const {
  11730. renderTasks,
  11731. operatorList
  11732. } of this._intentStates.values()) {
  11733. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  11734. return false;
  11735. }
  11736. }
  11737. this._intentStates.clear();
  11738. this.objs.clear();
  11739. this.#pendingCleanup = false;
  11740. return true;
  11741. }
  11742. #abortDelayedCleanup() {
  11743. if (this.#delayedCleanupTimeout) {
  11744. clearTimeout(this.#delayedCleanupTimeout);
  11745. this.#delayedCleanupTimeout = null;
  11746. }
  11747. }
  11748. _startRenderPage(transparency, cacheKey) {
  11749. const intentState = this._intentStates.get(cacheKey);
  11750. if (!intentState) {
  11751. return;
  11752. }
  11753. this._stats?.timeEnd("Page Request");
  11754. intentState.displayReadyCapability?.resolve(transparency);
  11755. }
  11756. _renderPageChunk(operatorListChunk, intentState) {
  11757. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  11758. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  11759. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  11760. }
  11761. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  11762. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  11763. for (const internalRenderTask of intentState.renderTasks) {
  11764. internalRenderTask.operatorListChanged();
  11765. }
  11766. if (operatorListChunk.lastChunk) {
  11767. this.#tryCleanup(true);
  11768. }
  11769. }
  11770. _pumpOperatorList({
  11771. renderingIntent,
  11772. cacheKey,
  11773. annotationStorageSerializable,
  11774. modifiedIds
  11775. }) {
  11776. const {
  11777. map,
  11778. transfer
  11779. } = annotationStorageSerializable;
  11780. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  11781. pageIndex: this._pageIndex,
  11782. intent: renderingIntent,
  11783. cacheKey,
  11784. annotationStorage: map,
  11785. modifiedIds
  11786. }, transfer);
  11787. const reader = readableStream.getReader();
  11788. const intentState = this._intentStates.get(cacheKey);
  11789. intentState.streamReader = reader;
  11790. const pump = () => {
  11791. reader.read().then(({
  11792. value,
  11793. done
  11794. }) => {
  11795. if (done) {
  11796. intentState.streamReader = null;
  11797. return;
  11798. }
  11799. if (this._transport.destroyed) {
  11800. return;
  11801. }
  11802. this._renderPageChunk(value, intentState);
  11803. pump();
  11804. }, reason => {
  11805. intentState.streamReader = null;
  11806. if (this._transport.destroyed) {
  11807. return;
  11808. }
  11809. if (intentState.operatorList) {
  11810. intentState.operatorList.lastChunk = true;
  11811. for (const internalRenderTask of intentState.renderTasks) {
  11812. internalRenderTask.operatorListChanged();
  11813. }
  11814. this.#tryCleanup(true);
  11815. }
  11816. if (intentState.displayReadyCapability) {
  11817. intentState.displayReadyCapability.reject(reason);
  11818. } else if (intentState.opListReadCapability) {
  11819. intentState.opListReadCapability.reject(reason);
  11820. } else {
  11821. throw reason;
  11822. }
  11823. });
  11824. };
  11825. pump();
  11826. }
  11827. _abortOperatorList({
  11828. intentState,
  11829. reason,
  11830. force = false
  11831. }) {
  11832. if (!intentState.streamReader) {
  11833. return;
  11834. }
  11835. if (intentState.streamReaderCancelTimeout) {
  11836. clearTimeout(intentState.streamReaderCancelTimeout);
  11837. intentState.streamReaderCancelTimeout = null;
  11838. }
  11839. if (!force) {
  11840. if (intentState.renderTasks.size > 0) {
  11841. return;
  11842. }
  11843. if (reason instanceof RenderingCancelledException) {
  11844. let delay = RENDERING_CANCELLED_TIMEOUT;
  11845. if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
  11846. delay += reason.extraDelay;
  11847. }
  11848. intentState.streamReaderCancelTimeout = setTimeout(() => {
  11849. intentState.streamReaderCancelTimeout = null;
  11850. this._abortOperatorList({
  11851. intentState,
  11852. reason,
  11853. force: true
  11854. });
  11855. }, delay);
  11856. return;
  11857. }
  11858. }
  11859. intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {});
  11860. intentState.streamReader = null;
  11861. if (this._transport.destroyed) {
  11862. return;
  11863. }
  11864. for (const [curCacheKey, curIntentState] of this._intentStates) {
  11865. if (curIntentState === intentState) {
  11866. this._intentStates.delete(curCacheKey);
  11867. break;
  11868. }
  11869. }
  11870. this.cleanup();
  11871. }
  11872. get stats() {
  11873. return this._stats;
  11874. }
  11875. }
  11876. class LoopbackPort {
  11877. #listeners = new Map();
  11878. #deferred = Promise.resolve();
  11879. postMessage(obj, transfer) {
  11880. const event = {
  11881. data: structuredClone(obj, transfer ? {
  11882. transfer
  11883. } : null)
  11884. };
  11885. this.#deferred.then(() => {
  11886. for (const [listener] of this.#listeners) {
  11887. listener.call(this, event);
  11888. }
  11889. });
  11890. }
  11891. addEventListener(name, listener, options = null) {
  11892. let rmAbort = null;
  11893. if (options?.signal instanceof AbortSignal) {
  11894. const {
  11895. signal
  11896. } = options;
  11897. if (signal.aborted) {
  11898. warn("LoopbackPort - cannot use an `aborted` signal.");
  11899. return;
  11900. }
  11901. const onAbort = () => this.removeEventListener(name, listener);
  11902. rmAbort = () => signal.removeEventListener("abort", onAbort);
  11903. signal.addEventListener("abort", onAbort);
  11904. }
  11905. this.#listeners.set(listener, rmAbort);
  11906. }
  11907. removeEventListener(name, listener) {
  11908. const rmAbort = this.#listeners.get(listener);
  11909. rmAbort?.();
  11910. this.#listeners.delete(listener);
  11911. }
  11912. terminate() {
  11913. for (const [, rmAbort] of this.#listeners) {
  11914. rmAbort?.();
  11915. }
  11916. this.#listeners.clear();
  11917. }
  11918. }
  11919. class PDFWorker {
  11920. static #fakeWorkerId = 0;
  11921. static #isWorkerDisabled = false;
  11922. static #workerPorts;
  11923. static {
  11924. if (isNodeJS) {
  11925. this.#isWorkerDisabled = true;
  11926. GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";
  11927. }
  11928. this._isSameOrigin = (baseUrl, otherUrl) => {
  11929. let base;
  11930. try {
  11931. base = new URL(baseUrl);
  11932. if (!base.origin || base.origin === "null") {
  11933. return false;
  11934. }
  11935. } catch {
  11936. return false;
  11937. }
  11938. const other = new URL(otherUrl, base);
  11939. return base.origin === other.origin;
  11940. };
  11941. this._createCDNWrapper = url => {
  11942. const wrapper = `await import("${url}");`;
  11943. return URL.createObjectURL(new Blob([wrapper], {
  11944. type: "text/javascript"
  11945. }));
  11946. };
  11947. }
  11948. constructor({
  11949. name = null,
  11950. port = null,
  11951. verbosity = getVerbosityLevel()
  11952. } = {}) {
  11953. this.name = name;
  11954. this.destroyed = false;
  11955. this.verbosity = verbosity;
  11956. this._readyCapability = Promise.withResolvers();
  11957. this._port = null;
  11958. this._webWorker = null;
  11959. this._messageHandler = null;
  11960. if (port) {
  11961. if (PDFWorker.#workerPorts?.has(port)) {
  11962. throw new Error("Cannot use more than one PDFWorker per port.");
  11963. }
  11964. (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);
  11965. this._initializeFromPort(port);
  11966. return;
  11967. }
  11968. this._initialize();
  11969. }
  11970. get promise() {
  11971. if (isNodeJS) {
  11972. return Promise.all([NodePackages.promise, this._readyCapability.promise]);
  11973. }
  11974. return this._readyCapability.promise;
  11975. }
  11976. #resolve() {
  11977. this._readyCapability.resolve();
  11978. this._messageHandler.send("configure", {
  11979. verbosity: this.verbosity
  11980. });
  11981. }
  11982. get port() {
  11983. return this._port;
  11984. }
  11985. get messageHandler() {
  11986. return this._messageHandler;
  11987. }
  11988. _initializeFromPort(port) {
  11989. this._port = port;
  11990. this._messageHandler = new MessageHandler("main", "worker", port);
  11991. this._messageHandler.on("ready", function () {});
  11992. this.#resolve();
  11993. }
  11994. _initialize() {
  11995. if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) {
  11996. this._setupFakeWorker();
  11997. return;
  11998. }
  11999. let {
  12000. workerSrc
  12001. } = PDFWorker;
  12002. try {
  12003. if (!PDFWorker._isSameOrigin(window.location.href, workerSrc)) {
  12004. workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);
  12005. }
  12006. const worker = new Worker(workerSrc, {
  12007. type: "module"
  12008. });
  12009. const messageHandler = new MessageHandler("main", "worker", worker);
  12010. const terminateEarly = () => {
  12011. ac.abort();
  12012. messageHandler.destroy();
  12013. worker.terminate();
  12014. if (this.destroyed) {
  12015. this._readyCapability.reject(new Error("Worker was destroyed"));
  12016. } else {
  12017. this._setupFakeWorker();
  12018. }
  12019. };
  12020. const ac = new AbortController();
  12021. worker.addEventListener("error", () => {
  12022. if (!this._webWorker) {
  12023. terminateEarly();
  12024. }
  12025. }, {
  12026. signal: ac.signal
  12027. });
  12028. messageHandler.on("test", data => {
  12029. ac.abort();
  12030. if (this.destroyed || !data) {
  12031. terminateEarly();
  12032. return;
  12033. }
  12034. this._messageHandler = messageHandler;
  12035. this._port = worker;
  12036. this._webWorker = worker;
  12037. this.#resolve();
  12038. });
  12039. messageHandler.on("ready", data => {
  12040. ac.abort();
  12041. if (this.destroyed) {
  12042. terminateEarly();
  12043. return;
  12044. }
  12045. try {
  12046. sendTest();
  12047. } catch {
  12048. this._setupFakeWorker();
  12049. }
  12050. });
  12051. const sendTest = () => {
  12052. const testObj = new Uint8Array();
  12053. messageHandler.send("test", testObj, [testObj.buffer]);
  12054. };
  12055. sendTest();
  12056. return;
  12057. } catch {
  12058. info("The worker has been disabled.");
  12059. }
  12060. this._setupFakeWorker();
  12061. }
  12062. _setupFakeWorker() {
  12063. if (!PDFWorker.#isWorkerDisabled) {
  12064. warn("Setting up fake worker.");
  12065. PDFWorker.#isWorkerDisabled = true;
  12066. }
  12067. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  12068. if (this.destroyed) {
  12069. this._readyCapability.reject(new Error("Worker was destroyed"));
  12070. return;
  12071. }
  12072. const port = new LoopbackPort();
  12073. this._port = port;
  12074. const id = `fake${PDFWorker.#fakeWorkerId++}`;
  12075. const workerHandler = new MessageHandler(id + "_worker", id, port);
  12076. WorkerMessageHandler.setup(workerHandler, port);
  12077. this._messageHandler = new MessageHandler(id, id + "_worker", port);
  12078. this.#resolve();
  12079. }).catch(reason => {
  12080. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  12081. });
  12082. }
  12083. destroy() {
  12084. this.destroyed = true;
  12085. if (this._webWorker) {
  12086. this._webWorker.terminate();
  12087. this._webWorker = null;
  12088. }
  12089. PDFWorker.#workerPorts?.delete(this._port);
  12090. this._port = null;
  12091. if (this._messageHandler) {
  12092. this._messageHandler.destroy();
  12093. this._messageHandler = null;
  12094. }
  12095. }
  12096. static fromPort(params) {
  12097. if (!params?.port) {
  12098. throw new Error("PDFWorker.fromPort - invalid method signature.");
  12099. }
  12100. const cachedPort = this.#workerPorts?.get(params.port);
  12101. if (cachedPort) {
  12102. if (cachedPort._pendingDestroy) {
  12103. throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
  12104. }
  12105. return cachedPort;
  12106. }
  12107. return new PDFWorker(params);
  12108. }
  12109. static get workerSrc() {
  12110. if (GlobalWorkerOptions.workerSrc) {
  12111. return GlobalWorkerOptions.workerSrc;
  12112. }
  12113. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  12114. }
  12115. static get #mainThreadWorkerMessageHandler() {
  12116. try {
  12117. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  12118. } catch {
  12119. return null;
  12120. }
  12121. }
  12122. static get _setupFakeWorkerGlobal() {
  12123. const loader = async () => {
  12124. if (this.#mainThreadWorkerMessageHandler) {
  12125. return this.#mainThreadWorkerMessageHandler;
  12126. }
  12127. const worker = await import(/*webpackIgnore: true*/this.workerSrc);
  12128. return worker.WorkerMessageHandler;
  12129. };
  12130. return shadow(this, "_setupFakeWorkerGlobal", loader());
  12131. }
  12132. }
  12133. class WorkerTransport {
  12134. #methodPromises = new Map();
  12135. #pageCache = new Map();
  12136. #pagePromises = new Map();
  12137. #pageRefCache = new Map();
  12138. #passwordCapability = null;
  12139. constructor(messageHandler, loadingTask, networkStream, params, factory) {
  12140. this.messageHandler = messageHandler;
  12141. this.loadingTask = loadingTask;
  12142. this.commonObjs = new PDFObjects();
  12143. this.fontLoader = new FontLoader({
  12144. ownerDocument: params.ownerDocument,
  12145. styleElement: params.styleElement
  12146. });
  12147. this.loadingParams = params.loadingParams;
  12148. this._params = params;
  12149. this.canvasFactory = factory.canvasFactory;
  12150. this.filterFactory = factory.filterFactory;
  12151. this.cMapReaderFactory = factory.cMapReaderFactory;
  12152. this.standardFontDataFactory = factory.standardFontDataFactory;
  12153. this.destroyed = false;
  12154. this.destroyCapability = null;
  12155. this._networkStream = networkStream;
  12156. this._fullReader = null;
  12157. this._lastProgress = null;
  12158. this.downloadInfoCapability = Promise.withResolvers();
  12159. this.setupMessageHandler();
  12160. }
  12161. #cacheSimpleMethod(name, data = null) {
  12162. const cachedPromise = this.#methodPromises.get(name);
  12163. if (cachedPromise) {
  12164. return cachedPromise;
  12165. }
  12166. const promise = this.messageHandler.sendWithPromise(name, data);
  12167. this.#methodPromises.set(name, promise);
  12168. return promise;
  12169. }
  12170. get annotationStorage() {
  12171. return shadow(this, "annotationStorage", new AnnotationStorage());
  12172. }
  12173. getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {
  12174. let renderingIntent = RenderingIntentFlag.DISPLAY;
  12175. let annotationStorageSerializable = SerializableEmpty;
  12176. switch (intent) {
  12177. case "any":
  12178. renderingIntent = RenderingIntentFlag.ANY;
  12179. break;
  12180. case "display":
  12181. break;
  12182. case "print":
  12183. renderingIntent = RenderingIntentFlag.PRINT;
  12184. break;
  12185. default:
  12186. warn(`getRenderingIntent - invalid intent: ${intent}`);
  12187. }
  12188. const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  12189. switch (annotationMode) {
  12190. case AnnotationMode.DISABLE:
  12191. renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
  12192. break;
  12193. case AnnotationMode.ENABLE:
  12194. break;
  12195. case AnnotationMode.ENABLE_FORMS:
  12196. renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
  12197. break;
  12198. case AnnotationMode.ENABLE_STORAGE:
  12199. renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
  12200. annotationStorageSerializable = annotationStorage.serializable;
  12201. break;
  12202. default:
  12203. warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  12204. }
  12205. if (isEditing) {
  12206. renderingIntent += RenderingIntentFlag.IS_EDITING;
  12207. }
  12208. if (isOpList) {
  12209. renderingIntent += RenderingIntentFlag.OPLIST;
  12210. }
  12211. const {
  12212. ids: modifiedIds,
  12213. hash: modifiedIdsHash
  12214. } = annotationStorage.modifiedIds;
  12215. const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];
  12216. return {
  12217. renderingIntent,
  12218. cacheKey: cacheKeyBuf.join("_"),
  12219. annotationStorageSerializable,
  12220. modifiedIds
  12221. };
  12222. }
  12223. destroy() {
  12224. if (this.destroyCapability) {
  12225. return this.destroyCapability.promise;
  12226. }
  12227. this.destroyed = true;
  12228. this.destroyCapability = Promise.withResolvers();
  12229. this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
  12230. const waitOn = [];
  12231. for (const page of this.#pageCache.values()) {
  12232. waitOn.push(page._destroy());
  12233. }
  12234. this.#pageCache.clear();
  12235. this.#pagePromises.clear();
  12236. this.#pageRefCache.clear();
  12237. if (this.hasOwnProperty("annotationStorage")) {
  12238. this.annotationStorage.resetModified();
  12239. }
  12240. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  12241. waitOn.push(terminated);
  12242. Promise.all(waitOn).then(() => {
  12243. this.commonObjs.clear();
  12244. this.fontLoader.clear();
  12245. this.#methodPromises.clear();
  12246. this.filterFactory.destroy();
  12247. TextLayer.cleanup();
  12248. this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
  12249. if (this.messageHandler) {
  12250. this.messageHandler.destroy();
  12251. this.messageHandler = null;
  12252. }
  12253. this.destroyCapability.resolve();
  12254. }, this.destroyCapability.reject);
  12255. return this.destroyCapability.promise;
  12256. }
  12257. setupMessageHandler() {
  12258. const {
  12259. messageHandler,
  12260. loadingTask
  12261. } = this;
  12262. messageHandler.on("GetReader", (data, sink) => {
  12263. assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  12264. this._fullReader = this._networkStream.getFullReader();
  12265. this._fullReader.onProgress = evt => {
  12266. this._lastProgress = {
  12267. loaded: evt.loaded,
  12268. total: evt.total
  12269. };
  12270. };
  12271. sink.onPull = () => {
  12272. this._fullReader.read().then(function ({
  12273. value,
  12274. done
  12275. }) {
  12276. if (done) {
  12277. sink.close();
  12278. return;
  12279. }
  12280. assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
  12281. sink.enqueue(new Uint8Array(value), 1, [value]);
  12282. }).catch(reason => {
  12283. sink.error(reason);
  12284. });
  12285. };
  12286. sink.onCancel = reason => {
  12287. this._fullReader.cancel(reason);
  12288. sink.ready.catch(readyReason => {
  12289. if (this.destroyed) {
  12290. return;
  12291. }
  12292. throw readyReason;
  12293. });
  12294. };
  12295. });
  12296. messageHandler.on("ReaderHeadersReady", async data => {
  12297. await this._fullReader.headersReady;
  12298. const {
  12299. isStreamingSupported,
  12300. isRangeSupported,
  12301. contentLength
  12302. } = this._fullReader;
  12303. if (!isStreamingSupported || !isRangeSupported) {
  12304. if (this._lastProgress) {
  12305. loadingTask.onProgress?.(this._lastProgress);
  12306. }
  12307. this._fullReader.onProgress = evt => {
  12308. loadingTask.onProgress?.({
  12309. loaded: evt.loaded,
  12310. total: evt.total
  12311. });
  12312. };
  12313. }
  12314. return {
  12315. isStreamingSupported,
  12316. isRangeSupported,
  12317. contentLength
  12318. };
  12319. });
  12320. messageHandler.on("GetRangeReader", (data, sink) => {
  12321. assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  12322. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  12323. if (!rangeReader) {
  12324. sink.close();
  12325. return;
  12326. }
  12327. sink.onPull = () => {
  12328. rangeReader.read().then(function ({
  12329. value,
  12330. done
  12331. }) {
  12332. if (done) {
  12333. sink.close();
  12334. return;
  12335. }
  12336. assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
  12337. sink.enqueue(new Uint8Array(value), 1, [value]);
  12338. }).catch(reason => {
  12339. sink.error(reason);
  12340. });
  12341. };
  12342. sink.onCancel = reason => {
  12343. rangeReader.cancel(reason);
  12344. sink.ready.catch(readyReason => {
  12345. if (this.destroyed) {
  12346. return;
  12347. }
  12348. throw readyReason;
  12349. });
  12350. };
  12351. });
  12352. messageHandler.on("GetDoc", ({
  12353. pdfInfo
  12354. }) => {
  12355. this._numPages = pdfInfo.numPages;
  12356. this._htmlForXfa = pdfInfo.htmlForXfa;
  12357. delete pdfInfo.htmlForXfa;
  12358. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  12359. });
  12360. messageHandler.on("DocException", function (ex) {
  12361. let reason;
  12362. switch (ex.name) {
  12363. case "PasswordException":
  12364. reason = new PasswordException(ex.message, ex.code);
  12365. break;
  12366. case "InvalidPDFException":
  12367. reason = new InvalidPDFException(ex.message);
  12368. break;
  12369. case "MissingPDFException":
  12370. reason = new MissingPDFException(ex.message);
  12371. break;
  12372. case "UnexpectedResponseException":
  12373. reason = new UnexpectedResponseException(ex.message, ex.status);
  12374. break;
  12375. case "UnknownErrorException":
  12376. reason = new UnknownErrorException(ex.message, ex.details);
  12377. break;
  12378. default:
  12379. unreachable("DocException - expected a valid Error.");
  12380. }
  12381. loadingTask._capability.reject(reason);
  12382. });
  12383. messageHandler.on("PasswordRequest", exception => {
  12384. this.#passwordCapability = Promise.withResolvers();
  12385. if (loadingTask.onPassword) {
  12386. const updatePassword = password => {
  12387. if (password instanceof Error) {
  12388. this.#passwordCapability.reject(password);
  12389. } else {
  12390. this.#passwordCapability.resolve({
  12391. password
  12392. });
  12393. }
  12394. };
  12395. try {
  12396. loadingTask.onPassword(updatePassword, exception.code);
  12397. } catch (ex) {
  12398. this.#passwordCapability.reject(ex);
  12399. }
  12400. } else {
  12401. this.#passwordCapability.reject(new PasswordException(exception.message, exception.code));
  12402. }
  12403. return this.#passwordCapability.promise;
  12404. });
  12405. messageHandler.on("DataLoaded", data => {
  12406. loadingTask.onProgress?.({
  12407. loaded: data.length,
  12408. total: data.length
  12409. });
  12410. this.downloadInfoCapability.resolve(data);
  12411. });
  12412. messageHandler.on("StartRenderPage", data => {
  12413. if (this.destroyed) {
  12414. return;
  12415. }
  12416. const page = this.#pageCache.get(data.pageIndex);
  12417. page._startRenderPage(data.transparency, data.cacheKey);
  12418. });
  12419. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  12420. if (this.destroyed) {
  12421. return null;
  12422. }
  12423. if (this.commonObjs.has(id)) {
  12424. return null;
  12425. }
  12426. switch (type) {
  12427. case "Font":
  12428. const {
  12429. disableFontFace,
  12430. fontExtraProperties,
  12431. pdfBug
  12432. } = this._params;
  12433. if ("error" in exportedData) {
  12434. const exportedError = exportedData.error;
  12435. warn(`Error during font loading: ${exportedError}`);
  12436. this.commonObjs.resolve(id, exportedError);
  12437. break;
  12438. }
  12439. const inspectFont = pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
  12440. const font = new FontFaceObject(exportedData, {
  12441. disableFontFace,
  12442. inspectFont
  12443. });
  12444. this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
  12445. id
  12446. })).finally(() => {
  12447. if (!fontExtraProperties && font.data) {
  12448. font.data = null;
  12449. }
  12450. this.commonObjs.resolve(id, font);
  12451. });
  12452. break;
  12453. case "CopyLocalImage":
  12454. const {
  12455. imageRef
  12456. } = exportedData;
  12457. assert(imageRef, "The imageRef must be defined.");
  12458. for (const pageProxy of this.#pageCache.values()) {
  12459. for (const [, data] of pageProxy.objs) {
  12460. if (data?.ref !== imageRef) {
  12461. continue;
  12462. }
  12463. if (!data.dataLen) {
  12464. return null;
  12465. }
  12466. this.commonObjs.resolve(id, structuredClone(data));
  12467. return data.dataLen;
  12468. }
  12469. }
  12470. break;
  12471. case "FontPath":
  12472. case "Image":
  12473. case "Pattern":
  12474. this.commonObjs.resolve(id, exportedData);
  12475. break;
  12476. default:
  12477. throw new Error(`Got unknown common object type ${type}`);
  12478. }
  12479. return null;
  12480. });
  12481. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  12482. if (this.destroyed) {
  12483. return;
  12484. }
  12485. const pageProxy = this.#pageCache.get(pageIndex);
  12486. if (pageProxy.objs.has(id)) {
  12487. return;
  12488. }
  12489. if (pageProxy._intentStates.size === 0) {
  12490. imageData?.bitmap?.close();
  12491. return;
  12492. }
  12493. switch (type) {
  12494. case "Image":
  12495. pageProxy.objs.resolve(id, imageData);
  12496. if (imageData?.dataLen > MAX_IMAGE_SIZE_TO_CACHE) {
  12497. pageProxy._maybeCleanupAfterRender = true;
  12498. }
  12499. break;
  12500. case "Pattern":
  12501. pageProxy.objs.resolve(id, imageData);
  12502. break;
  12503. default:
  12504. throw new Error(`Got unknown object type ${type}`);
  12505. }
  12506. });
  12507. messageHandler.on("DocProgress", data => {
  12508. if (this.destroyed) {
  12509. return;
  12510. }
  12511. loadingTask.onProgress?.({
  12512. loaded: data.loaded,
  12513. total: data.total
  12514. });
  12515. });
  12516. messageHandler.on("FetchBuiltInCMap", async data => {
  12517. if (this.destroyed) {
  12518. throw new Error("Worker was destroyed.");
  12519. }
  12520. if (!this.cMapReaderFactory) {
  12521. throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");
  12522. }
  12523. return this.cMapReaderFactory.fetch(data);
  12524. });
  12525. messageHandler.on("FetchStandardFontData", async data => {
  12526. if (this.destroyed) {
  12527. throw new Error("Worker was destroyed.");
  12528. }
  12529. if (!this.standardFontDataFactory) {
  12530. throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");
  12531. }
  12532. return this.standardFontDataFactory.fetch(data);
  12533. });
  12534. }
  12535. getData() {
  12536. return this.messageHandler.sendWithPromise("GetData", null);
  12537. }
  12538. saveDocument() {
  12539. if (this.annotationStorage.size <= 0) {
  12540. warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  12541. }
  12542. const {
  12543. map,
  12544. transfer
  12545. } = this.annotationStorage.serializable;
  12546. return this.messageHandler.sendWithPromise("SaveDocument", {
  12547. isPureXfa: !!this._htmlForXfa,
  12548. numPages: this._numPages,
  12549. annotationStorage: map,
  12550. filename: this._fullReader?.filename ?? null
  12551. }, transfer).finally(() => {
  12552. this.annotationStorage.resetModified();
  12553. });
  12554. }
  12555. getPage(pageNumber) {
  12556. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  12557. return Promise.reject(new Error("Invalid page request."));
  12558. }
  12559. const pageIndex = pageNumber - 1,
  12560. cachedPromise = this.#pagePromises.get(pageIndex);
  12561. if (cachedPromise) {
  12562. return cachedPromise;
  12563. }
  12564. const promise = this.messageHandler.sendWithPromise("GetPage", {
  12565. pageIndex
  12566. }).then(pageInfo => {
  12567. if (this.destroyed) {
  12568. throw new Error("Transport destroyed");
  12569. }
  12570. if (pageInfo.refStr) {
  12571. this.#pageRefCache.set(pageInfo.refStr, pageNumber);
  12572. }
  12573. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
  12574. this.#pageCache.set(pageIndex, page);
  12575. return page;
  12576. });
  12577. this.#pagePromises.set(pageIndex, promise);
  12578. return promise;
  12579. }
  12580. getPageIndex(ref) {
  12581. if (!isRefProxy(ref)) {
  12582. return Promise.reject(new Error("Invalid pageIndex request."));
  12583. }
  12584. return this.messageHandler.sendWithPromise("GetPageIndex", {
  12585. num: ref.num,
  12586. gen: ref.gen
  12587. });
  12588. }
  12589. getAnnotations(pageIndex, intent) {
  12590. return this.messageHandler.sendWithPromise("GetAnnotations", {
  12591. pageIndex,
  12592. intent
  12593. });
  12594. }
  12595. getFieldObjects() {
  12596. return this.#cacheSimpleMethod("GetFieldObjects");
  12597. }
  12598. hasJSActions() {
  12599. return this.#cacheSimpleMethod("HasJSActions");
  12600. }
  12601. getCalculationOrderIds() {
  12602. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  12603. }
  12604. getDestinations() {
  12605. return this.messageHandler.sendWithPromise("GetDestinations", null);
  12606. }
  12607. getDestination(id) {
  12608. if (typeof id !== "string") {
  12609. return Promise.reject(new Error("Invalid destination request."));
  12610. }
  12611. return this.messageHandler.sendWithPromise("GetDestination", {
  12612. id
  12613. });
  12614. }
  12615. getPageLabels() {
  12616. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  12617. }
  12618. getPageLayout() {
  12619. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  12620. }
  12621. getPageMode() {
  12622. return this.messageHandler.sendWithPromise("GetPageMode", null);
  12623. }
  12624. getViewerPreferences() {
  12625. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  12626. }
  12627. getOpenAction() {
  12628. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  12629. }
  12630. getAttachments() {
  12631. return this.messageHandler.sendWithPromise("GetAttachments", null);
  12632. }
  12633. getDocJSActions() {
  12634. return this.#cacheSimpleMethod("GetDocJSActions");
  12635. }
  12636. getPageJSActions(pageIndex) {
  12637. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  12638. pageIndex
  12639. });
  12640. }
  12641. getStructTree(pageIndex) {
  12642. return this.messageHandler.sendWithPromise("GetStructTree", {
  12643. pageIndex
  12644. });
  12645. }
  12646. getOutline() {
  12647. return this.messageHandler.sendWithPromise("GetOutline", null);
  12648. }
  12649. getOptionalContentConfig(renderingIntent) {
  12650. return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent));
  12651. }
  12652. getPermissions() {
  12653. return this.messageHandler.sendWithPromise("GetPermissions", null);
  12654. }
  12655. getMetadata() {
  12656. const name = "GetMetadata",
  12657. cachedPromise = this.#methodPromises.get(name);
  12658. if (cachedPromise) {
  12659. return cachedPromise;
  12660. }
  12661. const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({
  12662. info: results[0],
  12663. metadata: results[1] ? new Metadata(results[1]) : null,
  12664. contentDispositionFilename: this._fullReader?.filename ?? null,
  12665. contentLength: this._fullReader?.contentLength ?? null
  12666. }));
  12667. this.#methodPromises.set(name, promise);
  12668. return promise;
  12669. }
  12670. getMarkInfo() {
  12671. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  12672. }
  12673. async startCleanup(keepLoadedFonts = false) {
  12674. if (this.destroyed) {
  12675. return;
  12676. }
  12677. await this.messageHandler.sendWithPromise("Cleanup", null);
  12678. for (const page of this.#pageCache.values()) {
  12679. const cleanupSuccessful = page.cleanup();
  12680. if (!cleanupSuccessful) {
  12681. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  12682. }
  12683. }
  12684. this.commonObjs.clear();
  12685. if (!keepLoadedFonts) {
  12686. this.fontLoader.clear();
  12687. }
  12688. this.#methodPromises.clear();
  12689. this.filterFactory.destroy(true);
  12690. TextLayer.cleanup();
  12691. }
  12692. cachedPageNumber(ref) {
  12693. if (!isRefProxy(ref)) {
  12694. return null;
  12695. }
  12696. const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
  12697. return this.#pageRefCache.get(refStr) ?? null;
  12698. }
  12699. }
  12700. const INITIAL_DATA = Symbol("INITIAL_DATA");
  12701. class PDFObjects {
  12702. #objs = Object.create(null);
  12703. #ensureObj(objId) {
  12704. return this.#objs[objId] ||= {
  12705. ...Promise.withResolvers(),
  12706. data: INITIAL_DATA
  12707. };
  12708. }
  12709. get(objId, callback = null) {
  12710. if (callback) {
  12711. const obj = this.#ensureObj(objId);
  12712. obj.promise.then(() => callback(obj.data));
  12713. return null;
  12714. }
  12715. const obj = this.#objs[objId];
  12716. if (!obj || obj.data === INITIAL_DATA) {
  12717. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  12718. }
  12719. return obj.data;
  12720. }
  12721. has(objId) {
  12722. const obj = this.#objs[objId];
  12723. return !!obj && obj.data !== INITIAL_DATA;
  12724. }
  12725. resolve(objId, data = null) {
  12726. const obj = this.#ensureObj(objId);
  12727. obj.data = data;
  12728. obj.resolve();
  12729. }
  12730. clear() {
  12731. for (const objId in this.#objs) {
  12732. const {
  12733. data
  12734. } = this.#objs[objId];
  12735. data?.bitmap?.close();
  12736. }
  12737. this.#objs = Object.create(null);
  12738. }
  12739. *[Symbol.iterator]() {
  12740. for (const objId in this.#objs) {
  12741. const {
  12742. data
  12743. } = this.#objs[objId];
  12744. if (data === INITIAL_DATA) {
  12745. continue;
  12746. }
  12747. yield [objId, data];
  12748. }
  12749. }
  12750. }
  12751. class RenderTask {
  12752. #internalRenderTask = null;
  12753. constructor(internalRenderTask) {
  12754. this.#internalRenderTask = internalRenderTask;
  12755. this.onContinue = null;
  12756. }
  12757. get promise() {
  12758. return this.#internalRenderTask.capability.promise;
  12759. }
  12760. cancel(extraDelay = 0) {
  12761. this.#internalRenderTask.cancel(null, extraDelay);
  12762. }
  12763. get separateAnnots() {
  12764. const {
  12765. separateAnnots
  12766. } = this.#internalRenderTask.operatorList;
  12767. if (!separateAnnots) {
  12768. return false;
  12769. }
  12770. const {
  12771. annotationCanvasMap
  12772. } = this.#internalRenderTask;
  12773. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  12774. }
  12775. }
  12776. class InternalRenderTask {
  12777. #rAF = null;
  12778. static #canvasInUse = new WeakSet();
  12779. constructor({
  12780. callback,
  12781. params,
  12782. objs,
  12783. commonObjs,
  12784. annotationCanvasMap,
  12785. operatorList,
  12786. pageIndex,
  12787. canvasFactory,
  12788. filterFactory,
  12789. useRequestAnimationFrame = false,
  12790. pdfBug = false,
  12791. pageColors = null
  12792. }) {
  12793. this.callback = callback;
  12794. this.params = params;
  12795. this.objs = objs;
  12796. this.commonObjs = commonObjs;
  12797. this.annotationCanvasMap = annotationCanvasMap;
  12798. this.operatorListIdx = null;
  12799. this.operatorList = operatorList;
  12800. this._pageIndex = pageIndex;
  12801. this.canvasFactory = canvasFactory;
  12802. this.filterFactory = filterFactory;
  12803. this._pdfBug = pdfBug;
  12804. this.pageColors = pageColors;
  12805. this.running = false;
  12806. this.graphicsReadyCallback = null;
  12807. this.graphicsReady = false;
  12808. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  12809. this.cancelled = false;
  12810. this.capability = Promise.withResolvers();
  12811. this.task = new RenderTask(this);
  12812. this._cancelBound = this.cancel.bind(this);
  12813. this._continueBound = this._continue.bind(this);
  12814. this._scheduleNextBound = this._scheduleNext.bind(this);
  12815. this._nextBound = this._next.bind(this);
  12816. this._canvas = params.canvasContext.canvas;
  12817. }
  12818. get completed() {
  12819. return this.capability.promise.catch(function () {});
  12820. }
  12821. initializeGraphics({
  12822. transparency = false,
  12823. optionalContentConfig
  12824. }) {
  12825. if (this.cancelled) {
  12826. return;
  12827. }
  12828. if (this._canvas) {
  12829. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  12830. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  12831. }
  12832. InternalRenderTask.#canvasInUse.add(this._canvas);
  12833. }
  12834. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  12835. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  12836. this.stepper.init(this.operatorList);
  12837. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  12838. }
  12839. const {
  12840. canvasContext,
  12841. viewport,
  12842. transform,
  12843. background
  12844. } = this.params;
  12845. this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  12846. optionalContentConfig
  12847. }, this.annotationCanvasMap, this.pageColors);
  12848. this.gfx.beginDrawing({
  12849. transform,
  12850. viewport,
  12851. transparency,
  12852. background
  12853. });
  12854. this.operatorListIdx = 0;
  12855. this.graphicsReady = true;
  12856. this.graphicsReadyCallback?.();
  12857. }
  12858. cancel(error = null, extraDelay = 0) {
  12859. this.running = false;
  12860. this.cancelled = true;
  12861. this.gfx?.endDrawing();
  12862. if (this.#rAF) {
  12863. window.cancelAnimationFrame(this.#rAF);
  12864. this.#rAF = null;
  12865. }
  12866. InternalRenderTask.#canvasInUse.delete(this._canvas);
  12867. this.callback(error || new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay));
  12868. }
  12869. operatorListChanged() {
  12870. if (!this.graphicsReady) {
  12871. this.graphicsReadyCallback ||= this._continueBound;
  12872. return;
  12873. }
  12874. this.stepper?.updateOperatorList(this.operatorList);
  12875. if (this.running) {
  12876. return;
  12877. }
  12878. this._continue();
  12879. }
  12880. _continue() {
  12881. this.running = true;
  12882. if (this.cancelled) {
  12883. return;
  12884. }
  12885. if (this.task.onContinue) {
  12886. this.task.onContinue(this._scheduleNextBound);
  12887. } else {
  12888. this._scheduleNext();
  12889. }
  12890. }
  12891. _scheduleNext() {
  12892. if (this._useRequestAnimationFrame) {
  12893. this.#rAF = window.requestAnimationFrame(() => {
  12894. this.#rAF = null;
  12895. this._nextBound().catch(this._cancelBound);
  12896. });
  12897. } else {
  12898. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  12899. }
  12900. }
  12901. async _next() {
  12902. if (this.cancelled) {
  12903. return;
  12904. }
  12905. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  12906. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  12907. this.running = false;
  12908. if (this.operatorList.lastChunk) {
  12909. this.gfx.endDrawing();
  12910. InternalRenderTask.#canvasInUse.delete(this._canvas);
  12911. this.callback();
  12912. }
  12913. }
  12914. }
  12915. }
  12916. const version = "4.8.69";
  12917. const build = "3634dab10";
  12918. ;// ./src/shared/scripting_utils.js
  12919. function makeColorComp(n) {
  12920. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  12921. }
  12922. function scaleAndClamp(x) {
  12923. return Math.max(0, Math.min(255, 255 * x));
  12924. }
  12925. class ColorConverters {
  12926. static CMYK_G([c, y, m, k]) {
  12927. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  12928. }
  12929. static G_CMYK([g]) {
  12930. return ["CMYK", 0, 0, 0, 1 - g];
  12931. }
  12932. static G_RGB([g]) {
  12933. return ["RGB", g, g, g];
  12934. }
  12935. static G_rgb([g]) {
  12936. g = scaleAndClamp(g);
  12937. return [g, g, g];
  12938. }
  12939. static G_HTML([g]) {
  12940. const G = makeColorComp(g);
  12941. return `#${G}${G}${G}`;
  12942. }
  12943. static RGB_G([r, g, b]) {
  12944. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  12945. }
  12946. static RGB_rgb(color) {
  12947. return color.map(scaleAndClamp);
  12948. }
  12949. static RGB_HTML(color) {
  12950. return `#${color.map(makeColorComp).join("")}`;
  12951. }
  12952. static T_HTML() {
  12953. return "#00000000";
  12954. }
  12955. static T_rgb() {
  12956. return [null];
  12957. }
  12958. static CMYK_RGB([c, y, m, k]) {
  12959. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  12960. }
  12961. static CMYK_rgb([c, y, m, k]) {
  12962. return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
  12963. }
  12964. static CMYK_HTML(components) {
  12965. const rgb = this.CMYK_RGB(components).slice(1);
  12966. return this.RGB_HTML(rgb);
  12967. }
  12968. static RGB_CMYK([r, g, b]) {
  12969. const c = 1 - r;
  12970. const m = 1 - g;
  12971. const y = 1 - b;
  12972. const k = Math.min(c, m, y);
  12973. return ["CMYK", c, m, y, k];
  12974. }
  12975. }
  12976. ;// ./src/display/svg_factory.js
  12977. class BaseSVGFactory {
  12978. create(width, height, skipDimensions = false) {
  12979. if (width <= 0 || height <= 0) {
  12980. throw new Error("Invalid SVG dimensions");
  12981. }
  12982. const svg = this._createSVG("svg:svg");
  12983. svg.setAttribute("version", "1.1");
  12984. if (!skipDimensions) {
  12985. svg.setAttribute("width", `${width}px`);
  12986. svg.setAttribute("height", `${height}px`);
  12987. }
  12988. svg.setAttribute("preserveAspectRatio", "none");
  12989. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  12990. return svg;
  12991. }
  12992. createElement(type) {
  12993. if (typeof type !== "string") {
  12994. throw new Error("Invalid SVG element type");
  12995. }
  12996. return this._createSVG(type);
  12997. }
  12998. _createSVG(type) {
  12999. unreachable("Abstract method `_createSVG` called.");
  13000. }
  13001. }
  13002. class DOMSVGFactory extends BaseSVGFactory {
  13003. _createSVG(type) {
  13004. return document.createElementNS(SVG_NS, type);
  13005. }
  13006. }
  13007. ;// ./src/display/xfa_layer.js
  13008. class XfaLayer {
  13009. static setupStorage(html, id, element, storage, intent) {
  13010. const storedData = storage.getValue(id, {
  13011. value: null
  13012. });
  13013. switch (element.name) {
  13014. case "textarea":
  13015. if (storedData.value !== null) {
  13016. html.textContent = storedData.value;
  13017. }
  13018. if (intent === "print") {
  13019. break;
  13020. }
  13021. html.addEventListener("input", event => {
  13022. storage.setValue(id, {
  13023. value: event.target.value
  13024. });
  13025. });
  13026. break;
  13027. case "input":
  13028. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  13029. if (storedData.value === element.attributes.xfaOn) {
  13030. html.setAttribute("checked", true);
  13031. } else if (storedData.value === element.attributes.xfaOff) {
  13032. html.removeAttribute("checked");
  13033. }
  13034. if (intent === "print") {
  13035. break;
  13036. }
  13037. html.addEventListener("change", event => {
  13038. storage.setValue(id, {
  13039. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  13040. });
  13041. });
  13042. } else {
  13043. if (storedData.value !== null) {
  13044. html.setAttribute("value", storedData.value);
  13045. }
  13046. if (intent === "print") {
  13047. break;
  13048. }
  13049. html.addEventListener("input", event => {
  13050. storage.setValue(id, {
  13051. value: event.target.value
  13052. });
  13053. });
  13054. }
  13055. break;
  13056. case "select":
  13057. if (storedData.value !== null) {
  13058. html.setAttribute("value", storedData.value);
  13059. for (const option of element.children) {
  13060. if (option.attributes.value === storedData.value) {
  13061. option.attributes.selected = true;
  13062. } else if (option.attributes.hasOwnProperty("selected")) {
  13063. delete option.attributes.selected;
  13064. }
  13065. }
  13066. }
  13067. html.addEventListener("input", event => {
  13068. const options = event.target.options;
  13069. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  13070. storage.setValue(id, {
  13071. value
  13072. });
  13073. });
  13074. break;
  13075. }
  13076. }
  13077. static setAttributes({
  13078. html,
  13079. element,
  13080. storage = null,
  13081. intent,
  13082. linkService
  13083. }) {
  13084. const {
  13085. attributes
  13086. } = element;
  13087. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  13088. if (attributes.type === "radio") {
  13089. attributes.name = `${attributes.name}-${intent}`;
  13090. }
  13091. for (const [key, value] of Object.entries(attributes)) {
  13092. if (value === null || value === undefined) {
  13093. continue;
  13094. }
  13095. switch (key) {
  13096. case "class":
  13097. if (value.length) {
  13098. html.setAttribute(key, value.join(" "));
  13099. }
  13100. break;
  13101. case "dataId":
  13102. break;
  13103. case "id":
  13104. html.setAttribute("data-element-id", value);
  13105. break;
  13106. case "style":
  13107. Object.assign(html.style, value);
  13108. break;
  13109. case "textContent":
  13110. html.textContent = value;
  13111. break;
  13112. default:
  13113. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  13114. html.setAttribute(key, value);
  13115. }
  13116. }
  13117. }
  13118. if (isHTMLAnchorElement) {
  13119. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  13120. }
  13121. if (storage && attributes.dataId) {
  13122. this.setupStorage(html, attributes.dataId, element, storage);
  13123. }
  13124. }
  13125. static render(parameters) {
  13126. const storage = parameters.annotationStorage;
  13127. const linkService = parameters.linkService;
  13128. const root = parameters.xfaHtml;
  13129. const intent = parameters.intent || "display";
  13130. const rootHtml = document.createElement(root.name);
  13131. if (root.attributes) {
  13132. this.setAttributes({
  13133. html: rootHtml,
  13134. element: root,
  13135. intent,
  13136. linkService
  13137. });
  13138. }
  13139. const isNotForRichText = intent !== "richText";
  13140. const rootDiv = parameters.div;
  13141. rootDiv.append(rootHtml);
  13142. if (parameters.viewport) {
  13143. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  13144. rootDiv.style.transform = transform;
  13145. }
  13146. if (isNotForRichText) {
  13147. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  13148. }
  13149. const textDivs = [];
  13150. if (root.children.length === 0) {
  13151. if (root.value) {
  13152. const node = document.createTextNode(root.value);
  13153. rootHtml.append(node);
  13154. if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
  13155. textDivs.push(node);
  13156. }
  13157. }
  13158. return {
  13159. textDivs
  13160. };
  13161. }
  13162. const stack = [[root, -1, rootHtml]];
  13163. while (stack.length > 0) {
  13164. const [parent, i, html] = stack.at(-1);
  13165. if (i + 1 === parent.children.length) {
  13166. stack.pop();
  13167. continue;
  13168. }
  13169. const child = parent.children[++stack.at(-1)[1]];
  13170. if (child === null) {
  13171. continue;
  13172. }
  13173. const {
  13174. name
  13175. } = child;
  13176. if (name === "#text") {
  13177. const node = document.createTextNode(child.value);
  13178. textDivs.push(node);
  13179. html.append(node);
  13180. continue;
  13181. }
  13182. const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
  13183. html.append(childHtml);
  13184. if (child.attributes) {
  13185. this.setAttributes({
  13186. html: childHtml,
  13187. element: child,
  13188. storage,
  13189. intent,
  13190. linkService
  13191. });
  13192. }
  13193. if (child.children?.length > 0) {
  13194. stack.push([child, -1, childHtml]);
  13195. } else if (child.value) {
  13196. const node = document.createTextNode(child.value);
  13197. if (isNotForRichText && XfaText.shouldBuildText(name)) {
  13198. textDivs.push(node);
  13199. }
  13200. childHtml.append(node);
  13201. }
  13202. }
  13203. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  13204. el.setAttribute("readOnly", true);
  13205. }
  13206. return {
  13207. textDivs
  13208. };
  13209. }
  13210. static update(parameters) {
  13211. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  13212. parameters.div.style.transform = transform;
  13213. parameters.div.hidden = false;
  13214. }
  13215. }
  13216. ;// ./src/display/annotation_layer.js
  13217. const DEFAULT_TAB_INDEX = 1000;
  13218. const annotation_layer_DEFAULT_FONT_SIZE = 9;
  13219. const GetElementsByNameSet = new WeakSet();
  13220. function getRectDims(rect) {
  13221. return {
  13222. width: rect[2] - rect[0],
  13223. height: rect[3] - rect[1]
  13224. };
  13225. }
  13226. class AnnotationElementFactory {
  13227. static create(parameters) {
  13228. const subtype = parameters.data.annotationType;
  13229. switch (subtype) {
  13230. case AnnotationType.LINK:
  13231. return new LinkAnnotationElement(parameters);
  13232. case AnnotationType.TEXT:
  13233. return new TextAnnotationElement(parameters);
  13234. case AnnotationType.WIDGET:
  13235. const fieldType = parameters.data.fieldType;
  13236. switch (fieldType) {
  13237. case "Tx":
  13238. return new TextWidgetAnnotationElement(parameters);
  13239. case "Btn":
  13240. if (parameters.data.radioButton) {
  13241. return new RadioButtonWidgetAnnotationElement(parameters);
  13242. } else if (parameters.data.checkBox) {
  13243. return new CheckboxWidgetAnnotationElement(parameters);
  13244. }
  13245. return new PushButtonWidgetAnnotationElement(parameters);
  13246. case "Ch":
  13247. return new ChoiceWidgetAnnotationElement(parameters);
  13248. case "Sig":
  13249. return new SignatureWidgetAnnotationElement(parameters);
  13250. }
  13251. return new WidgetAnnotationElement(parameters);
  13252. case AnnotationType.POPUP:
  13253. return new PopupAnnotationElement(parameters);
  13254. case AnnotationType.FREETEXT:
  13255. return new FreeTextAnnotationElement(parameters);
  13256. case AnnotationType.LINE:
  13257. return new LineAnnotationElement(parameters);
  13258. case AnnotationType.SQUARE:
  13259. return new SquareAnnotationElement(parameters);
  13260. case AnnotationType.CIRCLE:
  13261. return new CircleAnnotationElement(parameters);
  13262. case AnnotationType.POLYLINE:
  13263. return new PolylineAnnotationElement(parameters);
  13264. case AnnotationType.CARET:
  13265. return new CaretAnnotationElement(parameters);
  13266. case AnnotationType.INK:
  13267. return new InkAnnotationElement(parameters);
  13268. case AnnotationType.POLYGON:
  13269. return new PolygonAnnotationElement(parameters);
  13270. case AnnotationType.HIGHLIGHT:
  13271. return new HighlightAnnotationElement(parameters);
  13272. case AnnotationType.UNDERLINE:
  13273. return new UnderlineAnnotationElement(parameters);
  13274. case AnnotationType.SQUIGGLY:
  13275. return new SquigglyAnnotationElement(parameters);
  13276. case AnnotationType.STRIKEOUT:
  13277. return new StrikeOutAnnotationElement(parameters);
  13278. case AnnotationType.STAMP:
  13279. return new StampAnnotationElement(parameters);
  13280. case AnnotationType.FILEATTACHMENT:
  13281. return new FileAttachmentAnnotationElement(parameters);
  13282. default:
  13283. return new AnnotationElement(parameters);
  13284. }
  13285. }
  13286. }
  13287. class AnnotationElement {
  13288. #updates = null;
  13289. #hasBorder = false;
  13290. #popupElement = null;
  13291. constructor(parameters, {
  13292. isRenderable = false,
  13293. ignoreBorder = false,
  13294. createQuadrilaterals = false
  13295. } = {}) {
  13296. this.isRenderable = isRenderable;
  13297. this.data = parameters.data;
  13298. this.layer = parameters.layer;
  13299. this.linkService = parameters.linkService;
  13300. this.downloadManager = parameters.downloadManager;
  13301. this.imageResourcesPath = parameters.imageResourcesPath;
  13302. this.renderForms = parameters.renderForms;
  13303. this.svgFactory = parameters.svgFactory;
  13304. this.annotationStorage = parameters.annotationStorage;
  13305. this.enableScripting = parameters.enableScripting;
  13306. this.hasJSActions = parameters.hasJSActions;
  13307. this._fieldObjects = parameters.fieldObjects;
  13308. this.parent = parameters.parent;
  13309. if (isRenderable) {
  13310. this.container = this._createContainer(ignoreBorder);
  13311. }
  13312. if (createQuadrilaterals) {
  13313. this._createQuadrilaterals();
  13314. }
  13315. }
  13316. static _hasPopupData({
  13317. titleObj,
  13318. contentsObj,
  13319. richText
  13320. }) {
  13321. return !!(titleObj?.str || contentsObj?.str || richText?.str);
  13322. }
  13323. get _isEditable() {
  13324. return this.data.isEditable;
  13325. }
  13326. get hasPopupData() {
  13327. return AnnotationElement._hasPopupData(this.data);
  13328. }
  13329. updateEdited(params) {
  13330. if (!this.container) {
  13331. return;
  13332. }
  13333. this.#updates ||= {
  13334. rect: this.data.rect.slice(0)
  13335. };
  13336. const {
  13337. rect
  13338. } = params;
  13339. if (rect) {
  13340. this.#setRectEdited(rect);
  13341. }
  13342. this.#popupElement?.popup.updateEdited(params);
  13343. }
  13344. resetEdited() {
  13345. if (!this.#updates) {
  13346. return;
  13347. }
  13348. this.#setRectEdited(this.#updates.rect);
  13349. this.#popupElement?.popup.resetEdited();
  13350. this.#updates = null;
  13351. }
  13352. #setRectEdited(rect) {
  13353. const {
  13354. container: {
  13355. style
  13356. },
  13357. data: {
  13358. rect: currentRect,
  13359. rotation
  13360. },
  13361. parent: {
  13362. viewport: {
  13363. rawDims: {
  13364. pageWidth,
  13365. pageHeight,
  13366. pageX,
  13367. pageY
  13368. }
  13369. }
  13370. }
  13371. } = this;
  13372. currentRect?.splice(0, 4, ...rect);
  13373. const {
  13374. width,
  13375. height
  13376. } = getRectDims(rect);
  13377. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  13378. style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
  13379. if (rotation === 0) {
  13380. style.width = `${100 * width / pageWidth}%`;
  13381. style.height = `${100 * height / pageHeight}%`;
  13382. } else {
  13383. this.setRotation(rotation);
  13384. }
  13385. }
  13386. _createContainer(ignoreBorder) {
  13387. const {
  13388. data,
  13389. parent: {
  13390. page,
  13391. viewport
  13392. }
  13393. } = this;
  13394. const container = document.createElement("section");
  13395. container.setAttribute("data-annotation-id", data.id);
  13396. if (!(this instanceof WidgetAnnotationElement)) {
  13397. container.tabIndex = DEFAULT_TAB_INDEX;
  13398. }
  13399. const {
  13400. style
  13401. } = container;
  13402. style.zIndex = this.parent.zIndex++;
  13403. if (data.alternativeText) {
  13404. container.title = data.alternativeText;
  13405. }
  13406. if (data.noRotate) {
  13407. container.classList.add("norotate");
  13408. }
  13409. if (!data.rect || this instanceof PopupAnnotationElement) {
  13410. const {
  13411. rotation
  13412. } = data;
  13413. if (!data.hasOwnCanvas && rotation !== 0) {
  13414. this.setRotation(rotation, container);
  13415. }
  13416. return container;
  13417. }
  13418. const {
  13419. width,
  13420. height
  13421. } = getRectDims(data.rect);
  13422. if (!ignoreBorder && data.borderStyle.width > 0) {
  13423. style.borderWidth = `${data.borderStyle.width}px`;
  13424. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  13425. const verticalRadius = data.borderStyle.verticalCornerRadius;
  13426. if (horizontalRadius > 0 || verticalRadius > 0) {
  13427. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  13428. style.borderRadius = radius;
  13429. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  13430. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  13431. style.borderRadius = radius;
  13432. }
  13433. switch (data.borderStyle.style) {
  13434. case AnnotationBorderStyleType.SOLID:
  13435. style.borderStyle = "solid";
  13436. break;
  13437. case AnnotationBorderStyleType.DASHED:
  13438. style.borderStyle = "dashed";
  13439. break;
  13440. case AnnotationBorderStyleType.BEVELED:
  13441. warn("Unimplemented border style: beveled");
  13442. break;
  13443. case AnnotationBorderStyleType.INSET:
  13444. warn("Unimplemented border style: inset");
  13445. break;
  13446. case AnnotationBorderStyleType.UNDERLINE:
  13447. style.borderBottomStyle = "solid";
  13448. break;
  13449. default:
  13450. break;
  13451. }
  13452. const borderColor = data.borderColor || null;
  13453. if (borderColor) {
  13454. this.#hasBorder = true;
  13455. style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  13456. } else {
  13457. style.borderWidth = 0;
  13458. }
  13459. }
  13460. 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]]);
  13461. const {
  13462. pageWidth,
  13463. pageHeight,
  13464. pageX,
  13465. pageY
  13466. } = viewport.rawDims;
  13467. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  13468. style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
  13469. const {
  13470. rotation
  13471. } = data;
  13472. if (data.hasOwnCanvas || rotation === 0) {
  13473. style.width = `${100 * width / pageWidth}%`;
  13474. style.height = `${100 * height / pageHeight}%`;
  13475. } else {
  13476. this.setRotation(rotation, container);
  13477. }
  13478. return container;
  13479. }
  13480. setRotation(angle, container = this.container) {
  13481. if (!this.data.rect) {
  13482. return;
  13483. }
  13484. const {
  13485. pageWidth,
  13486. pageHeight
  13487. } = this.parent.viewport.rawDims;
  13488. const {
  13489. width,
  13490. height
  13491. } = getRectDims(this.data.rect);
  13492. let elementWidth, elementHeight;
  13493. if (angle % 180 === 0) {
  13494. elementWidth = 100 * width / pageWidth;
  13495. elementHeight = 100 * height / pageHeight;
  13496. } else {
  13497. elementWidth = 100 * height / pageWidth;
  13498. elementHeight = 100 * width / pageHeight;
  13499. }
  13500. container.style.width = `${elementWidth}%`;
  13501. container.style.height = `${elementHeight}%`;
  13502. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  13503. }
  13504. get _commonActions() {
  13505. const setColor = (jsName, styleName, event) => {
  13506. const color = event.detail[jsName];
  13507. const colorType = color[0];
  13508. const colorArray = color.slice(1);
  13509. event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
  13510. this.annotationStorage.setValue(this.data.id, {
  13511. [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
  13512. });
  13513. };
  13514. return shadow(this, "_commonActions", {
  13515. display: event => {
  13516. const {
  13517. display
  13518. } = event.detail;
  13519. const hidden = display % 2 === 1;
  13520. this.container.style.visibility = hidden ? "hidden" : "visible";
  13521. this.annotationStorage.setValue(this.data.id, {
  13522. noView: hidden,
  13523. noPrint: display === 1 || display === 2
  13524. });
  13525. },
  13526. print: event => {
  13527. this.annotationStorage.setValue(this.data.id, {
  13528. noPrint: !event.detail.print
  13529. });
  13530. },
  13531. hidden: event => {
  13532. const {
  13533. hidden
  13534. } = event.detail;
  13535. this.container.style.visibility = hidden ? "hidden" : "visible";
  13536. this.annotationStorage.setValue(this.data.id, {
  13537. noPrint: hidden,
  13538. noView: hidden
  13539. });
  13540. },
  13541. focus: event => {
  13542. setTimeout(() => event.target.focus({
  13543. preventScroll: false
  13544. }), 0);
  13545. },
  13546. userName: event => {
  13547. event.target.title = event.detail.userName;
  13548. },
  13549. readonly: event => {
  13550. event.target.disabled = event.detail.readonly;
  13551. },
  13552. required: event => {
  13553. this._setRequired(event.target, event.detail.required);
  13554. },
  13555. bgColor: event => {
  13556. setColor("bgColor", "backgroundColor", event);
  13557. },
  13558. fillColor: event => {
  13559. setColor("fillColor", "backgroundColor", event);
  13560. },
  13561. fgColor: event => {
  13562. setColor("fgColor", "color", event);
  13563. },
  13564. textColor: event => {
  13565. setColor("textColor", "color", event);
  13566. },
  13567. borderColor: event => {
  13568. setColor("borderColor", "borderColor", event);
  13569. },
  13570. strokeColor: event => {
  13571. setColor("strokeColor", "borderColor", event);
  13572. },
  13573. rotation: event => {
  13574. const angle = event.detail.rotation;
  13575. this.setRotation(angle);
  13576. this.annotationStorage.setValue(this.data.id, {
  13577. rotation: angle
  13578. });
  13579. }
  13580. });
  13581. }
  13582. _dispatchEventFromSandbox(actions, jsEvent) {
  13583. const commonActions = this._commonActions;
  13584. for (const name of Object.keys(jsEvent.detail)) {
  13585. const action = actions[name] || commonActions[name];
  13586. action?.(jsEvent);
  13587. }
  13588. }
  13589. _setDefaultPropertiesFromJS(element) {
  13590. if (!this.enableScripting) {
  13591. return;
  13592. }
  13593. const storedData = this.annotationStorage.getRawValue(this.data.id);
  13594. if (!storedData) {
  13595. return;
  13596. }
  13597. const commonActions = this._commonActions;
  13598. for (const [actionName, detail] of Object.entries(storedData)) {
  13599. const action = commonActions[actionName];
  13600. if (action) {
  13601. const eventProxy = {
  13602. detail: {
  13603. [actionName]: detail
  13604. },
  13605. target: element
  13606. };
  13607. action(eventProxy);
  13608. delete storedData[actionName];
  13609. }
  13610. }
  13611. }
  13612. _createQuadrilaterals() {
  13613. if (!this.container) {
  13614. return;
  13615. }
  13616. const {
  13617. quadPoints
  13618. } = this.data;
  13619. if (!quadPoints) {
  13620. return;
  13621. }
  13622. const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x));
  13623. if (quadPoints.length === 8) {
  13624. const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);
  13625. if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
  13626. return;
  13627. }
  13628. }
  13629. const {
  13630. style
  13631. } = this.container;
  13632. let svgBuffer;
  13633. if (this.#hasBorder) {
  13634. const {
  13635. borderColor,
  13636. borderWidth
  13637. } = style;
  13638. style.borderWidth = 0;
  13639. 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}">`];
  13640. this.container.classList.add("hasBorder");
  13641. }
  13642. const width = rectTrX - rectBlX;
  13643. const height = rectTrY - rectBlY;
  13644. const {
  13645. svgFactory
  13646. } = this;
  13647. const svg = svgFactory.createElement("svg");
  13648. svg.classList.add("quadrilateralsContainer");
  13649. svg.setAttribute("width", 0);
  13650. svg.setAttribute("height", 0);
  13651. const defs = svgFactory.createElement("defs");
  13652. svg.append(defs);
  13653. const clipPath = svgFactory.createElement("clipPath");
  13654. const id = `clippath_${this.data.id}`;
  13655. clipPath.setAttribute("id", id);
  13656. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  13657. defs.append(clipPath);
  13658. for (let i = 2, ii = quadPoints.length; i < ii; i += 8) {
  13659. const trX = quadPoints[i];
  13660. const trY = quadPoints[i + 1];
  13661. const blX = quadPoints[i + 2];
  13662. const blY = quadPoints[i + 3];
  13663. const rect = svgFactory.createElement("rect");
  13664. const x = (blX - rectBlX) / width;
  13665. const y = (rectTrY - trY) / height;
  13666. const rectWidth = (trX - blX) / width;
  13667. const rectHeight = (trY - blY) / height;
  13668. rect.setAttribute("x", x);
  13669. rect.setAttribute("y", y);
  13670. rect.setAttribute("width", rectWidth);
  13671. rect.setAttribute("height", rectHeight);
  13672. clipPath.append(rect);
  13673. svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);
  13674. }
  13675. if (this.#hasBorder) {
  13676. svgBuffer.push(`</g></svg>')`);
  13677. style.backgroundImage = svgBuffer.join("");
  13678. }
  13679. this.container.append(svg);
  13680. this.container.style.clipPath = `url(#${id})`;
  13681. }
  13682. _createPopup() {
  13683. const {
  13684. data
  13685. } = this;
  13686. const popup = this.#popupElement = new PopupAnnotationElement({
  13687. data: {
  13688. color: data.color,
  13689. titleObj: data.titleObj,
  13690. modificationDate: data.modificationDate,
  13691. contentsObj: data.contentsObj,
  13692. richText: data.richText,
  13693. parentRect: data.rect,
  13694. borderStyle: 0,
  13695. id: `popup_${data.id}`,
  13696. rotation: data.rotation
  13697. },
  13698. parent: this.parent,
  13699. elements: [this]
  13700. });
  13701. this.parent.div.append(popup.render());
  13702. }
  13703. render() {
  13704. unreachable("Abstract method `AnnotationElement.render` called");
  13705. }
  13706. _getElementsByName(name, skipId = null) {
  13707. const fields = [];
  13708. if (this._fieldObjects) {
  13709. const fieldObj = this._fieldObjects[name];
  13710. if (fieldObj) {
  13711. for (const {
  13712. page,
  13713. id,
  13714. exportValues
  13715. } of fieldObj) {
  13716. if (page === -1) {
  13717. continue;
  13718. }
  13719. if (id === skipId) {
  13720. continue;
  13721. }
  13722. const exportValue = typeof exportValues === "string" ? exportValues : null;
  13723. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  13724. if (domElement && !GetElementsByNameSet.has(domElement)) {
  13725. warn(`_getElementsByName - element not allowed: ${id}`);
  13726. continue;
  13727. }
  13728. fields.push({
  13729. id,
  13730. exportValue,
  13731. domElement
  13732. });
  13733. }
  13734. }
  13735. return fields;
  13736. }
  13737. for (const domElement of document.getElementsByName(name)) {
  13738. const {
  13739. exportValue
  13740. } = domElement;
  13741. const id = domElement.getAttribute("data-element-id");
  13742. if (id === skipId) {
  13743. continue;
  13744. }
  13745. if (!GetElementsByNameSet.has(domElement)) {
  13746. continue;
  13747. }
  13748. fields.push({
  13749. id,
  13750. exportValue,
  13751. domElement
  13752. });
  13753. }
  13754. return fields;
  13755. }
  13756. show() {
  13757. if (this.container) {
  13758. this.container.hidden = false;
  13759. }
  13760. this.popup?.maybeShow();
  13761. }
  13762. hide() {
  13763. if (this.container) {
  13764. this.container.hidden = true;
  13765. }
  13766. this.popup?.forceHide();
  13767. }
  13768. getElementsToTriggerPopup() {
  13769. return this.container;
  13770. }
  13771. addHighlightArea() {
  13772. const triggers = this.getElementsToTriggerPopup();
  13773. if (Array.isArray(triggers)) {
  13774. for (const element of triggers) {
  13775. element.classList.add("highlightArea");
  13776. }
  13777. } else {
  13778. triggers.classList.add("highlightArea");
  13779. }
  13780. }
  13781. _editOnDoubleClick() {
  13782. if (!this._isEditable) {
  13783. return;
  13784. }
  13785. const {
  13786. annotationEditorType: mode,
  13787. data: {
  13788. id: editId
  13789. }
  13790. } = this;
  13791. this.container.addEventListener("dblclick", () => {
  13792. this.linkService.eventBus?.dispatch("switchannotationeditormode", {
  13793. source: this,
  13794. mode,
  13795. editId
  13796. });
  13797. });
  13798. }
  13799. }
  13800. class LinkAnnotationElement extends AnnotationElement {
  13801. constructor(parameters, options = null) {
  13802. super(parameters, {
  13803. isRenderable: true,
  13804. ignoreBorder: !!options?.ignoreBorder,
  13805. createQuadrilaterals: true
  13806. });
  13807. this.isTooltipOnly = parameters.data.isTooltipOnly;
  13808. }
  13809. render() {
  13810. const {
  13811. data,
  13812. linkService
  13813. } = this;
  13814. const link = document.createElement("a");
  13815. link.setAttribute("data-element-id", data.id);
  13816. let isBound = false;
  13817. if (data.url) {
  13818. linkService.addLinkAttributes(link, data.url, data.newWindow);
  13819. isBound = true;
  13820. } else if (data.action) {
  13821. this._bindNamedAction(link, data.action);
  13822. isBound = true;
  13823. } else if (data.attachment) {
  13824. this.#bindAttachment(link, data.attachment, data.attachmentDest);
  13825. isBound = true;
  13826. } else if (data.setOCGState) {
  13827. this.#bindSetOCGState(link, data.setOCGState);
  13828. isBound = true;
  13829. } else if (data.dest) {
  13830. this._bindLink(link, data.dest);
  13831. isBound = true;
  13832. } else {
  13833. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  13834. this._bindJSAction(link, data);
  13835. isBound = true;
  13836. }
  13837. if (data.resetForm) {
  13838. this._bindResetFormAction(link, data.resetForm);
  13839. isBound = true;
  13840. } else if (this.isTooltipOnly && !isBound) {
  13841. this._bindLink(link, "");
  13842. isBound = true;
  13843. }
  13844. }
  13845. this.container.classList.add("linkAnnotation");
  13846. if (isBound) {
  13847. this.container.append(link);
  13848. }
  13849. return this.container;
  13850. }
  13851. #setInternalLink() {
  13852. this.container.setAttribute("data-internal-link", "");
  13853. }
  13854. _bindLink(link, destination) {
  13855. link.href = this.linkService.getDestinationHash(destination);
  13856. link.onclick = () => {
  13857. if (destination) {
  13858. this.linkService.goToDestination(destination);
  13859. }
  13860. return false;
  13861. };
  13862. if (destination || destination === "") {
  13863. this.#setInternalLink();
  13864. }
  13865. }
  13866. _bindNamedAction(link, action) {
  13867. link.href = this.linkService.getAnchorUrl("");
  13868. link.onclick = () => {
  13869. this.linkService.executeNamedAction(action);
  13870. return false;
  13871. };
  13872. this.#setInternalLink();
  13873. }
  13874. #bindAttachment(link, attachment, dest = null) {
  13875. link.href = this.linkService.getAnchorUrl("");
  13876. if (attachment.description) {
  13877. link.title = attachment.description;
  13878. }
  13879. link.onclick = () => {
  13880. this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
  13881. return false;
  13882. };
  13883. this.#setInternalLink();
  13884. }
  13885. #bindSetOCGState(link, action) {
  13886. link.href = this.linkService.getAnchorUrl("");
  13887. link.onclick = () => {
  13888. this.linkService.executeSetOCGState(action);
  13889. return false;
  13890. };
  13891. this.#setInternalLink();
  13892. }
  13893. _bindJSAction(link, data) {
  13894. link.href = this.linkService.getAnchorUrl("");
  13895. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  13896. for (const name of Object.keys(data.actions)) {
  13897. const jsName = map.get(name);
  13898. if (!jsName) {
  13899. continue;
  13900. }
  13901. link[jsName] = () => {
  13902. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  13903. source: this,
  13904. detail: {
  13905. id: data.id,
  13906. name
  13907. }
  13908. });
  13909. return false;
  13910. };
  13911. }
  13912. if (!link.onclick) {
  13913. link.onclick = () => false;
  13914. }
  13915. this.#setInternalLink();
  13916. }
  13917. _bindResetFormAction(link, resetForm) {
  13918. const otherClickAction = link.onclick;
  13919. if (!otherClickAction) {
  13920. link.href = this.linkService.getAnchorUrl("");
  13921. }
  13922. this.#setInternalLink();
  13923. if (!this._fieldObjects) {
  13924. warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  13925. if (!otherClickAction) {
  13926. link.onclick = () => false;
  13927. }
  13928. return;
  13929. }
  13930. link.onclick = () => {
  13931. otherClickAction?.();
  13932. const {
  13933. fields: resetFormFields,
  13934. refs: resetFormRefs,
  13935. include
  13936. } = resetForm;
  13937. const allFields = [];
  13938. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  13939. const fieldIds = new Set(resetFormRefs);
  13940. for (const fieldName of resetFormFields) {
  13941. const fields = this._fieldObjects[fieldName] || [];
  13942. for (const {
  13943. id
  13944. } of fields) {
  13945. fieldIds.add(id);
  13946. }
  13947. }
  13948. for (const fields of Object.values(this._fieldObjects)) {
  13949. for (const field of fields) {
  13950. if (fieldIds.has(field.id) === include) {
  13951. allFields.push(field);
  13952. }
  13953. }
  13954. }
  13955. } else {
  13956. for (const fields of Object.values(this._fieldObjects)) {
  13957. allFields.push(...fields);
  13958. }
  13959. }
  13960. const storage = this.annotationStorage;
  13961. const allIds = [];
  13962. for (const field of allFields) {
  13963. const {
  13964. id
  13965. } = field;
  13966. allIds.push(id);
  13967. switch (field.type) {
  13968. case "text":
  13969. {
  13970. const value = field.defaultValue || "";
  13971. storage.setValue(id, {
  13972. value
  13973. });
  13974. break;
  13975. }
  13976. case "checkbox":
  13977. case "radiobutton":
  13978. {
  13979. const value = field.defaultValue === field.exportValues;
  13980. storage.setValue(id, {
  13981. value
  13982. });
  13983. break;
  13984. }
  13985. case "combobox":
  13986. case "listbox":
  13987. {
  13988. const value = field.defaultValue || "";
  13989. storage.setValue(id, {
  13990. value
  13991. });
  13992. break;
  13993. }
  13994. default:
  13995. continue;
  13996. }
  13997. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  13998. if (!domElement) {
  13999. continue;
  14000. } else if (!GetElementsByNameSet.has(domElement)) {
  14001. warn(`_bindResetFormAction - element not allowed: ${id}`);
  14002. continue;
  14003. }
  14004. domElement.dispatchEvent(new Event("resetform"));
  14005. }
  14006. if (this.enableScripting) {
  14007. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14008. source: this,
  14009. detail: {
  14010. id: "app",
  14011. ids: allIds,
  14012. name: "ResetForm"
  14013. }
  14014. });
  14015. }
  14016. return false;
  14017. };
  14018. }
  14019. }
  14020. class TextAnnotationElement extends AnnotationElement {
  14021. constructor(parameters) {
  14022. super(parameters, {
  14023. isRenderable: true
  14024. });
  14025. }
  14026. render() {
  14027. this.container.classList.add("textAnnotation");
  14028. const image = document.createElement("img");
  14029. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  14030. image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
  14031. image.setAttribute("data-l10n-args", JSON.stringify({
  14032. type: this.data.name
  14033. }));
  14034. if (!this.data.popupRef && this.hasPopupData) {
  14035. this._createPopup();
  14036. }
  14037. this.container.append(image);
  14038. return this.container;
  14039. }
  14040. }
  14041. class WidgetAnnotationElement extends AnnotationElement {
  14042. render() {
  14043. return this.container;
  14044. }
  14045. showElementAndHideCanvas(element) {
  14046. if (this.data.hasOwnCanvas) {
  14047. if (element.previousSibling?.nodeName === "CANVAS") {
  14048. element.previousSibling.hidden = true;
  14049. }
  14050. element.hidden = false;
  14051. }
  14052. }
  14053. _getKeyModifier(event) {
  14054. return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
  14055. }
  14056. _setEventListener(element, elementData, baseName, eventName, valueGetter) {
  14057. if (baseName.includes("mouse")) {
  14058. element.addEventListener(baseName, event => {
  14059. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14060. source: this,
  14061. detail: {
  14062. id: this.data.id,
  14063. name: eventName,
  14064. value: valueGetter(event),
  14065. shift: event.shiftKey,
  14066. modifier: this._getKeyModifier(event)
  14067. }
  14068. });
  14069. });
  14070. } else {
  14071. element.addEventListener(baseName, event => {
  14072. if (baseName === "blur") {
  14073. if (!elementData.focused || !event.relatedTarget) {
  14074. return;
  14075. }
  14076. elementData.focused = false;
  14077. } else if (baseName === "focus") {
  14078. if (elementData.focused) {
  14079. return;
  14080. }
  14081. elementData.focused = true;
  14082. }
  14083. if (!valueGetter) {
  14084. return;
  14085. }
  14086. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14087. source: this,
  14088. detail: {
  14089. id: this.data.id,
  14090. name: eventName,
  14091. value: valueGetter(event)
  14092. }
  14093. });
  14094. });
  14095. }
  14096. }
  14097. _setEventListeners(element, elementData, names, getter) {
  14098. for (const [baseName, eventName] of names) {
  14099. if (eventName === "Action" || this.data.actions?.[eventName]) {
  14100. if (eventName === "Focus" || eventName === "Blur") {
  14101. elementData ||= {
  14102. focused: false
  14103. };
  14104. }
  14105. this._setEventListener(element, elementData, baseName, eventName, getter);
  14106. if (eventName === "Focus" && !this.data.actions?.Blur) {
  14107. this._setEventListener(element, elementData, "blur", "Blur", null);
  14108. } else if (eventName === "Blur" && !this.data.actions?.Focus) {
  14109. this._setEventListener(element, elementData, "focus", "Focus", null);
  14110. }
  14111. }
  14112. }
  14113. }
  14114. _setBackgroundColor(element) {
  14115. const color = this.data.backgroundColor || null;
  14116. element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);
  14117. }
  14118. _setTextStyle(element) {
  14119. const TEXT_ALIGNMENT = ["left", "center", "right"];
  14120. const {
  14121. fontColor
  14122. } = this.data.defaultAppearanceData;
  14123. const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
  14124. const style = element.style;
  14125. let computedFontSize;
  14126. const BORDER_SIZE = 2;
  14127. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  14128. if (this.data.multiLine) {
  14129. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  14130. const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
  14131. const lineHeight = height / numberOfLines;
  14132. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
  14133. } else {
  14134. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  14135. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
  14136. }
  14137. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  14138. style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  14139. if (this.data.textAlignment !== null) {
  14140. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  14141. }
  14142. }
  14143. _setRequired(element, isRequired) {
  14144. if (isRequired) {
  14145. element.setAttribute("required", true);
  14146. } else {
  14147. element.removeAttribute("required");
  14148. }
  14149. element.setAttribute("aria-required", isRequired);
  14150. }
  14151. }
  14152. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  14153. constructor(parameters) {
  14154. const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  14155. super(parameters, {
  14156. isRenderable
  14157. });
  14158. }
  14159. setPropertyOnSiblings(base, key, value, keyInStorage) {
  14160. const storage = this.annotationStorage;
  14161. for (const element of this._getElementsByName(base.name, base.id)) {
  14162. if (element.domElement) {
  14163. element.domElement[key] = value;
  14164. }
  14165. storage.setValue(element.id, {
  14166. [keyInStorage]: value
  14167. });
  14168. }
  14169. }
  14170. render() {
  14171. const storage = this.annotationStorage;
  14172. const id = this.data.id;
  14173. this.container.classList.add("textWidgetAnnotation");
  14174. let element = null;
  14175. if (this.renderForms) {
  14176. const storedData = storage.getValue(id, {
  14177. value: this.data.fieldValue
  14178. });
  14179. let textContent = storedData.value || "";
  14180. const maxLen = storage.getValue(id, {
  14181. charLimit: this.data.maxLen
  14182. }).charLimit;
  14183. if (maxLen && textContent.length > maxLen) {
  14184. textContent = textContent.slice(0, maxLen);
  14185. }
  14186. let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
  14187. if (fieldFormattedValues && this.data.comb) {
  14188. fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
  14189. }
  14190. const elementData = {
  14191. userValue: textContent,
  14192. formattedValue: fieldFormattedValues,
  14193. lastCommittedValue: null,
  14194. commitKey: 1,
  14195. focused: false
  14196. };
  14197. if (this.data.multiLine) {
  14198. element = document.createElement("textarea");
  14199. element.textContent = fieldFormattedValues ?? textContent;
  14200. if (this.data.doNotScroll) {
  14201. element.style.overflowY = "hidden";
  14202. }
  14203. } else {
  14204. element = document.createElement("input");
  14205. element.type = "text";
  14206. element.setAttribute("value", fieldFormattedValues ?? textContent);
  14207. if (this.data.doNotScroll) {
  14208. element.style.overflowX = "hidden";
  14209. }
  14210. }
  14211. if (this.data.hasOwnCanvas) {
  14212. element.hidden = true;
  14213. }
  14214. GetElementsByNameSet.add(element);
  14215. element.setAttribute("data-element-id", id);
  14216. element.disabled = this.data.readOnly;
  14217. element.name = this.data.fieldName;
  14218. element.tabIndex = DEFAULT_TAB_INDEX;
  14219. this._setRequired(element, this.data.required);
  14220. if (maxLen) {
  14221. element.maxLength = maxLen;
  14222. }
  14223. element.addEventListener("input", event => {
  14224. storage.setValue(id, {
  14225. value: event.target.value
  14226. });
  14227. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  14228. elementData.formattedValue = null;
  14229. });
  14230. element.addEventListener("resetform", event => {
  14231. const defaultValue = this.data.defaultFieldValue ?? "";
  14232. element.value = elementData.userValue = defaultValue;
  14233. elementData.formattedValue = null;
  14234. });
  14235. let blurListener = event => {
  14236. const {
  14237. formattedValue
  14238. } = elementData;
  14239. if (formattedValue !== null && formattedValue !== undefined) {
  14240. event.target.value = formattedValue;
  14241. }
  14242. event.target.scrollLeft = 0;
  14243. };
  14244. if (this.enableScripting && this.hasJSActions) {
  14245. element.addEventListener("focus", event => {
  14246. if (elementData.focused) {
  14247. return;
  14248. }
  14249. const {
  14250. target
  14251. } = event;
  14252. if (elementData.userValue) {
  14253. target.value = elementData.userValue;
  14254. }
  14255. elementData.lastCommittedValue = target.value;
  14256. elementData.commitKey = 1;
  14257. if (!this.data.actions?.Focus) {
  14258. elementData.focused = true;
  14259. }
  14260. });
  14261. element.addEventListener("updatefromsandbox", jsEvent => {
  14262. this.showElementAndHideCanvas(jsEvent.target);
  14263. const actions = {
  14264. value(event) {
  14265. elementData.userValue = event.detail.value ?? "";
  14266. storage.setValue(id, {
  14267. value: elementData.userValue.toString()
  14268. });
  14269. event.target.value = elementData.userValue;
  14270. },
  14271. formattedValue(event) {
  14272. const {
  14273. formattedValue
  14274. } = event.detail;
  14275. elementData.formattedValue = formattedValue;
  14276. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  14277. event.target.value = formattedValue;
  14278. }
  14279. storage.setValue(id, {
  14280. formattedValue
  14281. });
  14282. },
  14283. selRange(event) {
  14284. event.target.setSelectionRange(...event.detail.selRange);
  14285. },
  14286. charLimit: event => {
  14287. const {
  14288. charLimit
  14289. } = event.detail;
  14290. const {
  14291. target
  14292. } = event;
  14293. if (charLimit === 0) {
  14294. target.removeAttribute("maxLength");
  14295. return;
  14296. }
  14297. target.setAttribute("maxLength", charLimit);
  14298. let value = elementData.userValue;
  14299. if (!value || value.length <= charLimit) {
  14300. return;
  14301. }
  14302. value = value.slice(0, charLimit);
  14303. target.value = elementData.userValue = value;
  14304. storage.setValue(id, {
  14305. value
  14306. });
  14307. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14308. source: this,
  14309. detail: {
  14310. id,
  14311. name: "Keystroke",
  14312. value,
  14313. willCommit: true,
  14314. commitKey: 1,
  14315. selStart: target.selectionStart,
  14316. selEnd: target.selectionEnd
  14317. }
  14318. });
  14319. }
  14320. };
  14321. this._dispatchEventFromSandbox(actions, jsEvent);
  14322. });
  14323. element.addEventListener("keydown", event => {
  14324. elementData.commitKey = 1;
  14325. let commitKey = -1;
  14326. if (event.key === "Escape") {
  14327. commitKey = 0;
  14328. } else if (event.key === "Enter" && !this.data.multiLine) {
  14329. commitKey = 2;
  14330. } else if (event.key === "Tab") {
  14331. elementData.commitKey = 3;
  14332. }
  14333. if (commitKey === -1) {
  14334. return;
  14335. }
  14336. const {
  14337. value
  14338. } = event.target;
  14339. if (elementData.lastCommittedValue === value) {
  14340. return;
  14341. }
  14342. elementData.lastCommittedValue = value;
  14343. elementData.userValue = value;
  14344. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14345. source: this,
  14346. detail: {
  14347. id,
  14348. name: "Keystroke",
  14349. value,
  14350. willCommit: true,
  14351. commitKey,
  14352. selStart: event.target.selectionStart,
  14353. selEnd: event.target.selectionEnd
  14354. }
  14355. });
  14356. });
  14357. const _blurListener = blurListener;
  14358. blurListener = null;
  14359. element.addEventListener("blur", event => {
  14360. if (!elementData.focused || !event.relatedTarget) {
  14361. return;
  14362. }
  14363. if (!this.data.actions?.Blur) {
  14364. elementData.focused = false;
  14365. }
  14366. const {
  14367. value
  14368. } = event.target;
  14369. elementData.userValue = value;
  14370. if (elementData.lastCommittedValue !== value) {
  14371. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14372. source: this,
  14373. detail: {
  14374. id,
  14375. name: "Keystroke",
  14376. value,
  14377. willCommit: true,
  14378. commitKey: elementData.commitKey,
  14379. selStart: event.target.selectionStart,
  14380. selEnd: event.target.selectionEnd
  14381. }
  14382. });
  14383. }
  14384. _blurListener(event);
  14385. });
  14386. if (this.data.actions?.Keystroke) {
  14387. element.addEventListener("beforeinput", event => {
  14388. elementData.lastCommittedValue = null;
  14389. const {
  14390. data,
  14391. target
  14392. } = event;
  14393. const {
  14394. value,
  14395. selectionStart,
  14396. selectionEnd
  14397. } = target;
  14398. let selStart = selectionStart,
  14399. selEnd = selectionEnd;
  14400. switch (event.inputType) {
  14401. case "deleteWordBackward":
  14402. {
  14403. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  14404. if (match) {
  14405. selStart -= match[0].length;
  14406. }
  14407. break;
  14408. }
  14409. case "deleteWordForward":
  14410. {
  14411. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  14412. if (match) {
  14413. selEnd += match[0].length;
  14414. }
  14415. break;
  14416. }
  14417. case "deleteContentBackward":
  14418. if (selectionStart === selectionEnd) {
  14419. selStart -= 1;
  14420. }
  14421. break;
  14422. case "deleteContentForward":
  14423. if (selectionStart === selectionEnd) {
  14424. selEnd += 1;
  14425. }
  14426. break;
  14427. }
  14428. event.preventDefault();
  14429. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14430. source: this,
  14431. detail: {
  14432. id,
  14433. name: "Keystroke",
  14434. value,
  14435. change: data || "",
  14436. willCommit: false,
  14437. selStart,
  14438. selEnd
  14439. }
  14440. });
  14441. });
  14442. }
  14443. this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  14444. }
  14445. if (blurListener) {
  14446. element.addEventListener("blur", blurListener);
  14447. }
  14448. if (this.data.comb) {
  14449. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  14450. const combWidth = fieldWidth / maxLen;
  14451. element.classList.add("comb");
  14452. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  14453. }
  14454. } else {
  14455. element = document.createElement("div");
  14456. element.textContent = this.data.fieldValue;
  14457. element.style.verticalAlign = "middle";
  14458. element.style.display = "table-cell";
  14459. if (this.data.hasOwnCanvas) {
  14460. element.hidden = true;
  14461. }
  14462. }
  14463. this._setTextStyle(element);
  14464. this._setBackgroundColor(element);
  14465. this._setDefaultPropertiesFromJS(element);
  14466. this.container.append(element);
  14467. return this.container;
  14468. }
  14469. }
  14470. class SignatureWidgetAnnotationElement extends WidgetAnnotationElement {
  14471. constructor(parameters) {
  14472. super(parameters, {
  14473. isRenderable: !!parameters.data.hasOwnCanvas
  14474. });
  14475. }
  14476. }
  14477. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  14478. constructor(parameters) {
  14479. super(parameters, {
  14480. isRenderable: parameters.renderForms
  14481. });
  14482. }
  14483. render() {
  14484. const storage = this.annotationStorage;
  14485. const data = this.data;
  14486. const id = data.id;
  14487. let value = storage.getValue(id, {
  14488. value: data.exportValue === data.fieldValue
  14489. }).value;
  14490. if (typeof value === "string") {
  14491. value = value !== "Off";
  14492. storage.setValue(id, {
  14493. value
  14494. });
  14495. }
  14496. this.container.classList.add("buttonWidgetAnnotation", "checkBox");
  14497. const element = document.createElement("input");
  14498. GetElementsByNameSet.add(element);
  14499. element.setAttribute("data-element-id", id);
  14500. element.disabled = data.readOnly;
  14501. this._setRequired(element, this.data.required);
  14502. element.type = "checkbox";
  14503. element.name = data.fieldName;
  14504. if (value) {
  14505. element.setAttribute("checked", true);
  14506. }
  14507. element.setAttribute("exportValue", data.exportValue);
  14508. element.tabIndex = DEFAULT_TAB_INDEX;
  14509. element.addEventListener("change", event => {
  14510. const {
  14511. name,
  14512. checked
  14513. } = event.target;
  14514. for (const checkbox of this._getElementsByName(name, id)) {
  14515. const curChecked = checked && checkbox.exportValue === data.exportValue;
  14516. if (checkbox.domElement) {
  14517. checkbox.domElement.checked = curChecked;
  14518. }
  14519. storage.setValue(checkbox.id, {
  14520. value: curChecked
  14521. });
  14522. }
  14523. storage.setValue(id, {
  14524. value: checked
  14525. });
  14526. });
  14527. element.addEventListener("resetform", event => {
  14528. const defaultValue = data.defaultFieldValue || "Off";
  14529. event.target.checked = defaultValue === data.exportValue;
  14530. });
  14531. if (this.enableScripting && this.hasJSActions) {
  14532. element.addEventListener("updatefromsandbox", jsEvent => {
  14533. const actions = {
  14534. value(event) {
  14535. event.target.checked = event.detail.value !== "Off";
  14536. storage.setValue(id, {
  14537. value: event.target.checked
  14538. });
  14539. }
  14540. };
  14541. this._dispatchEventFromSandbox(actions, jsEvent);
  14542. });
  14543. 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);
  14544. }
  14545. this._setBackgroundColor(element);
  14546. this._setDefaultPropertiesFromJS(element);
  14547. this.container.append(element);
  14548. return this.container;
  14549. }
  14550. }
  14551. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  14552. constructor(parameters) {
  14553. super(parameters, {
  14554. isRenderable: parameters.renderForms
  14555. });
  14556. }
  14557. render() {
  14558. this.container.classList.add("buttonWidgetAnnotation", "radioButton");
  14559. const storage = this.annotationStorage;
  14560. const data = this.data;
  14561. const id = data.id;
  14562. let value = storage.getValue(id, {
  14563. value: data.fieldValue === data.buttonValue
  14564. }).value;
  14565. if (typeof value === "string") {
  14566. value = value !== data.buttonValue;
  14567. storage.setValue(id, {
  14568. value
  14569. });
  14570. }
  14571. if (value) {
  14572. for (const radio of this._getElementsByName(data.fieldName, id)) {
  14573. storage.setValue(radio.id, {
  14574. value: false
  14575. });
  14576. }
  14577. }
  14578. const element = document.createElement("input");
  14579. GetElementsByNameSet.add(element);
  14580. element.setAttribute("data-element-id", id);
  14581. element.disabled = data.readOnly;
  14582. this._setRequired(element, this.data.required);
  14583. element.type = "radio";
  14584. element.name = data.fieldName;
  14585. if (value) {
  14586. element.setAttribute("checked", true);
  14587. }
  14588. element.tabIndex = DEFAULT_TAB_INDEX;
  14589. element.addEventListener("change", event => {
  14590. const {
  14591. name,
  14592. checked
  14593. } = event.target;
  14594. for (const radio of this._getElementsByName(name, id)) {
  14595. storage.setValue(radio.id, {
  14596. value: false
  14597. });
  14598. }
  14599. storage.setValue(id, {
  14600. value: checked
  14601. });
  14602. });
  14603. element.addEventListener("resetform", event => {
  14604. const defaultValue = data.defaultFieldValue;
  14605. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  14606. });
  14607. if (this.enableScripting && this.hasJSActions) {
  14608. const pdfButtonValue = data.buttonValue;
  14609. element.addEventListener("updatefromsandbox", jsEvent => {
  14610. const actions = {
  14611. value: event => {
  14612. const checked = pdfButtonValue === event.detail.value;
  14613. for (const radio of this._getElementsByName(event.target.name)) {
  14614. const curChecked = checked && radio.id === id;
  14615. if (radio.domElement) {
  14616. radio.domElement.checked = curChecked;
  14617. }
  14618. storage.setValue(radio.id, {
  14619. value: curChecked
  14620. });
  14621. }
  14622. }
  14623. };
  14624. this._dispatchEventFromSandbox(actions, jsEvent);
  14625. });
  14626. 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);
  14627. }
  14628. this._setBackgroundColor(element);
  14629. this._setDefaultPropertiesFromJS(element);
  14630. this.container.append(element);
  14631. return this.container;
  14632. }
  14633. }
  14634. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  14635. constructor(parameters) {
  14636. super(parameters, {
  14637. ignoreBorder: parameters.data.hasAppearance
  14638. });
  14639. }
  14640. render() {
  14641. const container = super.render();
  14642. container.classList.add("buttonWidgetAnnotation", "pushButton");
  14643. const linkElement = container.lastChild;
  14644. if (this.enableScripting && this.hasJSActions && linkElement) {
  14645. this._setDefaultPropertiesFromJS(linkElement);
  14646. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  14647. this._dispatchEventFromSandbox({}, jsEvent);
  14648. });
  14649. }
  14650. return container;
  14651. }
  14652. }
  14653. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  14654. constructor(parameters) {
  14655. super(parameters, {
  14656. isRenderable: parameters.renderForms
  14657. });
  14658. }
  14659. render() {
  14660. this.container.classList.add("choiceWidgetAnnotation");
  14661. const storage = this.annotationStorage;
  14662. const id = this.data.id;
  14663. const storedData = storage.getValue(id, {
  14664. value: this.data.fieldValue
  14665. });
  14666. const selectElement = document.createElement("select");
  14667. GetElementsByNameSet.add(selectElement);
  14668. selectElement.setAttribute("data-element-id", id);
  14669. selectElement.disabled = this.data.readOnly;
  14670. this._setRequired(selectElement, this.data.required);
  14671. selectElement.name = this.data.fieldName;
  14672. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  14673. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  14674. if (!this.data.combo) {
  14675. selectElement.size = this.data.options.length;
  14676. if (this.data.multiSelect) {
  14677. selectElement.multiple = true;
  14678. }
  14679. }
  14680. selectElement.addEventListener("resetform", event => {
  14681. const defaultValue = this.data.defaultFieldValue;
  14682. for (const option of selectElement.options) {
  14683. option.selected = option.value === defaultValue;
  14684. }
  14685. });
  14686. for (const option of this.data.options) {
  14687. const optionElement = document.createElement("option");
  14688. optionElement.textContent = option.displayValue;
  14689. optionElement.value = option.exportValue;
  14690. if (storedData.value.includes(option.exportValue)) {
  14691. optionElement.setAttribute("selected", true);
  14692. addAnEmptyEntry = false;
  14693. }
  14694. selectElement.append(optionElement);
  14695. }
  14696. let removeEmptyEntry = null;
  14697. if (addAnEmptyEntry) {
  14698. const noneOptionElement = document.createElement("option");
  14699. noneOptionElement.value = " ";
  14700. noneOptionElement.setAttribute("hidden", true);
  14701. noneOptionElement.setAttribute("selected", true);
  14702. selectElement.prepend(noneOptionElement);
  14703. removeEmptyEntry = () => {
  14704. noneOptionElement.remove();
  14705. selectElement.removeEventListener("input", removeEmptyEntry);
  14706. removeEmptyEntry = null;
  14707. };
  14708. selectElement.addEventListener("input", removeEmptyEntry);
  14709. }
  14710. const getValue = isExport => {
  14711. const name = isExport ? "value" : "textContent";
  14712. const {
  14713. options,
  14714. multiple
  14715. } = selectElement;
  14716. if (!multiple) {
  14717. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  14718. }
  14719. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  14720. };
  14721. let selectedValues = getValue(false);
  14722. const getItems = event => {
  14723. const options = event.target.options;
  14724. return Array.prototype.map.call(options, option => ({
  14725. displayValue: option.textContent,
  14726. exportValue: option.value
  14727. }));
  14728. };
  14729. if (this.enableScripting && this.hasJSActions) {
  14730. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  14731. const actions = {
  14732. value(event) {
  14733. removeEmptyEntry?.();
  14734. const value = event.detail.value;
  14735. const values = new Set(Array.isArray(value) ? value : [value]);
  14736. for (const option of selectElement.options) {
  14737. option.selected = values.has(option.value);
  14738. }
  14739. storage.setValue(id, {
  14740. value: getValue(true)
  14741. });
  14742. selectedValues = getValue(false);
  14743. },
  14744. multipleSelection(event) {
  14745. selectElement.multiple = true;
  14746. },
  14747. remove(event) {
  14748. const options = selectElement.options;
  14749. const index = event.detail.remove;
  14750. options[index].selected = false;
  14751. selectElement.remove(index);
  14752. if (options.length > 0) {
  14753. const i = Array.prototype.findIndex.call(options, option => option.selected);
  14754. if (i === -1) {
  14755. options[0].selected = true;
  14756. }
  14757. }
  14758. storage.setValue(id, {
  14759. value: getValue(true),
  14760. items: getItems(event)
  14761. });
  14762. selectedValues = getValue(false);
  14763. },
  14764. clear(event) {
  14765. while (selectElement.length !== 0) {
  14766. selectElement.remove(0);
  14767. }
  14768. storage.setValue(id, {
  14769. value: null,
  14770. items: []
  14771. });
  14772. selectedValues = getValue(false);
  14773. },
  14774. insert(event) {
  14775. const {
  14776. index,
  14777. displayValue,
  14778. exportValue
  14779. } = event.detail.insert;
  14780. const selectChild = selectElement.children[index];
  14781. const optionElement = document.createElement("option");
  14782. optionElement.textContent = displayValue;
  14783. optionElement.value = exportValue;
  14784. if (selectChild) {
  14785. selectChild.before(optionElement);
  14786. } else {
  14787. selectElement.append(optionElement);
  14788. }
  14789. storage.setValue(id, {
  14790. value: getValue(true),
  14791. items: getItems(event)
  14792. });
  14793. selectedValues = getValue(false);
  14794. },
  14795. items(event) {
  14796. const {
  14797. items
  14798. } = event.detail;
  14799. while (selectElement.length !== 0) {
  14800. selectElement.remove(0);
  14801. }
  14802. for (const item of items) {
  14803. const {
  14804. displayValue,
  14805. exportValue
  14806. } = item;
  14807. const optionElement = document.createElement("option");
  14808. optionElement.textContent = displayValue;
  14809. optionElement.value = exportValue;
  14810. selectElement.append(optionElement);
  14811. }
  14812. if (selectElement.options.length > 0) {
  14813. selectElement.options[0].selected = true;
  14814. }
  14815. storage.setValue(id, {
  14816. value: getValue(true),
  14817. items: getItems(event)
  14818. });
  14819. selectedValues = getValue(false);
  14820. },
  14821. indices(event) {
  14822. const indices = new Set(event.detail.indices);
  14823. for (const option of event.target.options) {
  14824. option.selected = indices.has(option.index);
  14825. }
  14826. storage.setValue(id, {
  14827. value: getValue(true)
  14828. });
  14829. selectedValues = getValue(false);
  14830. },
  14831. editable(event) {
  14832. event.target.disabled = !event.detail.editable;
  14833. }
  14834. };
  14835. this._dispatchEventFromSandbox(actions, jsEvent);
  14836. });
  14837. selectElement.addEventListener("input", event => {
  14838. const exportValue = getValue(true);
  14839. const change = getValue(false);
  14840. storage.setValue(id, {
  14841. value: exportValue
  14842. });
  14843. event.preventDefault();
  14844. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14845. source: this,
  14846. detail: {
  14847. id,
  14848. name: "Keystroke",
  14849. value: selectedValues,
  14850. change,
  14851. changeEx: exportValue,
  14852. willCommit: false,
  14853. commitKey: 1,
  14854. keyDown: false
  14855. }
  14856. });
  14857. });
  14858. 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);
  14859. } else {
  14860. selectElement.addEventListener("input", function (event) {
  14861. storage.setValue(id, {
  14862. value: getValue(true)
  14863. });
  14864. });
  14865. }
  14866. if (this.data.combo) {
  14867. this._setTextStyle(selectElement);
  14868. } else {}
  14869. this._setBackgroundColor(selectElement);
  14870. this._setDefaultPropertiesFromJS(selectElement);
  14871. this.container.append(selectElement);
  14872. return this.container;
  14873. }
  14874. }
  14875. class PopupAnnotationElement extends AnnotationElement {
  14876. constructor(parameters) {
  14877. const {
  14878. data,
  14879. elements
  14880. } = parameters;
  14881. super(parameters, {
  14882. isRenderable: AnnotationElement._hasPopupData(data)
  14883. });
  14884. this.elements = elements;
  14885. this.popup = null;
  14886. }
  14887. render() {
  14888. this.container.classList.add("popupAnnotation");
  14889. const popup = this.popup = new PopupElement({
  14890. container: this.container,
  14891. color: this.data.color,
  14892. titleObj: this.data.titleObj,
  14893. modificationDate: this.data.modificationDate,
  14894. contentsObj: this.data.contentsObj,
  14895. richText: this.data.richText,
  14896. rect: this.data.rect,
  14897. parentRect: this.data.parentRect || null,
  14898. parent: this.parent,
  14899. elements: this.elements,
  14900. open: this.data.open
  14901. });
  14902. const elementIds = [];
  14903. for (const element of this.elements) {
  14904. element.popup = popup;
  14905. element.container.ariaHasPopup = "dialog";
  14906. elementIds.push(element.data.id);
  14907. element.addHighlightArea();
  14908. }
  14909. this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(","));
  14910. return this.container;
  14911. }
  14912. }
  14913. class PopupElement {
  14914. #boundKeyDown = this.#keyDown.bind(this);
  14915. #boundHide = this.#hide.bind(this);
  14916. #boundShow = this.#show.bind(this);
  14917. #boundToggle = this.#toggle.bind(this);
  14918. #color = null;
  14919. #container = null;
  14920. #contentsObj = null;
  14921. #dateObj = null;
  14922. #elements = null;
  14923. #parent = null;
  14924. #parentRect = null;
  14925. #pinned = false;
  14926. #popup = null;
  14927. #position = null;
  14928. #rect = null;
  14929. #richText = null;
  14930. #titleObj = null;
  14931. #updates = null;
  14932. #wasVisible = false;
  14933. constructor({
  14934. container,
  14935. color,
  14936. elements,
  14937. titleObj,
  14938. modificationDate,
  14939. contentsObj,
  14940. richText,
  14941. parent,
  14942. rect,
  14943. parentRect,
  14944. open
  14945. }) {
  14946. this.#container = container;
  14947. this.#titleObj = titleObj;
  14948. this.#contentsObj = contentsObj;
  14949. this.#richText = richText;
  14950. this.#parent = parent;
  14951. this.#color = color;
  14952. this.#rect = rect;
  14953. this.#parentRect = parentRect;
  14954. this.#elements = elements;
  14955. this.#dateObj = PDFDateString.toDateObject(modificationDate);
  14956. this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());
  14957. for (const element of this.trigger) {
  14958. element.addEventListener("click", this.#boundToggle);
  14959. element.addEventListener("mouseenter", this.#boundShow);
  14960. element.addEventListener("mouseleave", this.#boundHide);
  14961. element.classList.add("popupTriggerArea");
  14962. }
  14963. for (const element of elements) {
  14964. element.container?.addEventListener("keydown", this.#boundKeyDown);
  14965. }
  14966. this.#container.hidden = true;
  14967. if (open) {
  14968. this.#toggle();
  14969. }
  14970. }
  14971. render() {
  14972. if (this.#popup) {
  14973. return;
  14974. }
  14975. const popup = this.#popup = document.createElement("div");
  14976. popup.className = "popup";
  14977. if (this.#color) {
  14978. const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
  14979. if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) {
  14980. popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
  14981. } else {
  14982. const BACKGROUND_ENLIGHT = 0.7;
  14983. popup.style.backgroundColor = Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c)));
  14984. }
  14985. }
  14986. const header = document.createElement("span");
  14987. header.className = "header";
  14988. const title = document.createElement("h1");
  14989. header.append(title);
  14990. ({
  14991. dir: title.dir,
  14992. str: title.textContent
  14993. } = this.#titleObj);
  14994. popup.append(header);
  14995. if (this.#dateObj) {
  14996. const modificationDate = document.createElement("span");
  14997. modificationDate.classList.add("popupDate");
  14998. modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");
  14999. modificationDate.setAttribute("data-l10n-args", JSON.stringify({
  15000. dateObj: this.#dateObj.valueOf()
  15001. }));
  15002. header.append(modificationDate);
  15003. }
  15004. const html = this.#html;
  15005. if (html) {
  15006. XfaLayer.render({
  15007. xfaHtml: html,
  15008. intent: "richText",
  15009. div: popup
  15010. });
  15011. popup.lastChild.classList.add("richText", "popupContent");
  15012. } else {
  15013. const contents = this._formatContents(this.#contentsObj);
  15014. popup.append(contents);
  15015. }
  15016. this.#container.append(popup);
  15017. }
  15018. get #html() {
  15019. const richText = this.#richText;
  15020. const contentsObj = this.#contentsObj;
  15021. if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
  15022. return this.#richText.html || null;
  15023. }
  15024. return null;
  15025. }
  15026. get #fontSize() {
  15027. return this.#html?.attributes?.style?.fontSize || 0;
  15028. }
  15029. get #fontColor() {
  15030. return this.#html?.attributes?.style?.color || null;
  15031. }
  15032. #makePopupContent(text) {
  15033. const popupLines = [];
  15034. const popupContent = {
  15035. str: text,
  15036. html: {
  15037. name: "div",
  15038. attributes: {
  15039. dir: "auto"
  15040. },
  15041. children: [{
  15042. name: "p",
  15043. children: popupLines
  15044. }]
  15045. }
  15046. };
  15047. const lineAttributes = {
  15048. style: {
  15049. color: this.#fontColor,
  15050. fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--scale-factor))` : ""
  15051. }
  15052. };
  15053. for (const line of text.split("\n")) {
  15054. popupLines.push({
  15055. name: "span",
  15056. value: line,
  15057. attributes: lineAttributes
  15058. });
  15059. }
  15060. return popupContent;
  15061. }
  15062. _formatContents({
  15063. str,
  15064. dir
  15065. }) {
  15066. const p = document.createElement("p");
  15067. p.classList.add("popupContent");
  15068. p.dir = dir;
  15069. const lines = str.split(/(?:\r\n?|\n)/);
  15070. for (let i = 0, ii = lines.length; i < ii; ++i) {
  15071. const line = lines[i];
  15072. p.append(document.createTextNode(line));
  15073. if (i < ii - 1) {
  15074. p.append(document.createElement("br"));
  15075. }
  15076. }
  15077. return p;
  15078. }
  15079. #keyDown(event) {
  15080. if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
  15081. return;
  15082. }
  15083. if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
  15084. this.#toggle();
  15085. }
  15086. }
  15087. updateEdited({
  15088. rect,
  15089. popupContent
  15090. }) {
  15091. this.#updates ||= {
  15092. contentsObj: this.#contentsObj,
  15093. richText: this.#richText
  15094. };
  15095. if (rect) {
  15096. this.#position = null;
  15097. }
  15098. if (popupContent) {
  15099. this.#richText = this.#makePopupContent(popupContent);
  15100. this.#contentsObj = null;
  15101. }
  15102. this.#popup?.remove();
  15103. this.#popup = null;
  15104. }
  15105. resetEdited() {
  15106. if (!this.#updates) {
  15107. return;
  15108. }
  15109. ({
  15110. contentsObj: this.#contentsObj,
  15111. richText: this.#richText
  15112. } = this.#updates);
  15113. this.#updates = null;
  15114. this.#popup?.remove();
  15115. this.#popup = null;
  15116. this.#position = null;
  15117. }
  15118. #setPosition() {
  15119. if (this.#position !== null) {
  15120. return;
  15121. }
  15122. const {
  15123. page: {
  15124. view
  15125. },
  15126. viewport: {
  15127. rawDims: {
  15128. pageWidth,
  15129. pageHeight,
  15130. pageX,
  15131. pageY
  15132. }
  15133. }
  15134. } = this.#parent;
  15135. let useParentRect = !!this.#parentRect;
  15136. let rect = useParentRect ? this.#parentRect : this.#rect;
  15137. for (const element of this.#elements) {
  15138. if (!rect || Util.intersect(element.data.rect, rect) !== null) {
  15139. rect = element.data.rect;
  15140. useParentRect = true;
  15141. break;
  15142. }
  15143. }
  15144. const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
  15145. const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
  15146. const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
  15147. const popupLeft = normalizedRect[0] + parentWidth;
  15148. const popupTop = normalizedRect[1];
  15149. this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
  15150. const {
  15151. style
  15152. } = this.#container;
  15153. style.left = `${this.#position[0]}%`;
  15154. style.top = `${this.#position[1]}%`;
  15155. }
  15156. #toggle() {
  15157. this.#pinned = !this.#pinned;
  15158. if (this.#pinned) {
  15159. this.#show();
  15160. this.#container.addEventListener("click", this.#boundToggle);
  15161. this.#container.addEventListener("keydown", this.#boundKeyDown);
  15162. } else {
  15163. this.#hide();
  15164. this.#container.removeEventListener("click", this.#boundToggle);
  15165. this.#container.removeEventListener("keydown", this.#boundKeyDown);
  15166. }
  15167. }
  15168. #show() {
  15169. if (!this.#popup) {
  15170. this.render();
  15171. }
  15172. if (!this.isVisible) {
  15173. this.#setPosition();
  15174. this.#container.hidden = false;
  15175. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;
  15176. } else if (this.#pinned) {
  15177. this.#container.classList.add("focused");
  15178. }
  15179. }
  15180. #hide() {
  15181. this.#container.classList.remove("focused");
  15182. if (this.#pinned || !this.isVisible) {
  15183. return;
  15184. }
  15185. this.#container.hidden = true;
  15186. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;
  15187. }
  15188. forceHide() {
  15189. this.#wasVisible = this.isVisible;
  15190. if (!this.#wasVisible) {
  15191. return;
  15192. }
  15193. this.#container.hidden = true;
  15194. }
  15195. maybeShow() {
  15196. if (!this.#wasVisible) {
  15197. return;
  15198. }
  15199. if (!this.#popup) {
  15200. this.#show();
  15201. }
  15202. this.#wasVisible = false;
  15203. this.#container.hidden = false;
  15204. }
  15205. get isVisible() {
  15206. return this.#container.hidden === false;
  15207. }
  15208. }
  15209. class FreeTextAnnotationElement extends AnnotationElement {
  15210. constructor(parameters) {
  15211. super(parameters, {
  15212. isRenderable: true,
  15213. ignoreBorder: true
  15214. });
  15215. this.textContent = parameters.data.textContent;
  15216. this.textPosition = parameters.data.textPosition;
  15217. this.annotationEditorType = AnnotationEditorType.FREETEXT;
  15218. }
  15219. render() {
  15220. this.container.classList.add("freeTextAnnotation");
  15221. if (this.textContent) {
  15222. const content = document.createElement("div");
  15223. content.classList.add("annotationTextContent");
  15224. content.setAttribute("role", "comment");
  15225. for (const line of this.textContent) {
  15226. const lineSpan = document.createElement("span");
  15227. lineSpan.textContent = line;
  15228. content.append(lineSpan);
  15229. }
  15230. this.container.append(content);
  15231. }
  15232. if (!this.data.popupRef && this.hasPopupData) {
  15233. this._createPopup();
  15234. }
  15235. this._editOnDoubleClick();
  15236. return this.container;
  15237. }
  15238. }
  15239. class LineAnnotationElement extends AnnotationElement {
  15240. #line = null;
  15241. constructor(parameters) {
  15242. super(parameters, {
  15243. isRenderable: true,
  15244. ignoreBorder: true
  15245. });
  15246. }
  15247. render() {
  15248. this.container.classList.add("lineAnnotation");
  15249. const data = this.data;
  15250. const {
  15251. width,
  15252. height
  15253. } = getRectDims(data.rect);
  15254. const svg = this.svgFactory.create(width, height, true);
  15255. const line = this.#line = this.svgFactory.createElement("svg:line");
  15256. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  15257. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  15258. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  15259. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  15260. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  15261. line.setAttribute("stroke", "transparent");
  15262. line.setAttribute("fill", "transparent");
  15263. svg.append(line);
  15264. this.container.append(svg);
  15265. if (!data.popupRef && this.hasPopupData) {
  15266. this._createPopup();
  15267. }
  15268. return this.container;
  15269. }
  15270. getElementsToTriggerPopup() {
  15271. return this.#line;
  15272. }
  15273. addHighlightArea() {
  15274. this.container.classList.add("highlightArea");
  15275. }
  15276. }
  15277. class SquareAnnotationElement extends AnnotationElement {
  15278. #square = null;
  15279. constructor(parameters) {
  15280. super(parameters, {
  15281. isRenderable: true,
  15282. ignoreBorder: true
  15283. });
  15284. }
  15285. render() {
  15286. this.container.classList.add("squareAnnotation");
  15287. const data = this.data;
  15288. const {
  15289. width,
  15290. height
  15291. } = getRectDims(data.rect);
  15292. const svg = this.svgFactory.create(width, height, true);
  15293. const borderWidth = data.borderStyle.width;
  15294. const square = this.#square = this.svgFactory.createElement("svg:rect");
  15295. square.setAttribute("x", borderWidth / 2);
  15296. square.setAttribute("y", borderWidth / 2);
  15297. square.setAttribute("width", width - borderWidth);
  15298. square.setAttribute("height", height - borderWidth);
  15299. square.setAttribute("stroke-width", borderWidth || 1);
  15300. square.setAttribute("stroke", "transparent");
  15301. square.setAttribute("fill", "transparent");
  15302. svg.append(square);
  15303. this.container.append(svg);
  15304. if (!data.popupRef && this.hasPopupData) {
  15305. this._createPopup();
  15306. }
  15307. return this.container;
  15308. }
  15309. getElementsToTriggerPopup() {
  15310. return this.#square;
  15311. }
  15312. addHighlightArea() {
  15313. this.container.classList.add("highlightArea");
  15314. }
  15315. }
  15316. class CircleAnnotationElement extends AnnotationElement {
  15317. #circle = null;
  15318. constructor(parameters) {
  15319. super(parameters, {
  15320. isRenderable: true,
  15321. ignoreBorder: true
  15322. });
  15323. }
  15324. render() {
  15325. this.container.classList.add("circleAnnotation");
  15326. const data = this.data;
  15327. const {
  15328. width,
  15329. height
  15330. } = getRectDims(data.rect);
  15331. const svg = this.svgFactory.create(width, height, true);
  15332. const borderWidth = data.borderStyle.width;
  15333. const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
  15334. circle.setAttribute("cx", width / 2);
  15335. circle.setAttribute("cy", height / 2);
  15336. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  15337. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  15338. circle.setAttribute("stroke-width", borderWidth || 1);
  15339. circle.setAttribute("stroke", "transparent");
  15340. circle.setAttribute("fill", "transparent");
  15341. svg.append(circle);
  15342. this.container.append(svg);
  15343. if (!data.popupRef && this.hasPopupData) {
  15344. this._createPopup();
  15345. }
  15346. return this.container;
  15347. }
  15348. getElementsToTriggerPopup() {
  15349. return this.#circle;
  15350. }
  15351. addHighlightArea() {
  15352. this.container.classList.add("highlightArea");
  15353. }
  15354. }
  15355. class PolylineAnnotationElement extends AnnotationElement {
  15356. #polyline = null;
  15357. constructor(parameters) {
  15358. super(parameters, {
  15359. isRenderable: true,
  15360. ignoreBorder: true
  15361. });
  15362. this.containerClassName = "polylineAnnotation";
  15363. this.svgElementName = "svg:polyline";
  15364. }
  15365. render() {
  15366. this.container.classList.add(this.containerClassName);
  15367. const {
  15368. data: {
  15369. rect,
  15370. vertices,
  15371. borderStyle,
  15372. popupRef
  15373. }
  15374. } = this;
  15375. if (!vertices) {
  15376. return this.container;
  15377. }
  15378. const {
  15379. width,
  15380. height
  15381. } = getRectDims(rect);
  15382. const svg = this.svgFactory.create(width, height, true);
  15383. let points = [];
  15384. for (let i = 0, ii = vertices.length; i < ii; i += 2) {
  15385. const x = vertices[i] - rect[0];
  15386. const y = rect[3] - vertices[i + 1];
  15387. points.push(`${x},${y}`);
  15388. }
  15389. points = points.join(" ");
  15390. const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
  15391. polyline.setAttribute("points", points);
  15392. polyline.setAttribute("stroke-width", borderStyle.width || 1);
  15393. polyline.setAttribute("stroke", "transparent");
  15394. polyline.setAttribute("fill", "transparent");
  15395. svg.append(polyline);
  15396. this.container.append(svg);
  15397. if (!popupRef && this.hasPopupData) {
  15398. this._createPopup();
  15399. }
  15400. return this.container;
  15401. }
  15402. getElementsToTriggerPopup() {
  15403. return this.#polyline;
  15404. }
  15405. addHighlightArea() {
  15406. this.container.classList.add("highlightArea");
  15407. }
  15408. }
  15409. class PolygonAnnotationElement extends PolylineAnnotationElement {
  15410. constructor(parameters) {
  15411. super(parameters);
  15412. this.containerClassName = "polygonAnnotation";
  15413. this.svgElementName = "svg:polygon";
  15414. }
  15415. }
  15416. class CaretAnnotationElement extends AnnotationElement {
  15417. constructor(parameters) {
  15418. super(parameters, {
  15419. isRenderable: true,
  15420. ignoreBorder: true
  15421. });
  15422. }
  15423. render() {
  15424. this.container.classList.add("caretAnnotation");
  15425. if (!this.data.popupRef && this.hasPopupData) {
  15426. this._createPopup();
  15427. }
  15428. return this.container;
  15429. }
  15430. }
  15431. class InkAnnotationElement extends AnnotationElement {
  15432. #polylines = [];
  15433. constructor(parameters) {
  15434. super(parameters, {
  15435. isRenderable: true,
  15436. ignoreBorder: true
  15437. });
  15438. this.containerClassName = "inkAnnotation";
  15439. this.svgElementName = "svg:polyline";
  15440. this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;
  15441. }
  15442. render() {
  15443. this.container.classList.add(this.containerClassName);
  15444. const {
  15445. data: {
  15446. rect,
  15447. inkLists,
  15448. borderStyle,
  15449. popupRef
  15450. }
  15451. } = this;
  15452. const {
  15453. width,
  15454. height
  15455. } = getRectDims(rect);
  15456. const svg = this.svgFactory.create(width, height, true);
  15457. for (const inkList of inkLists) {
  15458. let points = [];
  15459. for (let i = 0, ii = inkList.length; i < ii; i += 2) {
  15460. const x = inkList[i] - rect[0];
  15461. const y = rect[3] - inkList[i + 1];
  15462. points.push(`${x},${y}`);
  15463. }
  15464. points = points.join(" ");
  15465. const polyline = this.svgFactory.createElement(this.svgElementName);
  15466. this.#polylines.push(polyline);
  15467. polyline.setAttribute("points", points);
  15468. polyline.setAttribute("stroke-width", borderStyle.width || 1);
  15469. polyline.setAttribute("stroke", "transparent");
  15470. polyline.setAttribute("fill", "transparent");
  15471. svg.append(polyline);
  15472. }
  15473. if (!popupRef && this.hasPopupData) {
  15474. this._createPopup();
  15475. }
  15476. this.container.append(svg);
  15477. this._editOnDoubleClick();
  15478. return this.container;
  15479. }
  15480. getElementsToTriggerPopup() {
  15481. return this.#polylines;
  15482. }
  15483. addHighlightArea() {
  15484. this.container.classList.add("highlightArea");
  15485. }
  15486. }
  15487. class HighlightAnnotationElement extends AnnotationElement {
  15488. constructor(parameters) {
  15489. super(parameters, {
  15490. isRenderable: true,
  15491. ignoreBorder: true,
  15492. createQuadrilaterals: true
  15493. });
  15494. this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;
  15495. }
  15496. render() {
  15497. if (!this.data.popupRef && this.hasPopupData) {
  15498. this._createPopup();
  15499. }
  15500. this.container.classList.add("highlightAnnotation");
  15501. this._editOnDoubleClick();
  15502. return this.container;
  15503. }
  15504. }
  15505. class UnderlineAnnotationElement extends AnnotationElement {
  15506. constructor(parameters) {
  15507. super(parameters, {
  15508. isRenderable: true,
  15509. ignoreBorder: true,
  15510. createQuadrilaterals: true
  15511. });
  15512. }
  15513. render() {
  15514. if (!this.data.popupRef && this.hasPopupData) {
  15515. this._createPopup();
  15516. }
  15517. this.container.classList.add("underlineAnnotation");
  15518. return this.container;
  15519. }
  15520. }
  15521. class SquigglyAnnotationElement extends AnnotationElement {
  15522. constructor(parameters) {
  15523. super(parameters, {
  15524. isRenderable: true,
  15525. ignoreBorder: true,
  15526. createQuadrilaterals: true
  15527. });
  15528. }
  15529. render() {
  15530. if (!this.data.popupRef && this.hasPopupData) {
  15531. this._createPopup();
  15532. }
  15533. this.container.classList.add("squigglyAnnotation");
  15534. return this.container;
  15535. }
  15536. }
  15537. class StrikeOutAnnotationElement extends AnnotationElement {
  15538. constructor(parameters) {
  15539. super(parameters, {
  15540. isRenderable: true,
  15541. ignoreBorder: true,
  15542. createQuadrilaterals: true
  15543. });
  15544. }
  15545. render() {
  15546. if (!this.data.popupRef && this.hasPopupData) {
  15547. this._createPopup();
  15548. }
  15549. this.container.classList.add("strikeoutAnnotation");
  15550. return this.container;
  15551. }
  15552. }
  15553. class StampAnnotationElement extends AnnotationElement {
  15554. constructor(parameters) {
  15555. super(parameters, {
  15556. isRenderable: true,
  15557. ignoreBorder: true
  15558. });
  15559. this.annotationEditorType = AnnotationEditorType.STAMP;
  15560. }
  15561. render() {
  15562. this.container.classList.add("stampAnnotation");
  15563. this.container.setAttribute("role", "img");
  15564. if (!this.data.popupRef && this.hasPopupData) {
  15565. this._createPopup();
  15566. }
  15567. this._editOnDoubleClick();
  15568. return this.container;
  15569. }
  15570. }
  15571. class FileAttachmentAnnotationElement extends AnnotationElement {
  15572. #trigger = null;
  15573. constructor(parameters) {
  15574. super(parameters, {
  15575. isRenderable: true
  15576. });
  15577. const {
  15578. file
  15579. } = this.data;
  15580. this.filename = file.filename;
  15581. this.content = file.content;
  15582. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  15583. source: this,
  15584. ...file
  15585. });
  15586. }
  15587. render() {
  15588. this.container.classList.add("fileAttachmentAnnotation");
  15589. const {
  15590. container,
  15591. data
  15592. } = this;
  15593. let trigger;
  15594. if (data.hasAppearance || data.fillAlpha === 0) {
  15595. trigger = document.createElement("div");
  15596. } else {
  15597. trigger = document.createElement("img");
  15598. trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
  15599. if (data.fillAlpha && data.fillAlpha < 1) {
  15600. trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
  15601. }
  15602. }
  15603. trigger.addEventListener("dblclick", this.#download.bind(this));
  15604. this.#trigger = trigger;
  15605. const {
  15606. isMac
  15607. } = util_FeatureTest.platform;
  15608. container.addEventListener("keydown", evt => {
  15609. if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
  15610. this.#download();
  15611. }
  15612. });
  15613. if (!data.popupRef && this.hasPopupData) {
  15614. this._createPopup();
  15615. } else {
  15616. trigger.classList.add("popupTriggerArea");
  15617. }
  15618. container.append(trigger);
  15619. return container;
  15620. }
  15621. getElementsToTriggerPopup() {
  15622. return this.#trigger;
  15623. }
  15624. addHighlightArea() {
  15625. this.container.classList.add("highlightArea");
  15626. }
  15627. #download() {
  15628. this.downloadManager?.openOrDownloadData(this.content, this.filename);
  15629. }
  15630. }
  15631. class AnnotationLayer {
  15632. #accessibilityManager = null;
  15633. #annotationCanvasMap = null;
  15634. #editableAnnotations = new Map();
  15635. #structTreeLayer = null;
  15636. constructor({
  15637. div,
  15638. accessibilityManager,
  15639. annotationCanvasMap,
  15640. annotationEditorUIManager,
  15641. page,
  15642. viewport,
  15643. structTreeLayer
  15644. }) {
  15645. this.div = div;
  15646. this.#accessibilityManager = accessibilityManager;
  15647. this.#annotationCanvasMap = annotationCanvasMap;
  15648. this.#structTreeLayer = structTreeLayer || null;
  15649. this.page = page;
  15650. this.viewport = viewport;
  15651. this.zIndex = 0;
  15652. this._annotationEditorUIManager = annotationEditorUIManager;
  15653. }
  15654. hasEditableAnnotations() {
  15655. return this.#editableAnnotations.size > 0;
  15656. }
  15657. async #appendElement(element, id) {
  15658. const contentElement = element.firstChild || element;
  15659. const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;
  15660. const ariaAttributes = await this.#structTreeLayer?.getAriaAttributes(annotationId);
  15661. if (ariaAttributes) {
  15662. for (const [key, value] of ariaAttributes) {
  15663. contentElement.setAttribute(key, value);
  15664. }
  15665. }
  15666. this.div.append(element);
  15667. this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false);
  15668. }
  15669. async render(params) {
  15670. const {
  15671. annotations
  15672. } = params;
  15673. const layer = this.div;
  15674. setLayerDimensions(layer, this.viewport);
  15675. const popupToElements = new Map();
  15676. const elementParams = {
  15677. data: null,
  15678. layer,
  15679. linkService: params.linkService,
  15680. downloadManager: params.downloadManager,
  15681. imageResourcesPath: params.imageResourcesPath || "",
  15682. renderForms: params.renderForms !== false,
  15683. svgFactory: new DOMSVGFactory(),
  15684. annotationStorage: params.annotationStorage || new AnnotationStorage(),
  15685. enableScripting: params.enableScripting === true,
  15686. hasJSActions: params.hasJSActions,
  15687. fieldObjects: params.fieldObjects,
  15688. parent: this,
  15689. elements: null
  15690. };
  15691. for (const data of annotations) {
  15692. if (data.noHTML) {
  15693. continue;
  15694. }
  15695. const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
  15696. if (!isPopupAnnotation) {
  15697. const {
  15698. width,
  15699. height
  15700. } = getRectDims(data.rect);
  15701. if (width <= 0 || height <= 0) {
  15702. continue;
  15703. }
  15704. } else {
  15705. const elements = popupToElements.get(data.id);
  15706. if (!elements) {
  15707. continue;
  15708. }
  15709. elementParams.elements = elements;
  15710. }
  15711. elementParams.data = data;
  15712. const element = AnnotationElementFactory.create(elementParams);
  15713. if (!element.isRenderable) {
  15714. continue;
  15715. }
  15716. if (!isPopupAnnotation && data.popupRef) {
  15717. const elements = popupToElements.get(data.popupRef);
  15718. if (!elements) {
  15719. popupToElements.set(data.popupRef, [element]);
  15720. } else {
  15721. elements.push(element);
  15722. }
  15723. }
  15724. const rendered = element.render();
  15725. if (data.hidden) {
  15726. rendered.style.visibility = "hidden";
  15727. }
  15728. await this.#appendElement(rendered, data.id);
  15729. if (element._isEditable) {
  15730. this.#editableAnnotations.set(element.data.id, element);
  15731. this._annotationEditorUIManager?.renderAnnotationElement(element);
  15732. }
  15733. }
  15734. this.#setAnnotationCanvasMap();
  15735. }
  15736. update({
  15737. viewport
  15738. }) {
  15739. const layer = this.div;
  15740. this.viewport = viewport;
  15741. setLayerDimensions(layer, {
  15742. rotation: viewport.rotation
  15743. });
  15744. this.#setAnnotationCanvasMap();
  15745. layer.hidden = false;
  15746. }
  15747. #setAnnotationCanvasMap() {
  15748. if (!this.#annotationCanvasMap) {
  15749. return;
  15750. }
  15751. const layer = this.div;
  15752. for (const [id, canvas] of this.#annotationCanvasMap) {
  15753. const element = layer.querySelector(`[data-annotation-id="${id}"]`);
  15754. if (!element) {
  15755. continue;
  15756. }
  15757. canvas.className = "annotationContent";
  15758. const {
  15759. firstChild
  15760. } = element;
  15761. if (!firstChild) {
  15762. element.append(canvas);
  15763. } else if (firstChild.nodeName === "CANVAS") {
  15764. firstChild.replaceWith(canvas);
  15765. } else if (!firstChild.classList.contains("annotationContent")) {
  15766. firstChild.before(canvas);
  15767. } else {
  15768. firstChild.after(canvas);
  15769. }
  15770. }
  15771. this.#annotationCanvasMap.clear();
  15772. }
  15773. getEditableAnnotations() {
  15774. return Array.from(this.#editableAnnotations.values());
  15775. }
  15776. getEditableAnnotation(id) {
  15777. return this.#editableAnnotations.get(id);
  15778. }
  15779. }
  15780. ;// ./src/display/editor/freetext.js
  15781. const EOL_PATTERN = /\r\n?|\n/g;
  15782. class FreeTextEditor extends AnnotationEditor {
  15783. #color;
  15784. #content = "";
  15785. #editorDivId = `${this.id}-editor`;
  15786. #editModeAC = null;
  15787. #fontSize;
  15788. static _freeTextDefaultContent = "";
  15789. static _internalPadding = 0;
  15790. static _defaultColor = null;
  15791. static _defaultFontSize = 10;
  15792. static get _keyboardManager() {
  15793. const proto = FreeTextEditor.prototype;
  15794. const arrowChecker = self => self.isEmpty();
  15795. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  15796. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  15797. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
  15798. bubbles: true
  15799. }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
  15800. args: [-small, 0],
  15801. checker: arrowChecker
  15802. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
  15803. args: [-big, 0],
  15804. checker: arrowChecker
  15805. }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
  15806. args: [small, 0],
  15807. checker: arrowChecker
  15808. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
  15809. args: [big, 0],
  15810. checker: arrowChecker
  15811. }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
  15812. args: [0, -small],
  15813. checker: arrowChecker
  15814. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
  15815. args: [0, -big],
  15816. checker: arrowChecker
  15817. }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
  15818. args: [0, small],
  15819. checker: arrowChecker
  15820. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
  15821. args: [0, big],
  15822. checker: arrowChecker
  15823. }]]));
  15824. }
  15825. static _type = "freetext";
  15826. static _editorType = AnnotationEditorType.FREETEXT;
  15827. constructor(params) {
  15828. super({
  15829. ...params,
  15830. name: "freeTextEditor"
  15831. });
  15832. this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
  15833. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  15834. }
  15835. static initialize(l10n, uiManager) {
  15836. AnnotationEditor.initialize(l10n, uiManager);
  15837. const style = getComputedStyle(document.documentElement);
  15838. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  15839. }
  15840. static updateDefaultParams(type, value) {
  15841. switch (type) {
  15842. case AnnotationEditorParamsType.FREETEXT_SIZE:
  15843. FreeTextEditor._defaultFontSize = value;
  15844. break;
  15845. case AnnotationEditorParamsType.FREETEXT_COLOR:
  15846. FreeTextEditor._defaultColor = value;
  15847. break;
  15848. }
  15849. }
  15850. updateParams(type, value) {
  15851. switch (type) {
  15852. case AnnotationEditorParamsType.FREETEXT_SIZE:
  15853. this.#updateFontSize(value);
  15854. break;
  15855. case AnnotationEditorParamsType.FREETEXT_COLOR:
  15856. this.#updateColor(value);
  15857. break;
  15858. }
  15859. }
  15860. static get defaultPropertiesToUpdate() {
  15861. return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
  15862. }
  15863. get propertiesToUpdate() {
  15864. return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  15865. }
  15866. #updateFontSize(fontSize) {
  15867. const setFontsize = size => {
  15868. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  15869. this.translate(0, -(size - this.#fontSize) * this.parentScale);
  15870. this.#fontSize = size;
  15871. this.#setEditorDimensions();
  15872. };
  15873. const savedFontsize = this.#fontSize;
  15874. this.addCommands({
  15875. cmd: setFontsize.bind(this, fontSize),
  15876. undo: setFontsize.bind(this, savedFontsize),
  15877. post: this._uiManager.updateUI.bind(this._uiManager, this),
  15878. mustExec: true,
  15879. type: AnnotationEditorParamsType.FREETEXT_SIZE,
  15880. overwriteIfSameType: true,
  15881. keepUndo: true
  15882. });
  15883. }
  15884. #updateColor(color) {
  15885. const setColor = col => {
  15886. this.#color = this.editorDiv.style.color = col;
  15887. };
  15888. const savedColor = this.#color;
  15889. this.addCommands({
  15890. cmd: setColor.bind(this, color),
  15891. undo: setColor.bind(this, savedColor),
  15892. post: this._uiManager.updateUI.bind(this._uiManager, this),
  15893. mustExec: true,
  15894. type: AnnotationEditorParamsType.FREETEXT_COLOR,
  15895. overwriteIfSameType: true,
  15896. keepUndo: true
  15897. });
  15898. }
  15899. _translateEmpty(x, y) {
  15900. this._uiManager.translateSelectedEditors(x, y, true);
  15901. }
  15902. getInitialTranslation() {
  15903. const scale = this.parentScale;
  15904. return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  15905. }
  15906. rebuild() {
  15907. if (!this.parent) {
  15908. return;
  15909. }
  15910. super.rebuild();
  15911. if (this.div === null) {
  15912. return;
  15913. }
  15914. if (!this.isAttachedToDOM) {
  15915. this.parent.add(this);
  15916. }
  15917. }
  15918. enableEditMode() {
  15919. if (this.isInEditMode()) {
  15920. return;
  15921. }
  15922. this.parent.setEditingState(false);
  15923. this.parent.updateToolbar(AnnotationEditorType.FREETEXT);
  15924. super.enableEditMode();
  15925. this.overlayDiv.classList.remove("enabled");
  15926. this.editorDiv.contentEditable = true;
  15927. this._isDraggable = false;
  15928. this.div.removeAttribute("aria-activedescendant");
  15929. this.#editModeAC = new AbortController();
  15930. const signal = this._uiManager.combinedSignal(this.#editModeAC);
  15931. this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {
  15932. signal
  15933. });
  15934. this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {
  15935. signal
  15936. });
  15937. this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {
  15938. signal
  15939. });
  15940. this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {
  15941. signal
  15942. });
  15943. this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {
  15944. signal
  15945. });
  15946. }
  15947. disableEditMode() {
  15948. if (!this.isInEditMode()) {
  15949. return;
  15950. }
  15951. this.parent.setEditingState(true);
  15952. super.disableEditMode();
  15953. this.overlayDiv.classList.add("enabled");
  15954. this.editorDiv.contentEditable = false;
  15955. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  15956. this._isDraggable = true;
  15957. this.#editModeAC?.abort();
  15958. this.#editModeAC = null;
  15959. this.div.focus({
  15960. preventScroll: true
  15961. });
  15962. this.isEditing = false;
  15963. this.parent.div.classList.add("freetextEditing");
  15964. }
  15965. focusin(event) {
  15966. if (!this._focusEventsAllowed) {
  15967. return;
  15968. }
  15969. super.focusin(event);
  15970. if (event.target !== this.editorDiv) {
  15971. this.editorDiv.focus();
  15972. }
  15973. }
  15974. onceAdded() {
  15975. if (this.width) {
  15976. return;
  15977. }
  15978. this.enableEditMode();
  15979. this.editorDiv.focus();
  15980. if (this._initialOptions?.isCentered) {
  15981. this.center();
  15982. }
  15983. this._initialOptions = null;
  15984. }
  15985. isEmpty() {
  15986. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  15987. }
  15988. remove() {
  15989. this.isEditing = false;
  15990. if (this.parent) {
  15991. this.parent.setEditingState(true);
  15992. this.parent.div.classList.add("freetextEditing");
  15993. }
  15994. super.remove();
  15995. }
  15996. #extractText() {
  15997. const buffer = [];
  15998. this.editorDiv.normalize();
  15999. let prevChild = null;
  16000. for (const child of this.editorDiv.childNodes) {
  16001. if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {
  16002. continue;
  16003. }
  16004. buffer.push(FreeTextEditor.#getNodeContent(child));
  16005. prevChild = child;
  16006. }
  16007. return buffer.join("\n");
  16008. }
  16009. #setEditorDimensions() {
  16010. const [parentWidth, parentHeight] = this.parentDimensions;
  16011. let rect;
  16012. if (this.isAttachedToDOM) {
  16013. rect = this.div.getBoundingClientRect();
  16014. } else {
  16015. const {
  16016. currentLayer,
  16017. div
  16018. } = this;
  16019. const savedDisplay = div.style.display;
  16020. const savedVisibility = div.classList.contains("hidden");
  16021. div.classList.remove("hidden");
  16022. div.style.display = "hidden";
  16023. currentLayer.div.append(this.div);
  16024. rect = div.getBoundingClientRect();
  16025. div.remove();
  16026. div.style.display = savedDisplay;
  16027. div.classList.toggle("hidden", savedVisibility);
  16028. }
  16029. if (this.rotation % 180 === this.parentRotation % 180) {
  16030. this.width = rect.width / parentWidth;
  16031. this.height = rect.height / parentHeight;
  16032. } else {
  16033. this.width = rect.height / parentWidth;
  16034. this.height = rect.width / parentHeight;
  16035. }
  16036. this.fixAndSetPosition();
  16037. }
  16038. commit() {
  16039. if (!this.isInEditMode()) {
  16040. return;
  16041. }
  16042. super.commit();
  16043. this.disableEditMode();
  16044. const savedText = this.#content;
  16045. const newText = this.#content = this.#extractText().trimEnd();
  16046. if (savedText === newText) {
  16047. return;
  16048. }
  16049. const setText = text => {
  16050. this.#content = text;
  16051. if (!text) {
  16052. this.remove();
  16053. return;
  16054. }
  16055. this.#setContent();
  16056. this._uiManager.rebuild(this);
  16057. this.#setEditorDimensions();
  16058. };
  16059. this.addCommands({
  16060. cmd: () => {
  16061. setText(newText);
  16062. },
  16063. undo: () => {
  16064. setText(savedText);
  16065. },
  16066. mustExec: false
  16067. });
  16068. this.#setEditorDimensions();
  16069. }
  16070. shouldGetKeyboardEvents() {
  16071. return this.isInEditMode();
  16072. }
  16073. enterInEditMode() {
  16074. this.enableEditMode();
  16075. this.editorDiv.focus();
  16076. }
  16077. dblclick(event) {
  16078. this.enterInEditMode();
  16079. }
  16080. keydown(event) {
  16081. if (event.target === this.div && event.key === "Enter") {
  16082. this.enterInEditMode();
  16083. event.preventDefault();
  16084. }
  16085. }
  16086. editorDivKeydown(event) {
  16087. FreeTextEditor._keyboardManager.exec(this, event);
  16088. }
  16089. editorDivFocus(event) {
  16090. this.isEditing = true;
  16091. }
  16092. editorDivBlur(event) {
  16093. this.isEditing = false;
  16094. }
  16095. editorDivInput(event) {
  16096. this.parent.div.classList.toggle("freetextEditing", this.isEmpty());
  16097. }
  16098. disableEditing() {
  16099. this.editorDiv.setAttribute("role", "comment");
  16100. this.editorDiv.removeAttribute("aria-multiline");
  16101. }
  16102. enableEditing() {
  16103. this.editorDiv.setAttribute("role", "textbox");
  16104. this.editorDiv.setAttribute("aria-multiline", true);
  16105. }
  16106. render() {
  16107. if (this.div) {
  16108. return this.div;
  16109. }
  16110. let baseX, baseY;
  16111. if (this.width) {
  16112. baseX = this.x;
  16113. baseY = this.y;
  16114. }
  16115. super.render();
  16116. this.editorDiv = document.createElement("div");
  16117. this.editorDiv.className = "internal";
  16118. this.editorDiv.setAttribute("id", this.#editorDivId);
  16119. this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2");
  16120. this.editorDiv.setAttribute("data-l10n-attrs", "default-content");
  16121. this.enableEditing();
  16122. this.editorDiv.contentEditable = true;
  16123. const {
  16124. style
  16125. } = this.editorDiv;
  16126. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  16127. style.color = this.#color;
  16128. this.div.append(this.editorDiv);
  16129. this.overlayDiv = document.createElement("div");
  16130. this.overlayDiv.classList.add("overlay", "enabled");
  16131. this.div.append(this.overlayDiv);
  16132. bindEvents(this, this.div, ["dblclick", "keydown"]);
  16133. if (this.width) {
  16134. const [parentWidth, parentHeight] = this.parentDimensions;
  16135. if (this.annotationElementId) {
  16136. const {
  16137. position
  16138. } = this._initialData;
  16139. let [tx, ty] = this.getInitialTranslation();
  16140. [tx, ty] = this.pageTranslationToScreen(tx, ty);
  16141. const [pageWidth, pageHeight] = this.pageDimensions;
  16142. const [pageX, pageY] = this.pageTranslation;
  16143. let posX, posY;
  16144. switch (this.rotation) {
  16145. case 0:
  16146. posX = baseX + (position[0] - pageX) / pageWidth;
  16147. posY = baseY + this.height - (position[1] - pageY) / pageHeight;
  16148. break;
  16149. case 90:
  16150. posX = baseX + (position[0] - pageX) / pageWidth;
  16151. posY = baseY - (position[1] - pageY) / pageHeight;
  16152. [tx, ty] = [ty, -tx];
  16153. break;
  16154. case 180:
  16155. posX = baseX - this.width + (position[0] - pageX) / pageWidth;
  16156. posY = baseY - (position[1] - pageY) / pageHeight;
  16157. [tx, ty] = [-tx, -ty];
  16158. break;
  16159. case 270:
  16160. posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
  16161. posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
  16162. [tx, ty] = [-ty, tx];
  16163. break;
  16164. }
  16165. this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
  16166. } else {
  16167. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  16168. }
  16169. this.#setContent();
  16170. this._isDraggable = true;
  16171. this.editorDiv.contentEditable = false;
  16172. } else {
  16173. this._isDraggable = false;
  16174. this.editorDiv.contentEditable = true;
  16175. }
  16176. return this.div;
  16177. }
  16178. static #getNodeContent(node) {
  16179. return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
  16180. }
  16181. editorDivPaste(event) {
  16182. const clipboardData = event.clipboardData || window.clipboardData;
  16183. const {
  16184. types
  16185. } = clipboardData;
  16186. if (types.length === 1 && types[0] === "text/plain") {
  16187. return;
  16188. }
  16189. event.preventDefault();
  16190. const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
  16191. if (!paste) {
  16192. return;
  16193. }
  16194. const selection = window.getSelection();
  16195. if (!selection.rangeCount) {
  16196. return;
  16197. }
  16198. this.editorDiv.normalize();
  16199. selection.deleteFromDocument();
  16200. const range = selection.getRangeAt(0);
  16201. if (!paste.includes("\n")) {
  16202. range.insertNode(document.createTextNode(paste));
  16203. this.editorDiv.normalize();
  16204. selection.collapseToStart();
  16205. return;
  16206. }
  16207. const {
  16208. startContainer,
  16209. startOffset
  16210. } = range;
  16211. const bufferBefore = [];
  16212. const bufferAfter = [];
  16213. if (startContainer.nodeType === Node.TEXT_NODE) {
  16214. const parent = startContainer.parentElement;
  16215. bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
  16216. if (parent !== this.editorDiv) {
  16217. let buffer = bufferBefore;
  16218. for (const child of this.editorDiv.childNodes) {
  16219. if (child === parent) {
  16220. buffer = bufferAfter;
  16221. continue;
  16222. }
  16223. buffer.push(FreeTextEditor.#getNodeContent(child));
  16224. }
  16225. }
  16226. bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
  16227. } else if (startContainer === this.editorDiv) {
  16228. let buffer = bufferBefore;
  16229. let i = 0;
  16230. for (const child of this.editorDiv.childNodes) {
  16231. if (i++ === startOffset) {
  16232. buffer = bufferAfter;
  16233. }
  16234. buffer.push(FreeTextEditor.#getNodeContent(child));
  16235. }
  16236. }
  16237. this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
  16238. this.#setContent();
  16239. const newRange = new Range();
  16240. let beforeLength = bufferBefore.reduce((acc, line) => acc + line.length, 0);
  16241. for (const {
  16242. firstChild
  16243. } of this.editorDiv.childNodes) {
  16244. if (firstChild.nodeType === Node.TEXT_NODE) {
  16245. const length = firstChild.nodeValue.length;
  16246. if (beforeLength <= length) {
  16247. newRange.setStart(firstChild, beforeLength);
  16248. newRange.setEnd(firstChild, beforeLength);
  16249. break;
  16250. }
  16251. beforeLength -= length;
  16252. }
  16253. }
  16254. selection.removeAllRanges();
  16255. selection.addRange(newRange);
  16256. }
  16257. #setContent() {
  16258. this.editorDiv.replaceChildren();
  16259. if (!this.#content) {
  16260. return;
  16261. }
  16262. for (const line of this.#content.split("\n")) {
  16263. const div = document.createElement("div");
  16264. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  16265. this.editorDiv.append(div);
  16266. }
  16267. }
  16268. #serializeContent() {
  16269. return this.#content.replaceAll("\xa0", " ");
  16270. }
  16271. static #deserializeContent(content) {
  16272. return content.replaceAll(" ", "\xa0");
  16273. }
  16274. get contentDiv() {
  16275. return this.editorDiv;
  16276. }
  16277. static async deserialize(data, parent, uiManager) {
  16278. let initialData = null;
  16279. if (data instanceof FreeTextAnnotationElement) {
  16280. const {
  16281. data: {
  16282. defaultAppearanceData: {
  16283. fontSize,
  16284. fontColor
  16285. },
  16286. rect,
  16287. rotation,
  16288. id,
  16289. popupRef
  16290. },
  16291. textContent,
  16292. textPosition,
  16293. parent: {
  16294. page: {
  16295. pageNumber
  16296. }
  16297. }
  16298. } = data;
  16299. if (!textContent || textContent.length === 0) {
  16300. return null;
  16301. }
  16302. initialData = data = {
  16303. annotationType: AnnotationEditorType.FREETEXT,
  16304. color: Array.from(fontColor),
  16305. fontSize,
  16306. value: textContent.join("\n"),
  16307. position: textPosition,
  16308. pageIndex: pageNumber - 1,
  16309. rect: rect.slice(0),
  16310. rotation,
  16311. id,
  16312. deleted: false,
  16313. popupRef
  16314. };
  16315. }
  16316. const editor = await super.deserialize(data, parent, uiManager);
  16317. editor.#fontSize = data.fontSize;
  16318. editor.#color = Util.makeHexColor(...data.color);
  16319. editor.#content = FreeTextEditor.#deserializeContent(data.value);
  16320. editor.annotationElementId = data.id || null;
  16321. editor._initialData = initialData;
  16322. return editor;
  16323. }
  16324. serialize(isForCopying = false) {
  16325. if (this.isEmpty()) {
  16326. return null;
  16327. }
  16328. if (this.deleted) {
  16329. return this.serializeDeleted();
  16330. }
  16331. const padding = FreeTextEditor._internalPadding * this.parentScale;
  16332. const rect = this.getRect(padding, padding);
  16333. const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
  16334. const serialized = {
  16335. annotationType: AnnotationEditorType.FREETEXT,
  16336. color,
  16337. fontSize: this.#fontSize,
  16338. value: this.#serializeContent(),
  16339. pageIndex: this.pageIndex,
  16340. rect,
  16341. rotation: this.rotation,
  16342. structTreeParentId: this._structTreeParentId
  16343. };
  16344. if (isForCopying) {
  16345. return serialized;
  16346. }
  16347. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  16348. return null;
  16349. }
  16350. serialized.id = this.annotationElementId;
  16351. return serialized;
  16352. }
  16353. #hasElementChanged(serialized) {
  16354. const {
  16355. value,
  16356. fontSize,
  16357. color,
  16358. pageIndex
  16359. } = this._initialData;
  16360. return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;
  16361. }
  16362. renderAnnotationElement(annotation) {
  16363. const content = super.renderAnnotationElement(annotation);
  16364. if (this.deleted) {
  16365. return content;
  16366. }
  16367. const {
  16368. style
  16369. } = content;
  16370. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  16371. style.color = this.#color;
  16372. content.replaceChildren();
  16373. for (const line of this.#content.split("\n")) {
  16374. const div = document.createElement("div");
  16375. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  16376. content.append(div);
  16377. }
  16378. const padding = FreeTextEditor._internalPadding * this.parentScale;
  16379. annotation.updateEdited({
  16380. rect: this.getRect(padding, padding),
  16381. popupContent: this.#content
  16382. });
  16383. return content;
  16384. }
  16385. resetAnnotationElement(annotation) {
  16386. super.resetAnnotationElement(annotation);
  16387. annotation.resetEdited();
  16388. }
  16389. }
  16390. ;// ./src/display/editor/drawers/outline.js
  16391. class Outline {
  16392. toSVGPath() {
  16393. unreachable("Abstract method `toSVGPath` must be implemented.");
  16394. }
  16395. get box() {
  16396. unreachable("Abstract getter `box` must be implemented.");
  16397. }
  16398. serialize(_bbox, _rotation) {
  16399. unreachable("Abstract method `serialize` must be implemented.");
  16400. }
  16401. get classNamesForDrawing() {
  16402. unreachable("Abstract getter `classNamesForDrawing` must be implemented.");
  16403. }
  16404. get classNamesForOutlining() {
  16405. unreachable("Abstract getter `classNamesForOutlining` must be implemented.");
  16406. }
  16407. get mustRemoveSelfIntersections() {
  16408. return false;
  16409. }
  16410. }
  16411. ;// ./src/display/editor/drawers/freedraw.js
  16412. class FreeDrawOutliner {
  16413. #box;
  16414. #bottom = [];
  16415. #innerMargin;
  16416. #isLTR;
  16417. #top = [];
  16418. #last = new Float64Array(18);
  16419. #lastX;
  16420. #lastY;
  16421. #min;
  16422. #min_dist;
  16423. #scaleFactor;
  16424. #thickness;
  16425. #points = [];
  16426. static #MIN_DIST = 8;
  16427. static #MIN_DIFF = 2;
  16428. static #MIN = FreeDrawOutliner.#MIN_DIST + FreeDrawOutliner.#MIN_DIFF;
  16429. constructor({
  16430. x,
  16431. y
  16432. }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  16433. this.#box = box;
  16434. this.#thickness = thickness * scaleFactor;
  16435. this.#isLTR = isLTR;
  16436. this.#last.set([NaN, NaN, NaN, NaN, x, y], 6);
  16437. this.#innerMargin = innerMargin;
  16438. this.#min_dist = FreeDrawOutliner.#MIN_DIST * scaleFactor;
  16439. this.#min = FreeDrawOutliner.#MIN * scaleFactor;
  16440. this.#scaleFactor = scaleFactor;
  16441. this.#points.push(x, y);
  16442. }
  16443. isEmpty() {
  16444. return isNaN(this.#last[8]);
  16445. }
  16446. #getLastCoords() {
  16447. const lastTop = this.#last.subarray(4, 6);
  16448. const lastBottom = this.#last.subarray(16, 18);
  16449. const [x, y, width, height] = this.#box;
  16450. 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];
  16451. }
  16452. add({
  16453. x,
  16454. y
  16455. }) {
  16456. this.#lastX = x;
  16457. this.#lastY = y;
  16458. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16459. let [x1, y1, x2, y2] = this.#last.subarray(8, 12);
  16460. const diffX = x - x2;
  16461. const diffY = y - y2;
  16462. const d = Math.hypot(diffX, diffY);
  16463. if (d < this.#min) {
  16464. return false;
  16465. }
  16466. const diffD = d - this.#min_dist;
  16467. const K = diffD / d;
  16468. const shiftX = K * diffX;
  16469. const shiftY = K * diffY;
  16470. let x0 = x1;
  16471. let y0 = y1;
  16472. x1 = x2;
  16473. y1 = y2;
  16474. x2 += shiftX;
  16475. y2 += shiftY;
  16476. this.#points?.push(x, y);
  16477. const nX = -shiftY / diffD;
  16478. const nY = shiftX / diffD;
  16479. const thX = nX * this.#thickness;
  16480. const thY = nY * this.#thickness;
  16481. this.#last.set(this.#last.subarray(2, 8), 0);
  16482. this.#last.set([x2 + thX, y2 + thY], 4);
  16483. this.#last.set(this.#last.subarray(14, 18), 12);
  16484. this.#last.set([x2 - thX, y2 - thY], 16);
  16485. if (isNaN(this.#last[6])) {
  16486. if (this.#top.length === 0) {
  16487. this.#last.set([x1 + thX, y1 + thY], 2);
  16488. this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
  16489. this.#last.set([x1 - thX, y1 - thY], 14);
  16490. this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
  16491. }
  16492. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  16493. return !this.isEmpty();
  16494. }
  16495. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  16496. const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
  16497. if (angle < Math.PI / 2) {
  16498. [x1, y1, x2, y2] = this.#last.subarray(2, 6);
  16499. this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  16500. [x1, y1, x0, y0] = this.#last.subarray(14, 18);
  16501. this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
  16502. return true;
  16503. }
  16504. [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6);
  16505. 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);
  16506. [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18);
  16507. 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);
  16508. return true;
  16509. }
  16510. toSVGPath() {
  16511. if (this.isEmpty()) {
  16512. return "";
  16513. }
  16514. const top = this.#top;
  16515. const bottom = this.#bottom;
  16516. if (isNaN(this.#last[6]) && !this.isEmpty()) {
  16517. return this.#toSVGPathTwoPoints();
  16518. }
  16519. const buffer = [];
  16520. buffer.push(`M${top[4]} ${top[5]}`);
  16521. for (let i = 6; i < top.length; i += 6) {
  16522. if (isNaN(top[i])) {
  16523. buffer.push(`L${top[i + 4]} ${top[i + 5]}`);
  16524. } else {
  16525. buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`);
  16526. }
  16527. }
  16528. this.#toSVGPathEnd(buffer);
  16529. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  16530. if (isNaN(bottom[i])) {
  16531. buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`);
  16532. } else {
  16533. buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`);
  16534. }
  16535. }
  16536. this.#toSVGPathStart(buffer);
  16537. return buffer.join(" ");
  16538. }
  16539. #toSVGPathTwoPoints() {
  16540. const [x, y, width, height] = this.#box;
  16541. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16542. 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`;
  16543. }
  16544. #toSVGPathStart(buffer) {
  16545. const bottom = this.#bottom;
  16546. buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
  16547. }
  16548. #toSVGPathEnd(buffer) {
  16549. const [x, y, width, height] = this.#box;
  16550. const lastTop = this.#last.subarray(4, 6);
  16551. const lastBottom = this.#last.subarray(16, 18);
  16552. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16553. 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}`);
  16554. }
  16555. newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
  16556. return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  16557. }
  16558. getOutlines() {
  16559. const top = this.#top;
  16560. const bottom = this.#bottom;
  16561. const last = this.#last;
  16562. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16563. const points = new Float64Array((this.#points?.length ?? 0) + 2);
  16564. for (let i = 0, ii = points.length - 2; i < ii; i += 2) {
  16565. points[i] = (this.#points[i] - layerX) / layerWidth;
  16566. points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight;
  16567. }
  16568. points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
  16569. points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
  16570. if (isNaN(last[6]) && !this.isEmpty()) {
  16571. return this.#getOutlineTwoPoints(points);
  16572. }
  16573. const outline = new Float64Array(this.#top.length + 24 + this.#bottom.length);
  16574. let N = top.length;
  16575. for (let i = 0; i < N; i += 2) {
  16576. if (isNaN(top[i])) {
  16577. outline[i] = outline[i + 1] = NaN;
  16578. continue;
  16579. }
  16580. outline[i] = top[i];
  16581. outline[i + 1] = top[i + 1];
  16582. }
  16583. N = this.#getOutlineEnd(outline, N);
  16584. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  16585. for (let j = 0; j < 6; j += 2) {
  16586. if (isNaN(bottom[i + j])) {
  16587. outline[N] = outline[N + 1] = NaN;
  16588. N += 2;
  16589. continue;
  16590. }
  16591. outline[N] = bottom[i + j];
  16592. outline[N + 1] = bottom[i + j + 1];
  16593. N += 2;
  16594. }
  16595. }
  16596. this.#getOutlineStart(outline, N);
  16597. return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  16598. }
  16599. #getOutlineTwoPoints(points) {
  16600. const last = this.#last;
  16601. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16602. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16603. const outline = new Float64Array(36);
  16604. 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);
  16605. return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  16606. }
  16607. #getOutlineStart(outline, pos) {
  16608. const bottom = this.#bottom;
  16609. outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos);
  16610. return pos += 6;
  16611. }
  16612. #getOutlineEnd(outline, pos) {
  16613. const lastTop = this.#last.subarray(4, 6);
  16614. const lastBottom = this.#last.subarray(16, 18);
  16615. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16616. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16617. 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);
  16618. return pos += 24;
  16619. }
  16620. }
  16621. class FreeDrawOutline extends Outline {
  16622. #box;
  16623. #bbox = null;
  16624. #innerMargin;
  16625. #isLTR;
  16626. #points;
  16627. #scaleFactor;
  16628. #outline;
  16629. constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
  16630. super();
  16631. this.#outline = outline;
  16632. this.#points = points;
  16633. this.#box = box;
  16634. this.#scaleFactor = scaleFactor;
  16635. this.#innerMargin = innerMargin;
  16636. this.#isLTR = isLTR;
  16637. this.#computeMinMax(isLTR);
  16638. const {
  16639. x,
  16640. y,
  16641. width,
  16642. height
  16643. } = this.#bbox;
  16644. for (let i = 0, ii = outline.length; i < ii; i += 2) {
  16645. outline[i] = (outline[i] - x) / width;
  16646. outline[i + 1] = (outline[i + 1] - y) / height;
  16647. }
  16648. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16649. points[i] = (points[i] - x) / width;
  16650. points[i + 1] = (points[i + 1] - y) / height;
  16651. }
  16652. }
  16653. toSVGPath() {
  16654. const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
  16655. for (let i = 6, ii = this.#outline.length; i < ii; i += 6) {
  16656. if (isNaN(this.#outline[i])) {
  16657. buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
  16658. continue;
  16659. }
  16660. 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]}`);
  16661. }
  16662. buffer.push("Z");
  16663. return buffer.join(" ");
  16664. }
  16665. serialize([blX, blY, trX, trY], rotation) {
  16666. const width = trX - blX;
  16667. const height = trY - blY;
  16668. let outline;
  16669. let points;
  16670. switch (rotation) {
  16671. case 0:
  16672. outline = this.#rescale(this.#outline, blX, trY, width, -height);
  16673. points = this.#rescale(this.#points, blX, trY, width, -height);
  16674. break;
  16675. case 90:
  16676. outline = this.#rescaleAndSwap(this.#outline, blX, blY, width, height);
  16677. points = this.#rescaleAndSwap(this.#points, blX, blY, width, height);
  16678. break;
  16679. case 180:
  16680. outline = this.#rescale(this.#outline, trX, blY, -width, height);
  16681. points = this.#rescale(this.#points, trX, blY, -width, height);
  16682. break;
  16683. case 270:
  16684. outline = this.#rescaleAndSwap(this.#outline, trX, trY, -width, -height);
  16685. points = this.#rescaleAndSwap(this.#points, trX, trY, -width, -height);
  16686. break;
  16687. }
  16688. return {
  16689. outline: Array.from(outline),
  16690. points: [Array.from(points)]
  16691. };
  16692. }
  16693. #rescale(src, tx, ty, sx, sy) {
  16694. const dest = new Float64Array(src.length);
  16695. for (let i = 0, ii = src.length; i < ii; i += 2) {
  16696. dest[i] = tx + src[i] * sx;
  16697. dest[i + 1] = ty + src[i + 1] * sy;
  16698. }
  16699. return dest;
  16700. }
  16701. #rescaleAndSwap(src, tx, ty, sx, sy) {
  16702. const dest = new Float64Array(src.length);
  16703. for (let i = 0, ii = src.length; i < ii; i += 2) {
  16704. dest[i] = tx + src[i + 1] * sx;
  16705. dest[i + 1] = ty + src[i] * sy;
  16706. }
  16707. return dest;
  16708. }
  16709. #computeMinMax(isLTR) {
  16710. const outline = this.#outline;
  16711. let lastX = outline[4];
  16712. let lastY = outline[5];
  16713. let minX = lastX;
  16714. let minY = lastY;
  16715. let maxX = lastX;
  16716. let maxY = lastY;
  16717. let lastPointX = lastX;
  16718. let lastPointY = lastY;
  16719. const ltrCallback = isLTR ? Math.max : Math.min;
  16720. for (let i = 6, ii = outline.length; i < ii; i += 6) {
  16721. if (isNaN(outline[i])) {
  16722. minX = Math.min(minX, outline[i + 4]);
  16723. minY = Math.min(minY, outline[i + 5]);
  16724. maxX = Math.max(maxX, outline[i + 4]);
  16725. maxY = Math.max(maxY, outline[i + 5]);
  16726. if (lastPointY < outline[i + 5]) {
  16727. lastPointX = outline[i + 4];
  16728. lastPointY = outline[i + 5];
  16729. } else if (lastPointY === outline[i + 5]) {
  16730. lastPointX = ltrCallback(lastPointX, outline[i + 4]);
  16731. }
  16732. } else {
  16733. const bbox = Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6));
  16734. minX = Math.min(minX, bbox[0]);
  16735. minY = Math.min(minY, bbox[1]);
  16736. maxX = Math.max(maxX, bbox[2]);
  16737. maxY = Math.max(maxY, bbox[3]);
  16738. if (lastPointY < bbox[3]) {
  16739. lastPointX = bbox[2];
  16740. lastPointY = bbox[3];
  16741. } else if (lastPointY === bbox[3]) {
  16742. lastPointX = ltrCallback(lastPointX, bbox[2]);
  16743. }
  16744. }
  16745. lastX = outline[i + 4];
  16746. lastY = outline[i + 5];
  16747. }
  16748. const x = minX - this.#innerMargin,
  16749. y = minY - this.#innerMargin,
  16750. width = maxX - minX + 2 * this.#innerMargin,
  16751. height = maxY - minY + 2 * this.#innerMargin;
  16752. this.#bbox = {
  16753. x,
  16754. y,
  16755. width,
  16756. height,
  16757. lastPoint: [lastPointX, lastPointY]
  16758. };
  16759. }
  16760. get box() {
  16761. return this.#bbox;
  16762. }
  16763. newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  16764. return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  16765. }
  16766. getNewOutline(thickness, innerMargin) {
  16767. const {
  16768. x,
  16769. y,
  16770. width,
  16771. height
  16772. } = this.#bbox;
  16773. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16774. const sx = width * layerWidth;
  16775. const sy = height * layerHeight;
  16776. const tx = x * layerWidth + layerX;
  16777. const ty = y * layerHeight + layerY;
  16778. const outliner = this.newOutliner({
  16779. x: this.#points[0] * sx + tx,
  16780. y: this.#points[1] * sy + ty
  16781. }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
  16782. for (let i = 2; i < this.#points.length; i += 2) {
  16783. outliner.add({
  16784. x: this.#points[i] * sx + tx,
  16785. y: this.#points[i + 1] * sy + ty
  16786. });
  16787. }
  16788. return outliner.getOutlines();
  16789. }
  16790. get mustRemoveSelfIntersections() {
  16791. return true;
  16792. }
  16793. }
  16794. ;// ./src/display/editor/drawers/highlight.js
  16795. class HighlightOutliner {
  16796. #box;
  16797. #verticalEdges = [];
  16798. #intervals = [];
  16799. constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
  16800. let minX = Infinity;
  16801. let maxX = -Infinity;
  16802. let minY = Infinity;
  16803. let maxY = -Infinity;
  16804. const NUMBER_OF_DIGITS = 4;
  16805. const EPSILON = 10 ** -NUMBER_OF_DIGITS;
  16806. for (const {
  16807. x,
  16808. y,
  16809. width,
  16810. height
  16811. } of boxes) {
  16812. const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON;
  16813. const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON;
  16814. const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON;
  16815. const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON;
  16816. const left = [x1, y1, y2, true];
  16817. const right = [x2, y1, y2, false];
  16818. this.#verticalEdges.push(left, right);
  16819. minX = Math.min(minX, x1);
  16820. maxX = Math.max(maxX, x2);
  16821. minY = Math.min(minY, y1);
  16822. maxY = Math.max(maxY, y2);
  16823. }
  16824. const bboxWidth = maxX - minX + 2 * innerMargin;
  16825. const bboxHeight = maxY - minY + 2 * innerMargin;
  16826. const shiftedMinX = minX - innerMargin;
  16827. const shiftedMinY = minY - innerMargin;
  16828. const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
  16829. const lastPoint = [lastEdge[0], lastEdge[2]];
  16830. for (const edge of this.#verticalEdges) {
  16831. const [x, y1, y2] = edge;
  16832. edge[0] = (x - shiftedMinX) / bboxWidth;
  16833. edge[1] = (y1 - shiftedMinY) / bboxHeight;
  16834. edge[2] = (y2 - shiftedMinY) / bboxHeight;
  16835. }
  16836. this.#box = {
  16837. x: shiftedMinX,
  16838. y: shiftedMinY,
  16839. width: bboxWidth,
  16840. height: bboxHeight,
  16841. lastPoint
  16842. };
  16843. }
  16844. getOutlines() {
  16845. this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
  16846. const outlineVerticalEdges = [];
  16847. for (const edge of this.#verticalEdges) {
  16848. if (edge[3]) {
  16849. outlineVerticalEdges.push(...this.#breakEdge(edge));
  16850. this.#insert(edge);
  16851. } else {
  16852. this.#remove(edge);
  16853. outlineVerticalEdges.push(...this.#breakEdge(edge));
  16854. }
  16855. }
  16856. return this.#getOutlines(outlineVerticalEdges);
  16857. }
  16858. #getOutlines(outlineVerticalEdges) {
  16859. const edges = [];
  16860. const allEdges = new Set();
  16861. for (const edge of outlineVerticalEdges) {
  16862. const [x, y1, y2] = edge;
  16863. edges.push([x, y1, edge], [x, y2, edge]);
  16864. }
  16865. edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
  16866. for (let i = 0, ii = edges.length; i < ii; i += 2) {
  16867. const edge1 = edges[i][2];
  16868. const edge2 = edges[i + 1][2];
  16869. edge1.push(edge2);
  16870. edge2.push(edge1);
  16871. allEdges.add(edge1);
  16872. allEdges.add(edge2);
  16873. }
  16874. const outlines = [];
  16875. let outline;
  16876. while (allEdges.size > 0) {
  16877. const edge = allEdges.values().next().value;
  16878. let [x, y1, y2, edge1, edge2] = edge;
  16879. allEdges.delete(edge);
  16880. let lastPointX = x;
  16881. let lastPointY = y1;
  16882. outline = [x, y2];
  16883. outlines.push(outline);
  16884. while (true) {
  16885. let e;
  16886. if (allEdges.has(edge1)) {
  16887. e = edge1;
  16888. } else if (allEdges.has(edge2)) {
  16889. e = edge2;
  16890. } else {
  16891. break;
  16892. }
  16893. allEdges.delete(e);
  16894. [x, y1, y2, edge1, edge2] = e;
  16895. if (lastPointX !== x) {
  16896. outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2);
  16897. lastPointX = x;
  16898. }
  16899. lastPointY = lastPointY === y1 ? y2 : y1;
  16900. }
  16901. outline.push(lastPointX, lastPointY);
  16902. }
  16903. return new HighlightOutline(outlines, this.#box);
  16904. }
  16905. #binarySearch(y) {
  16906. const array = this.#intervals;
  16907. let start = 0;
  16908. let end = array.length - 1;
  16909. while (start <= end) {
  16910. const middle = start + end >> 1;
  16911. const y1 = array[middle][0];
  16912. if (y1 === y) {
  16913. return middle;
  16914. }
  16915. if (y1 < y) {
  16916. start = middle + 1;
  16917. } else {
  16918. end = middle - 1;
  16919. }
  16920. }
  16921. return end + 1;
  16922. }
  16923. #insert([, y1, y2]) {
  16924. const index = this.#binarySearch(y1);
  16925. this.#intervals.splice(index, 0, [y1, y2]);
  16926. }
  16927. #remove([, y1, y2]) {
  16928. const index = this.#binarySearch(y1);
  16929. for (let i = index; i < this.#intervals.length; i++) {
  16930. const [start, end] = this.#intervals[i];
  16931. if (start !== y1) {
  16932. break;
  16933. }
  16934. if (start === y1 && end === y2) {
  16935. this.#intervals.splice(i, 1);
  16936. return;
  16937. }
  16938. }
  16939. for (let i = index - 1; i >= 0; i--) {
  16940. const [start, end] = this.#intervals[i];
  16941. if (start !== y1) {
  16942. break;
  16943. }
  16944. if (start === y1 && end === y2) {
  16945. this.#intervals.splice(i, 1);
  16946. return;
  16947. }
  16948. }
  16949. }
  16950. #breakEdge(edge) {
  16951. const [x, y1, y2] = edge;
  16952. const results = [[x, y1, y2]];
  16953. const index = this.#binarySearch(y2);
  16954. for (let i = 0; i < index; i++) {
  16955. const [start, end] = this.#intervals[i];
  16956. for (let j = 0, jj = results.length; j < jj; j++) {
  16957. const [, y3, y4] = results[j];
  16958. if (end <= y3 || y4 <= start) {
  16959. continue;
  16960. }
  16961. if (y3 >= start) {
  16962. if (y4 > end) {
  16963. results[j][1] = end;
  16964. } else {
  16965. if (jj === 1) {
  16966. return [];
  16967. }
  16968. results.splice(j, 1);
  16969. j--;
  16970. jj--;
  16971. }
  16972. continue;
  16973. }
  16974. results[j][2] = start;
  16975. if (y4 > end) {
  16976. results.push([x, end, y4]);
  16977. }
  16978. }
  16979. }
  16980. return results;
  16981. }
  16982. }
  16983. class HighlightOutline extends Outline {
  16984. #box;
  16985. #outlines;
  16986. constructor(outlines, box) {
  16987. super();
  16988. this.#outlines = outlines;
  16989. this.#box = box;
  16990. }
  16991. toSVGPath() {
  16992. const buffer = [];
  16993. for (const polygon of this.#outlines) {
  16994. let [prevX, prevY] = polygon;
  16995. buffer.push(`M${prevX} ${prevY}`);
  16996. for (let i = 2; i < polygon.length; i += 2) {
  16997. const x = polygon[i];
  16998. const y = polygon[i + 1];
  16999. if (x === prevX) {
  17000. buffer.push(`V${y}`);
  17001. prevY = y;
  17002. } else if (y === prevY) {
  17003. buffer.push(`H${x}`);
  17004. prevX = x;
  17005. }
  17006. }
  17007. buffer.push("Z");
  17008. }
  17009. return buffer.join(" ");
  17010. }
  17011. serialize([blX, blY, trX, trY], _rotation) {
  17012. const outlines = [];
  17013. const width = trX - blX;
  17014. const height = trY - blY;
  17015. for (const outline of this.#outlines) {
  17016. const points = new Array(outline.length);
  17017. for (let i = 0; i < outline.length; i += 2) {
  17018. points[i] = blX + outline[i] * width;
  17019. points[i + 1] = trY - outline[i + 1] * height;
  17020. }
  17021. outlines.push(points);
  17022. }
  17023. return outlines;
  17024. }
  17025. get box() {
  17026. return this.#box;
  17027. }
  17028. get classNamesForDrawing() {
  17029. return ["highlight"];
  17030. }
  17031. get classNamesForOutlining() {
  17032. return ["highlightOutline"];
  17033. }
  17034. }
  17035. class FreeHighlightOutliner extends FreeDrawOutliner {
  17036. newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
  17037. return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  17038. }
  17039. get classNamesForDrawing() {
  17040. return ["highlight", "free"];
  17041. }
  17042. }
  17043. class FreeHighlightOutline extends FreeDrawOutline {
  17044. get classNamesForDrawing() {
  17045. return ["highlight", "free"];
  17046. }
  17047. get classNamesForOutlining() {
  17048. return ["highlightOutline", "free"];
  17049. }
  17050. newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  17051. return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  17052. }
  17053. }
  17054. ;// ./src/display/editor/color_picker.js
  17055. class ColorPicker {
  17056. #button = null;
  17057. #buttonSwatch = null;
  17058. #defaultColor;
  17059. #dropdown = null;
  17060. #dropdownWasFromKeyboard = false;
  17061. #isMainColorPicker = false;
  17062. #editor = null;
  17063. #eventBus;
  17064. #openDropdownAC = null;
  17065. #uiManager = null;
  17066. #type;
  17067. static #l10nColor = null;
  17068. static get _keyboardManager() {
  17069. 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]]));
  17070. }
  17071. constructor({
  17072. editor = null,
  17073. uiManager = null
  17074. }) {
  17075. if (editor) {
  17076. this.#isMainColorPicker = false;
  17077. this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR;
  17078. this.#editor = editor;
  17079. } else {
  17080. this.#isMainColorPicker = true;
  17081. this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR;
  17082. }
  17083. this.#uiManager = editor?._uiManager || uiManager;
  17084. this.#eventBus = this.#uiManager._eventBus;
  17085. this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
  17086. ColorPicker.#l10nColor ||= Object.freeze({
  17087. blue: "pdfjs-editor-colorpicker-blue",
  17088. green: "pdfjs-editor-colorpicker-green",
  17089. pink: "pdfjs-editor-colorpicker-pink",
  17090. red: "pdfjs-editor-colorpicker-red",
  17091. yellow: "pdfjs-editor-colorpicker-yellow"
  17092. });
  17093. }
  17094. renderButton() {
  17095. const button = this.#button = document.createElement("button");
  17096. button.className = "colorPicker";
  17097. button.tabIndex = "0";
  17098. button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
  17099. button.setAttribute("aria-haspopup", true);
  17100. const signal = this.#uiManager._signal;
  17101. button.addEventListener("click", this.#openDropdown.bind(this), {
  17102. signal
  17103. });
  17104. button.addEventListener("keydown", this.#keyDown.bind(this), {
  17105. signal
  17106. });
  17107. const swatch = this.#buttonSwatch = document.createElement("span");
  17108. swatch.className = "swatch";
  17109. swatch.setAttribute("aria-hidden", true);
  17110. swatch.style.backgroundColor = this.#defaultColor;
  17111. button.append(swatch);
  17112. return button;
  17113. }
  17114. renderMainDropdown() {
  17115. const dropdown = this.#dropdown = this.#getDropdownRoot();
  17116. dropdown.setAttribute("aria-orientation", "horizontal");
  17117. dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel");
  17118. return dropdown;
  17119. }
  17120. #getDropdownRoot() {
  17121. const div = document.createElement("div");
  17122. const signal = this.#uiManager._signal;
  17123. div.addEventListener("contextmenu", noContextMenu, {
  17124. signal
  17125. });
  17126. div.className = "dropdown";
  17127. div.role = "listbox";
  17128. div.setAttribute("aria-multiselectable", false);
  17129. div.setAttribute("aria-orientation", "vertical");
  17130. div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
  17131. for (const [name, color] of this.#uiManager.highlightColors) {
  17132. const button = document.createElement("button");
  17133. button.tabIndex = "0";
  17134. button.role = "option";
  17135. button.setAttribute("data-color", color);
  17136. button.title = name;
  17137. button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]);
  17138. const swatch = document.createElement("span");
  17139. button.append(swatch);
  17140. swatch.className = "swatch";
  17141. swatch.style.backgroundColor = color;
  17142. button.setAttribute("aria-selected", color === this.#defaultColor);
  17143. button.addEventListener("click", this.#colorSelect.bind(this, color), {
  17144. signal
  17145. });
  17146. div.append(button);
  17147. }
  17148. div.addEventListener("keydown", this.#keyDown.bind(this), {
  17149. signal
  17150. });
  17151. return div;
  17152. }
  17153. #colorSelect(color, event) {
  17154. event.stopPropagation();
  17155. this.#eventBus.dispatch("switchannotationeditorparams", {
  17156. source: this,
  17157. type: this.#type,
  17158. value: color
  17159. });
  17160. }
  17161. _colorSelectFromKeyboard(event) {
  17162. if (event.target === this.#button) {
  17163. this.#openDropdown(event);
  17164. return;
  17165. }
  17166. const color = event.target.getAttribute("data-color");
  17167. if (!color) {
  17168. return;
  17169. }
  17170. this.#colorSelect(color, event);
  17171. }
  17172. _moveToNext(event) {
  17173. if (!this.#isDropdownVisible) {
  17174. this.#openDropdown(event);
  17175. return;
  17176. }
  17177. if (event.target === this.#button) {
  17178. this.#dropdown.firstChild?.focus();
  17179. return;
  17180. }
  17181. event.target.nextSibling?.focus();
  17182. }
  17183. _moveToPrevious(event) {
  17184. if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
  17185. if (this.#isDropdownVisible) {
  17186. this._hideDropdownFromKeyboard();
  17187. }
  17188. return;
  17189. }
  17190. if (!this.#isDropdownVisible) {
  17191. this.#openDropdown(event);
  17192. }
  17193. event.target.previousSibling?.focus();
  17194. }
  17195. _moveToBeginning(event) {
  17196. if (!this.#isDropdownVisible) {
  17197. this.#openDropdown(event);
  17198. return;
  17199. }
  17200. this.#dropdown.firstChild?.focus();
  17201. }
  17202. _moveToEnd(event) {
  17203. if (!this.#isDropdownVisible) {
  17204. this.#openDropdown(event);
  17205. return;
  17206. }
  17207. this.#dropdown.lastChild?.focus();
  17208. }
  17209. #keyDown(event) {
  17210. ColorPicker._keyboardManager.exec(this, event);
  17211. }
  17212. #openDropdown(event) {
  17213. if (this.#isDropdownVisible) {
  17214. this.hideDropdown();
  17215. return;
  17216. }
  17217. this.#dropdownWasFromKeyboard = event.detail === 0;
  17218. if (!this.#openDropdownAC) {
  17219. this.#openDropdownAC = new AbortController();
  17220. window.addEventListener("pointerdown", this.#pointerDown.bind(this), {
  17221. signal: this.#uiManager.combinedSignal(this.#openDropdownAC)
  17222. });
  17223. }
  17224. if (this.#dropdown) {
  17225. this.#dropdown.classList.remove("hidden");
  17226. return;
  17227. }
  17228. const root = this.#dropdown = this.#getDropdownRoot();
  17229. this.#button.append(root);
  17230. }
  17231. #pointerDown(event) {
  17232. if (this.#dropdown?.contains(event.target)) {
  17233. return;
  17234. }
  17235. this.hideDropdown();
  17236. }
  17237. hideDropdown() {
  17238. this.#dropdown?.classList.add("hidden");
  17239. this.#openDropdownAC?.abort();
  17240. this.#openDropdownAC = null;
  17241. }
  17242. get #isDropdownVisible() {
  17243. return this.#dropdown && !this.#dropdown.classList.contains("hidden");
  17244. }
  17245. _hideDropdownFromKeyboard() {
  17246. if (this.#isMainColorPicker) {
  17247. return;
  17248. }
  17249. if (!this.#isDropdownVisible) {
  17250. this.#editor?.unselect();
  17251. return;
  17252. }
  17253. this.hideDropdown();
  17254. this.#button.focus({
  17255. preventScroll: true,
  17256. focusVisible: this.#dropdownWasFromKeyboard
  17257. });
  17258. }
  17259. updateColor(color) {
  17260. if (this.#buttonSwatch) {
  17261. this.#buttonSwatch.style.backgroundColor = color;
  17262. }
  17263. if (!this.#dropdown) {
  17264. return;
  17265. }
  17266. const i = this.#uiManager.highlightColors.values();
  17267. for (const child of this.#dropdown.children) {
  17268. child.setAttribute("aria-selected", i.next().value === color);
  17269. }
  17270. }
  17271. destroy() {
  17272. this.#button?.remove();
  17273. this.#button = null;
  17274. this.#buttonSwatch = null;
  17275. this.#dropdown?.remove();
  17276. this.#dropdown = null;
  17277. }
  17278. }
  17279. ;// ./src/display/editor/highlight.js
  17280. class HighlightEditor extends AnnotationEditor {
  17281. #anchorNode = null;
  17282. #anchorOffset = 0;
  17283. #boxes;
  17284. #clipPathId = null;
  17285. #colorPicker = null;
  17286. #focusOutlines = null;
  17287. #focusNode = null;
  17288. #focusOffset = 0;
  17289. #highlightDiv = null;
  17290. #highlightOutlines = null;
  17291. #id = null;
  17292. #isFreeHighlight = false;
  17293. #lastPoint = null;
  17294. #opacity;
  17295. #outlineId = null;
  17296. #text = "";
  17297. #thickness;
  17298. #methodOfCreation = "";
  17299. static _defaultColor = null;
  17300. static _defaultOpacity = 1;
  17301. static _defaultThickness = 12;
  17302. static _type = "highlight";
  17303. static _editorType = AnnotationEditorType.HIGHLIGHT;
  17304. static _freeHighlightId = -1;
  17305. static _freeHighlight = null;
  17306. static _freeHighlightClipId = "";
  17307. static get _keyboardManager() {
  17308. const proto = HighlightEditor.prototype;
  17309. return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
  17310. args: [0]
  17311. }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
  17312. args: [1]
  17313. }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
  17314. args: [2]
  17315. }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
  17316. args: [3]
  17317. }]]));
  17318. }
  17319. constructor(params) {
  17320. super({
  17321. ...params,
  17322. name: "highlightEditor"
  17323. });
  17324. this.color = params.color || HighlightEditor._defaultColor;
  17325. this.#thickness = params.thickness || HighlightEditor._defaultThickness;
  17326. this.#opacity = params.opacity || HighlightEditor._defaultOpacity;
  17327. this.#boxes = params.boxes || null;
  17328. this.#methodOfCreation = params.methodOfCreation || "";
  17329. this.#text = params.text || "";
  17330. this._isDraggable = false;
  17331. if (params.highlightId > -1) {
  17332. this.#isFreeHighlight = true;
  17333. this.#createFreeOutlines(params);
  17334. this.#addToDrawLayer();
  17335. } else if (this.#boxes) {
  17336. this.#anchorNode = params.anchorNode;
  17337. this.#anchorOffset = params.anchorOffset;
  17338. this.#focusNode = params.focusNode;
  17339. this.#focusOffset = params.focusOffset;
  17340. this.#createOutlines();
  17341. this.#addToDrawLayer();
  17342. this.rotate(this.rotation);
  17343. }
  17344. }
  17345. get telemetryInitialData() {
  17346. return {
  17347. action: "added",
  17348. type: this.#isFreeHighlight ? "free_highlight" : "highlight",
  17349. color: this._uiManager.highlightColorNames.get(this.color),
  17350. thickness: this.#thickness,
  17351. methodOfCreation: this.#methodOfCreation
  17352. };
  17353. }
  17354. get telemetryFinalData() {
  17355. return {
  17356. type: "highlight",
  17357. color: this._uiManager.highlightColorNames.get(this.color)
  17358. };
  17359. }
  17360. static computeTelemetryFinalData(data) {
  17361. return {
  17362. numberOfColors: data.get("color").size
  17363. };
  17364. }
  17365. #createOutlines() {
  17366. const outliner = new HighlightOutliner(this.#boxes, 0.001);
  17367. this.#highlightOutlines = outliner.getOutlines();
  17368. ({
  17369. x: this.x,
  17370. y: this.y,
  17371. width: this.width,
  17372. height: this.height
  17373. } = this.#highlightOutlines.box);
  17374. const outlinerForOutline = new HighlightOutliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr");
  17375. this.#focusOutlines = outlinerForOutline.getOutlines();
  17376. const {
  17377. lastPoint
  17378. } = this.#focusOutlines.box;
  17379. this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
  17380. }
  17381. #createFreeOutlines({
  17382. highlightOutlines,
  17383. highlightId,
  17384. clipPathId
  17385. }) {
  17386. this.#highlightOutlines = highlightOutlines;
  17387. const extraThickness = 1.5;
  17388. this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025);
  17389. if (highlightId >= 0) {
  17390. this.#id = highlightId;
  17391. this.#clipPathId = clipPathId;
  17392. this.parent.drawLayer.finalizeLine(highlightId, highlightOutlines);
  17393. this.#outlineId = this.parent.drawLayer.drawOutline(this.#focusOutlines);
  17394. } else if (this.parent) {
  17395. const angle = this.parent.viewport.rotation;
  17396. this.parent.drawLayer.updateLine(this.#id, highlightOutlines);
  17397. this.parent.drawLayer.updateBox(this.#id, HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360));
  17398. this.parent.drawLayer.updateLine(this.#outlineId, this.#focusOutlines);
  17399. this.parent.drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
  17400. }
  17401. const {
  17402. x,
  17403. y,
  17404. width,
  17405. height
  17406. } = highlightOutlines.box;
  17407. switch (this.rotation) {
  17408. case 0:
  17409. this.x = x;
  17410. this.y = y;
  17411. this.width = width;
  17412. this.height = height;
  17413. break;
  17414. case 90:
  17415. {
  17416. const [pageWidth, pageHeight] = this.parentDimensions;
  17417. this.x = y;
  17418. this.y = 1 - x;
  17419. this.width = width * pageHeight / pageWidth;
  17420. this.height = height * pageWidth / pageHeight;
  17421. break;
  17422. }
  17423. case 180:
  17424. this.x = 1 - x;
  17425. this.y = 1 - y;
  17426. this.width = width;
  17427. this.height = height;
  17428. break;
  17429. case 270:
  17430. {
  17431. const [pageWidth, pageHeight] = this.parentDimensions;
  17432. this.x = 1 - y;
  17433. this.y = x;
  17434. this.width = width * pageHeight / pageWidth;
  17435. this.height = height * pageWidth / pageHeight;
  17436. break;
  17437. }
  17438. }
  17439. const {
  17440. lastPoint
  17441. } = this.#focusOutlines.box;
  17442. this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height];
  17443. }
  17444. static initialize(l10n, uiManager) {
  17445. AnnotationEditor.initialize(l10n, uiManager);
  17446. HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
  17447. }
  17448. static updateDefaultParams(type, value) {
  17449. switch (type) {
  17450. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  17451. HighlightEditor._defaultColor = value;
  17452. break;
  17453. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  17454. HighlightEditor._defaultThickness = value;
  17455. break;
  17456. }
  17457. }
  17458. translateInPage(x, y) {}
  17459. get toolbarPosition() {
  17460. return this.#lastPoint;
  17461. }
  17462. updateParams(type, value) {
  17463. switch (type) {
  17464. case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
  17465. this.#updateColor(value);
  17466. break;
  17467. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  17468. this.#updateThickness(value);
  17469. break;
  17470. }
  17471. }
  17472. static get defaultPropertiesToUpdate() {
  17473. return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]];
  17474. }
  17475. get propertiesToUpdate() {
  17476. return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
  17477. }
  17478. #updateColor(color) {
  17479. const setColorAndOpacity = (col, opa) => {
  17480. this.color = col;
  17481. this.parent?.drawLayer.changeColor(this.#id, col);
  17482. this.#colorPicker?.updateColor(col);
  17483. this.#opacity = opa;
  17484. this.parent?.drawLayer.changeOpacity(this.#id, opa);
  17485. };
  17486. const savedColor = this.color;
  17487. const savedOpacity = this.#opacity;
  17488. this.addCommands({
  17489. cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity),
  17490. undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),
  17491. post: this._uiManager.updateUI.bind(this._uiManager, this),
  17492. mustExec: true,
  17493. type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
  17494. overwriteIfSameType: true,
  17495. keepUndo: true
  17496. });
  17497. this._reportTelemetry({
  17498. action: "color_changed",
  17499. color: this._uiManager.highlightColorNames.get(color)
  17500. }, true);
  17501. }
  17502. #updateThickness(thickness) {
  17503. const savedThickness = this.#thickness;
  17504. const setThickness = th => {
  17505. this.#thickness = th;
  17506. this.#changeThickness(th);
  17507. };
  17508. this.addCommands({
  17509. cmd: setThickness.bind(this, thickness),
  17510. undo: setThickness.bind(this, savedThickness),
  17511. post: this._uiManager.updateUI.bind(this._uiManager, this),
  17512. mustExec: true,
  17513. type: AnnotationEditorParamsType.INK_THICKNESS,
  17514. overwriteIfSameType: true,
  17515. keepUndo: true
  17516. });
  17517. this._reportTelemetry({
  17518. action: "thickness_changed",
  17519. thickness
  17520. }, true);
  17521. }
  17522. async addEditToolbar() {
  17523. const toolbar = await super.addEditToolbar();
  17524. if (!toolbar) {
  17525. return null;
  17526. }
  17527. if (this._uiManager.highlightColors) {
  17528. this.#colorPicker = new ColorPicker({
  17529. editor: this
  17530. });
  17531. toolbar.addColorPicker(this.#colorPicker);
  17532. }
  17533. return toolbar;
  17534. }
  17535. disableEditing() {
  17536. super.disableEditing();
  17537. this.div.classList.toggle("disabled", true);
  17538. }
  17539. enableEditing() {
  17540. super.enableEditing();
  17541. this.div.classList.toggle("disabled", false);
  17542. }
  17543. fixAndSetPosition() {
  17544. return super.fixAndSetPosition(this.#getRotation());
  17545. }
  17546. getBaseTranslation() {
  17547. return [0, 0];
  17548. }
  17549. getRect(tx, ty) {
  17550. return super.getRect(tx, ty, this.#getRotation());
  17551. }
  17552. onceAdded() {
  17553. if (!this.annotationElementId) {
  17554. this.parent.addUndoableEditor(this);
  17555. }
  17556. this.div.focus();
  17557. }
  17558. remove() {
  17559. this.#cleanDrawLayer();
  17560. this._reportTelemetry({
  17561. action: "deleted"
  17562. });
  17563. super.remove();
  17564. }
  17565. rebuild() {
  17566. if (!this.parent) {
  17567. return;
  17568. }
  17569. super.rebuild();
  17570. if (this.div === null) {
  17571. return;
  17572. }
  17573. this.#addToDrawLayer();
  17574. if (!this.isAttachedToDOM) {
  17575. this.parent.add(this);
  17576. }
  17577. }
  17578. setParent(parent) {
  17579. let mustBeSelected = false;
  17580. if (this.parent && !parent) {
  17581. this.#cleanDrawLayer();
  17582. } else if (parent) {
  17583. this.#addToDrawLayer(parent);
  17584. mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
  17585. }
  17586. super.setParent(parent);
  17587. this.show(this._isVisible);
  17588. if (mustBeSelected) {
  17589. this.select();
  17590. }
  17591. }
  17592. #changeThickness(thickness) {
  17593. if (!this.#isFreeHighlight) {
  17594. return;
  17595. }
  17596. this.#createFreeOutlines({
  17597. highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
  17598. });
  17599. this.fixAndSetPosition();
  17600. const [parentWidth, parentHeight] = this.parentDimensions;
  17601. this.setDims(this.width * parentWidth, this.height * parentHeight);
  17602. }
  17603. #cleanDrawLayer() {
  17604. if (this.#id === null || !this.parent) {
  17605. return;
  17606. }
  17607. this.parent.drawLayer.remove(this.#id);
  17608. this.#id = null;
  17609. this.parent.drawLayer.remove(this.#outlineId);
  17610. this.#outlineId = null;
  17611. }
  17612. #addToDrawLayer(parent = this.parent) {
  17613. if (this.#id !== null) {
  17614. return;
  17615. }
  17616. ({
  17617. id: this.#id,
  17618. clipPathId: this.#clipPathId
  17619. } = parent.drawLayer.draw(this.#highlightOutlines, this.color, this.#opacity));
  17620. this.#outlineId = parent.drawLayer.drawOutline(this.#focusOutlines);
  17621. if (this.#highlightDiv) {
  17622. this.#highlightDiv.style.clipPath = this.#clipPathId;
  17623. }
  17624. }
  17625. static #rotateBbox({
  17626. x,
  17627. y,
  17628. width,
  17629. height
  17630. }, angle) {
  17631. switch (angle) {
  17632. case 90:
  17633. return {
  17634. x: 1 - y - height,
  17635. y: x,
  17636. width: height,
  17637. height: width
  17638. };
  17639. case 180:
  17640. return {
  17641. x: 1 - x - width,
  17642. y: 1 - y - height,
  17643. width,
  17644. height
  17645. };
  17646. case 270:
  17647. return {
  17648. x: y,
  17649. y: 1 - x - width,
  17650. width: height,
  17651. height: width
  17652. };
  17653. }
  17654. return {
  17655. x,
  17656. y,
  17657. width,
  17658. height
  17659. };
  17660. }
  17661. rotate(angle) {
  17662. const {
  17663. drawLayer
  17664. } = this.parent;
  17665. let box;
  17666. if (this.#isFreeHighlight) {
  17667. angle = (angle - this.rotation + 360) % 360;
  17668. box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
  17669. } else {
  17670. box = HighlightEditor.#rotateBbox(this, angle);
  17671. }
  17672. drawLayer.rotate(this.#id, angle);
  17673. drawLayer.rotate(this.#outlineId, angle);
  17674. drawLayer.updateBox(this.#id, box);
  17675. drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
  17676. }
  17677. render() {
  17678. if (this.div) {
  17679. return this.div;
  17680. }
  17681. const div = super.render();
  17682. if (this.#text) {
  17683. div.setAttribute("aria-label", this.#text);
  17684. div.setAttribute("role", "mark");
  17685. }
  17686. if (this.#isFreeHighlight) {
  17687. div.classList.add("free");
  17688. } else {
  17689. this.div.addEventListener("keydown", this.#keydown.bind(this), {
  17690. signal: this._uiManager._signal
  17691. });
  17692. }
  17693. const highlightDiv = this.#highlightDiv = document.createElement("div");
  17694. div.append(highlightDiv);
  17695. highlightDiv.setAttribute("aria-hidden", "true");
  17696. highlightDiv.className = "internal";
  17697. highlightDiv.style.clipPath = this.#clipPathId;
  17698. const [parentWidth, parentHeight] = this.parentDimensions;
  17699. this.setDims(this.width * parentWidth, this.height * parentHeight);
  17700. bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
  17701. this.enableEditing();
  17702. return div;
  17703. }
  17704. pointerover() {
  17705. if (!this.isSelected) {
  17706. this.parent.drawLayer.addClass(this.#outlineId, "hovered");
  17707. }
  17708. }
  17709. pointerleave() {
  17710. if (!this.isSelected) {
  17711. this.parent.drawLayer.removeClass(this.#outlineId, "hovered");
  17712. }
  17713. }
  17714. #keydown(event) {
  17715. HighlightEditor._keyboardManager.exec(this, event);
  17716. }
  17717. _moveCaret(direction) {
  17718. this.parent.unselect(this);
  17719. switch (direction) {
  17720. case 0:
  17721. case 2:
  17722. this.#setCaret(true);
  17723. break;
  17724. case 1:
  17725. case 3:
  17726. this.#setCaret(false);
  17727. break;
  17728. }
  17729. }
  17730. #setCaret(start) {
  17731. if (!this.#anchorNode) {
  17732. return;
  17733. }
  17734. const selection = window.getSelection();
  17735. if (start) {
  17736. selection.setPosition(this.#anchorNode, this.#anchorOffset);
  17737. } else {
  17738. selection.setPosition(this.#focusNode, this.#focusOffset);
  17739. }
  17740. }
  17741. select() {
  17742. super.select();
  17743. if (!this.#outlineId) {
  17744. return;
  17745. }
  17746. this.parent?.drawLayer.removeClass(this.#outlineId, "hovered");
  17747. this.parent?.drawLayer.addClass(this.#outlineId, "selected");
  17748. }
  17749. unselect() {
  17750. super.unselect();
  17751. if (!this.#outlineId) {
  17752. return;
  17753. }
  17754. this.parent?.drawLayer.removeClass(this.#outlineId, "selected");
  17755. if (!this.#isFreeHighlight) {
  17756. this.#setCaret(false);
  17757. }
  17758. }
  17759. get _mustFixPosition() {
  17760. return !this.#isFreeHighlight;
  17761. }
  17762. show(visible = this._isVisible) {
  17763. super.show(visible);
  17764. if (this.parent) {
  17765. this.parent.drawLayer.show(this.#id, visible);
  17766. this.parent.drawLayer.show(this.#outlineId, visible);
  17767. }
  17768. }
  17769. #getRotation() {
  17770. return this.#isFreeHighlight ? this.rotation : 0;
  17771. }
  17772. #serializeBoxes() {
  17773. if (this.#isFreeHighlight) {
  17774. return null;
  17775. }
  17776. const [pageWidth, pageHeight] = this.pageDimensions;
  17777. const [pageX, pageY] = this.pageTranslation;
  17778. const boxes = this.#boxes;
  17779. const quadPoints = new Float32Array(boxes.length * 8);
  17780. let i = 0;
  17781. for (const {
  17782. x,
  17783. y,
  17784. width,
  17785. height
  17786. } of boxes) {
  17787. const sx = x * pageWidth + pageX;
  17788. const sy = (1 - y - height) * pageHeight + pageY;
  17789. quadPoints[i] = quadPoints[i + 4] = sx;
  17790. quadPoints[i + 1] = quadPoints[i + 3] = sy;
  17791. quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth;
  17792. quadPoints[i + 5] = quadPoints[i + 7] = sy + height * pageHeight;
  17793. i += 8;
  17794. }
  17795. return quadPoints;
  17796. }
  17797. #serializeOutlines(rect) {
  17798. return this.#highlightOutlines.serialize(rect, this.#getRotation());
  17799. }
  17800. static startHighlighting(parent, isLTR, {
  17801. target: textLayer,
  17802. x,
  17803. y
  17804. }) {
  17805. const {
  17806. x: layerX,
  17807. y: layerY,
  17808. width: parentWidth,
  17809. height: parentHeight
  17810. } = textLayer.getBoundingClientRect();
  17811. const ac = new AbortController();
  17812. const signal = parent.combinedSignal(ac);
  17813. const pointerDown = e => {
  17814. e.preventDefault();
  17815. e.stopPropagation();
  17816. };
  17817. const pointerUpCallback = e => {
  17818. ac.abort();
  17819. this.#endHighlight(parent, e);
  17820. };
  17821. window.addEventListener("blur", pointerUpCallback, {
  17822. signal
  17823. });
  17824. window.addEventListener("pointerup", pointerUpCallback, {
  17825. signal
  17826. });
  17827. window.addEventListener("pointerdown", pointerDown, {
  17828. capture: true,
  17829. passive: false,
  17830. signal
  17831. });
  17832. window.addEventListener("contextmenu", noContextMenu, {
  17833. signal
  17834. });
  17835. textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {
  17836. signal
  17837. });
  17838. this._freeHighlight = new FreeHighlightOutliner({
  17839. x,
  17840. y
  17841. }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001);
  17842. ({
  17843. id: this._freeHighlightId,
  17844. clipPathId: this._freeHighlightClipId
  17845. } = parent.drawLayer.draw(this._freeHighlight, this._defaultColor, this._defaultOpacity, true));
  17846. }
  17847. static #highlightMove(parent, event) {
  17848. if (this._freeHighlight.add(event)) {
  17849. parent.drawLayer.updatePath(this._freeHighlightId, this._freeHighlight);
  17850. }
  17851. }
  17852. static #endHighlight(parent, event) {
  17853. if (!this._freeHighlight.isEmpty()) {
  17854. parent.createAndAddNewEditor(event, false, {
  17855. highlightId: this._freeHighlightId,
  17856. highlightOutlines: this._freeHighlight.getOutlines(),
  17857. clipPathId: this._freeHighlightClipId,
  17858. methodOfCreation: "main_toolbar"
  17859. });
  17860. } else {
  17861. parent.drawLayer.remove(this._freeHighlightId);
  17862. }
  17863. this._freeHighlightId = -1;
  17864. this._freeHighlight = null;
  17865. this._freeHighlightClipId = "";
  17866. }
  17867. static async deserialize(data, parent, uiManager) {
  17868. let initialData = null;
  17869. if (data instanceof HighlightAnnotationElement) {
  17870. const {
  17871. data: {
  17872. quadPoints,
  17873. rect,
  17874. rotation,
  17875. id,
  17876. color,
  17877. opacity,
  17878. popupRef
  17879. },
  17880. parent: {
  17881. page: {
  17882. pageNumber
  17883. }
  17884. }
  17885. } = data;
  17886. initialData = data = {
  17887. annotationType: AnnotationEditorType.HIGHLIGHT,
  17888. color: Array.from(color),
  17889. opacity,
  17890. quadPoints,
  17891. boxes: null,
  17892. pageIndex: pageNumber - 1,
  17893. rect: rect.slice(0),
  17894. rotation,
  17895. id,
  17896. deleted: false,
  17897. popupRef
  17898. };
  17899. } else if (data instanceof InkAnnotationElement) {
  17900. const {
  17901. data: {
  17902. inkLists,
  17903. rect,
  17904. rotation,
  17905. id,
  17906. color,
  17907. borderStyle: {
  17908. rawWidth: thickness
  17909. },
  17910. popupRef
  17911. },
  17912. parent: {
  17913. page: {
  17914. pageNumber
  17915. }
  17916. }
  17917. } = data;
  17918. initialData = data = {
  17919. annotationType: AnnotationEditorType.HIGHLIGHT,
  17920. color: Array.from(color),
  17921. thickness,
  17922. inkLists,
  17923. boxes: null,
  17924. pageIndex: pageNumber - 1,
  17925. rect: rect.slice(0),
  17926. rotation,
  17927. id,
  17928. deleted: false,
  17929. popupRef
  17930. };
  17931. }
  17932. const {
  17933. color,
  17934. quadPoints,
  17935. inkLists,
  17936. opacity
  17937. } = data;
  17938. const editor = await super.deserialize(data, parent, uiManager);
  17939. editor.color = Util.makeHexColor(...color);
  17940. editor.#opacity = opacity || 1;
  17941. if (inkLists) {
  17942. editor.#thickness = data.thickness;
  17943. }
  17944. editor.annotationElementId = data.id || null;
  17945. editor._initialData = initialData;
  17946. const [pageWidth, pageHeight] = editor.pageDimensions;
  17947. const [pageX, pageY] = editor.pageTranslation;
  17948. if (quadPoints) {
  17949. const boxes = editor.#boxes = [];
  17950. for (let i = 0; i < quadPoints.length; i += 8) {
  17951. boxes.push({
  17952. x: (quadPoints[i] - pageX) / pageWidth,
  17953. y: 1 - (quadPoints[i + 1] - pageY) / pageHeight,
  17954. width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth,
  17955. height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight
  17956. });
  17957. }
  17958. editor.#createOutlines();
  17959. editor.#addToDrawLayer();
  17960. editor.rotate(editor.rotation);
  17961. } else if (inkLists) {
  17962. editor.#isFreeHighlight = true;
  17963. const points = inkLists[0];
  17964. const point = {
  17965. x: points[0] - pageX,
  17966. y: pageHeight - (points[1] - pageY)
  17967. };
  17968. const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001);
  17969. for (let i = 0, ii = points.length; i < ii; i += 2) {
  17970. point.x = points[i] - pageX;
  17971. point.y = pageHeight - (points[i + 1] - pageY);
  17972. outliner.add(point);
  17973. }
  17974. const {
  17975. id,
  17976. clipPathId
  17977. } = parent.drawLayer.draw(outliner, editor.color, editor._defaultOpacity, true);
  17978. editor.#createFreeOutlines({
  17979. highlightOutlines: outliner.getOutlines(),
  17980. highlightId: id,
  17981. clipPathId
  17982. });
  17983. editor.#addToDrawLayer();
  17984. }
  17985. return editor;
  17986. }
  17987. serialize(isForCopying = false) {
  17988. if (this.isEmpty() || isForCopying) {
  17989. return null;
  17990. }
  17991. if (this.deleted) {
  17992. return this.serializeDeleted();
  17993. }
  17994. const rect = this.getRect(0, 0);
  17995. const color = AnnotationEditor._colorManager.convert(this.color);
  17996. const serialized = {
  17997. annotationType: AnnotationEditorType.HIGHLIGHT,
  17998. color,
  17999. opacity: this.#opacity,
  18000. thickness: this.#thickness,
  18001. quadPoints: this.#serializeBoxes(),
  18002. outlines: this.#serializeOutlines(rect),
  18003. pageIndex: this.pageIndex,
  18004. rect,
  18005. rotation: this.#getRotation(),
  18006. structTreeParentId: this._structTreeParentId
  18007. };
  18008. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  18009. return null;
  18010. }
  18011. serialized.id = this.annotationElementId;
  18012. return serialized;
  18013. }
  18014. #hasElementChanged(serialized) {
  18015. const {
  18016. color
  18017. } = this._initialData;
  18018. return serialized.color.some((c, i) => c !== color[i]);
  18019. }
  18020. renderAnnotationElement(annotation) {
  18021. annotation.updateEdited({
  18022. rect: this.getRect(0, 0)
  18023. });
  18024. return null;
  18025. }
  18026. static canCreateNewEmptyEditor() {
  18027. return false;
  18028. }
  18029. }
  18030. ;// ./src/display/editor/ink.js
  18031. class InkEditor extends AnnotationEditor {
  18032. #baseHeight = 0;
  18033. #baseWidth = 0;
  18034. #canvasContextMenuTimeoutId = null;
  18035. #currentPath2D = new Path2D();
  18036. #disableEditing = false;
  18037. #drawingAC = null;
  18038. #hasSomethingToDraw = false;
  18039. #isCanvasInitialized = false;
  18040. #observer = null;
  18041. #pointerdownAC = null;
  18042. #realWidth = 0;
  18043. #realHeight = 0;
  18044. #requestFrameCallback = null;
  18045. static _defaultColor = null;
  18046. static _defaultOpacity = 1;
  18047. static _defaultThickness = 1;
  18048. static _type = "ink";
  18049. static _editorType = AnnotationEditorType.INK;
  18050. constructor(params) {
  18051. super({
  18052. ...params,
  18053. name: "inkEditor"
  18054. });
  18055. this.color = params.color || null;
  18056. this.thickness = params.thickness || null;
  18057. this.opacity = params.opacity || null;
  18058. this.paths = [];
  18059. this.bezierPath2D = [];
  18060. this.allRawPaths = [];
  18061. this.currentPath = [];
  18062. this.scaleFactor = 1;
  18063. this.translationX = this.translationY = 0;
  18064. this.x = 0;
  18065. this.y = 0;
  18066. this._willKeepAspectRatio = true;
  18067. }
  18068. static initialize(l10n, uiManager) {
  18069. AnnotationEditor.initialize(l10n, uiManager);
  18070. }
  18071. static updateDefaultParams(type, value) {
  18072. switch (type) {
  18073. case AnnotationEditorParamsType.INK_THICKNESS:
  18074. InkEditor._defaultThickness = value;
  18075. break;
  18076. case AnnotationEditorParamsType.INK_COLOR:
  18077. InkEditor._defaultColor = value;
  18078. break;
  18079. case AnnotationEditorParamsType.INK_OPACITY:
  18080. InkEditor._defaultOpacity = value / 100;
  18081. break;
  18082. }
  18083. }
  18084. updateParams(type, value) {
  18085. switch (type) {
  18086. case AnnotationEditorParamsType.INK_THICKNESS:
  18087. this.#updateThickness(value);
  18088. break;
  18089. case AnnotationEditorParamsType.INK_COLOR:
  18090. this.#updateColor(value);
  18091. break;
  18092. case AnnotationEditorParamsType.INK_OPACITY:
  18093. this.#updateOpacity(value);
  18094. break;
  18095. }
  18096. }
  18097. static get defaultPropertiesToUpdate() {
  18098. return [[AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
  18099. }
  18100. get propertiesToUpdate() {
  18101. return [[AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
  18102. }
  18103. #updateThickness(thickness) {
  18104. const setThickness = th => {
  18105. this.thickness = th;
  18106. this.#fitToContent();
  18107. };
  18108. const savedThickness = this.thickness;
  18109. this.addCommands({
  18110. cmd: setThickness.bind(this, thickness),
  18111. undo: setThickness.bind(this, savedThickness),
  18112. post: this._uiManager.updateUI.bind(this._uiManager, this),
  18113. mustExec: true,
  18114. type: AnnotationEditorParamsType.INK_THICKNESS,
  18115. overwriteIfSameType: true,
  18116. keepUndo: true
  18117. });
  18118. }
  18119. #updateColor(color) {
  18120. const setColor = col => {
  18121. this.color = col;
  18122. this.#redraw();
  18123. };
  18124. const savedColor = this.color;
  18125. this.addCommands({
  18126. cmd: setColor.bind(this, color),
  18127. undo: setColor.bind(this, savedColor),
  18128. post: this._uiManager.updateUI.bind(this._uiManager, this),
  18129. mustExec: true,
  18130. type: AnnotationEditorParamsType.INK_COLOR,
  18131. overwriteIfSameType: true,
  18132. keepUndo: true
  18133. });
  18134. }
  18135. #updateOpacity(opacity) {
  18136. const setOpacity = op => {
  18137. this.opacity = op;
  18138. this.#redraw();
  18139. };
  18140. opacity /= 100;
  18141. const savedOpacity = this.opacity;
  18142. this.addCommands({
  18143. cmd: setOpacity.bind(this, opacity),
  18144. undo: setOpacity.bind(this, savedOpacity),
  18145. post: this._uiManager.updateUI.bind(this._uiManager, this),
  18146. mustExec: true,
  18147. type: AnnotationEditorParamsType.INK_OPACITY,
  18148. overwriteIfSameType: true,
  18149. keepUndo: true
  18150. });
  18151. }
  18152. rebuild() {
  18153. if (!this.parent) {
  18154. return;
  18155. }
  18156. super.rebuild();
  18157. if (this.div === null) {
  18158. return;
  18159. }
  18160. if (!this.canvas) {
  18161. this.#createCanvas();
  18162. this.#createObserver();
  18163. }
  18164. if (!this.isAttachedToDOM) {
  18165. this.parent.add(this);
  18166. this.#setCanvasDims();
  18167. }
  18168. this.#fitToContent();
  18169. }
  18170. remove() {
  18171. if (this.canvas === null) {
  18172. return;
  18173. }
  18174. if (!this.isEmpty()) {
  18175. this.commit();
  18176. }
  18177. this.canvas.width = this.canvas.height = 0;
  18178. this.canvas.remove();
  18179. this.canvas = null;
  18180. if (this.#canvasContextMenuTimeoutId) {
  18181. clearTimeout(this.#canvasContextMenuTimeoutId);
  18182. this.#canvasContextMenuTimeoutId = null;
  18183. }
  18184. this.#observer?.disconnect();
  18185. this.#observer = null;
  18186. super.remove();
  18187. }
  18188. setParent(parent) {
  18189. if (!this.parent && parent) {
  18190. this._uiManager.removeShouldRescale(this);
  18191. } else if (this.parent && parent === null) {
  18192. this._uiManager.addShouldRescale(this);
  18193. }
  18194. super.setParent(parent);
  18195. }
  18196. onScaleChanging() {
  18197. const [parentWidth, parentHeight] = this.parentDimensions;
  18198. const width = this.width * parentWidth;
  18199. const height = this.height * parentHeight;
  18200. this.setDimensions(width, height);
  18201. }
  18202. enableEditMode() {
  18203. if (this.#disableEditing || this.canvas === null) {
  18204. return;
  18205. }
  18206. super.enableEditMode();
  18207. this._isDraggable = false;
  18208. this.#addPointerdownListener();
  18209. }
  18210. disableEditMode() {
  18211. if (!this.isInEditMode() || this.canvas === null) {
  18212. return;
  18213. }
  18214. super.disableEditMode();
  18215. this._isDraggable = !this.isEmpty();
  18216. this.div.classList.remove("editing");
  18217. this.#removePointerdownListener();
  18218. }
  18219. onceAdded() {
  18220. this._isDraggable = !this.isEmpty();
  18221. }
  18222. isEmpty() {
  18223. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  18224. }
  18225. #getInitialBBox() {
  18226. const {
  18227. parentRotation,
  18228. parentDimensions: [width, height]
  18229. } = this;
  18230. switch (parentRotation) {
  18231. case 90:
  18232. return [0, height, height, width];
  18233. case 180:
  18234. return [width, height, width, height];
  18235. case 270:
  18236. return [width, 0, height, width];
  18237. default:
  18238. return [0, 0, width, height];
  18239. }
  18240. }
  18241. #setStroke() {
  18242. const {
  18243. ctx,
  18244. color,
  18245. opacity,
  18246. thickness,
  18247. parentScale,
  18248. scaleFactor
  18249. } = this;
  18250. ctx.lineWidth = thickness * parentScale / scaleFactor;
  18251. ctx.lineCap = "round";
  18252. ctx.lineJoin = "round";
  18253. ctx.miterLimit = 10;
  18254. ctx.strokeStyle = `${color}${opacityToHex(opacity)}`;
  18255. }
  18256. #startDrawing(x, y) {
  18257. this.canvas.addEventListener("contextmenu", noContextMenu, {
  18258. signal: this._uiManager._signal
  18259. });
  18260. this.#removePointerdownListener();
  18261. this.#drawingAC = new AbortController();
  18262. const signal = this._uiManager.combinedSignal(this.#drawingAC);
  18263. this.canvas.addEventListener("pointerleave", this.canvasPointerleave.bind(this), {
  18264. signal
  18265. });
  18266. this.canvas.addEventListener("pointermove", this.canvasPointermove.bind(this), {
  18267. signal
  18268. });
  18269. this.canvas.addEventListener("pointerup", this.canvasPointerup.bind(this), {
  18270. signal
  18271. });
  18272. this.isEditing = true;
  18273. if (!this.#isCanvasInitialized) {
  18274. this.#isCanvasInitialized = true;
  18275. this.#setCanvasDims();
  18276. this.thickness ||= InkEditor._defaultThickness;
  18277. this.color ||= InkEditor._defaultColor || AnnotationEditor._defaultLineColor;
  18278. this.opacity ??= InkEditor._defaultOpacity;
  18279. }
  18280. this.currentPath.push([x, y]);
  18281. this.#hasSomethingToDraw = false;
  18282. this.#setStroke();
  18283. this.#requestFrameCallback = () => {
  18284. this.#drawPoints();
  18285. if (this.#requestFrameCallback) {
  18286. window.requestAnimationFrame(this.#requestFrameCallback);
  18287. }
  18288. };
  18289. window.requestAnimationFrame(this.#requestFrameCallback);
  18290. }
  18291. #draw(x, y) {
  18292. const [lastX, lastY] = this.currentPath.at(-1);
  18293. if (this.currentPath.length > 1 && x === lastX && y === lastY) {
  18294. return;
  18295. }
  18296. const currentPath = this.currentPath;
  18297. let path2D = this.#currentPath2D;
  18298. currentPath.push([x, y]);
  18299. this.#hasSomethingToDraw = true;
  18300. if (currentPath.length <= 2) {
  18301. path2D.moveTo(...currentPath[0]);
  18302. path2D.lineTo(x, y);
  18303. return;
  18304. }
  18305. if (currentPath.length === 3) {
  18306. this.#currentPath2D = path2D = new Path2D();
  18307. path2D.moveTo(...currentPath[0]);
  18308. }
  18309. this.#makeBezierCurve(path2D, ...currentPath.at(-3), ...currentPath.at(-2), x, y);
  18310. }
  18311. #endPath() {
  18312. if (this.currentPath.length === 0) {
  18313. return;
  18314. }
  18315. const lastPoint = this.currentPath.at(-1);
  18316. this.#currentPath2D.lineTo(...lastPoint);
  18317. }
  18318. #stopDrawing(x, y) {
  18319. this.#requestFrameCallback = null;
  18320. x = Math.min(Math.max(x, 0), this.canvas.width);
  18321. y = Math.min(Math.max(y, 0), this.canvas.height);
  18322. this.#draw(x, y);
  18323. this.#endPath();
  18324. let bezier;
  18325. if (this.currentPath.length !== 1) {
  18326. bezier = this.#generateBezierPoints();
  18327. } else {
  18328. const xy = [x, y];
  18329. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  18330. }
  18331. const path2D = this.#currentPath2D;
  18332. const currentPath = this.currentPath;
  18333. this.currentPath = [];
  18334. this.#currentPath2D = new Path2D();
  18335. const cmd = () => {
  18336. this.allRawPaths.push(currentPath);
  18337. this.paths.push(bezier);
  18338. this.bezierPath2D.push(path2D);
  18339. this._uiManager.rebuild(this);
  18340. };
  18341. const undo = () => {
  18342. this.allRawPaths.pop();
  18343. this.paths.pop();
  18344. this.bezierPath2D.pop();
  18345. if (this.paths.length === 0) {
  18346. this.remove();
  18347. } else {
  18348. if (!this.canvas) {
  18349. this.#createCanvas();
  18350. this.#createObserver();
  18351. }
  18352. this.#fitToContent();
  18353. }
  18354. };
  18355. this.addCommands({
  18356. cmd,
  18357. undo,
  18358. mustExec: true
  18359. });
  18360. }
  18361. #drawPoints() {
  18362. if (!this.#hasSomethingToDraw) {
  18363. return;
  18364. }
  18365. this.#hasSomethingToDraw = false;
  18366. const thickness = Math.ceil(this.thickness * this.parentScale);
  18367. const lastPoints = this.currentPath.slice(-3);
  18368. const x = lastPoints.map(xy => xy[0]);
  18369. const y = lastPoints.map(xy => xy[1]);
  18370. const xMin = Math.min(...x) - thickness;
  18371. const xMax = Math.max(...x) + thickness;
  18372. const yMin = Math.min(...y) - thickness;
  18373. const yMax = Math.max(...y) + thickness;
  18374. const {
  18375. ctx
  18376. } = this;
  18377. ctx.save();
  18378. ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  18379. for (const path of this.bezierPath2D) {
  18380. ctx.stroke(path);
  18381. }
  18382. ctx.stroke(this.#currentPath2D);
  18383. ctx.restore();
  18384. }
  18385. #makeBezierCurve(path2D, x0, y0, x1, y1, x2, y2) {
  18386. const prevX = (x0 + x1) / 2;
  18387. const prevY = (y0 + y1) / 2;
  18388. const x3 = (x1 + x2) / 2;
  18389. const y3 = (y1 + y2) / 2;
  18390. path2D.bezierCurveTo(prevX + 2 * (x1 - prevX) / 3, prevY + 2 * (y1 - prevY) / 3, x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3, x3, y3);
  18391. }
  18392. #generateBezierPoints() {
  18393. const path = this.currentPath;
  18394. if (path.length <= 2) {
  18395. return [[path[0], path[0], path.at(-1), path.at(-1)]];
  18396. }
  18397. const bezierPoints = [];
  18398. let i;
  18399. let [x0, y0] = path[0];
  18400. for (i = 1; i < path.length - 2; i++) {
  18401. const [x1, y1] = path[i];
  18402. const [x2, y2] = path[i + 1];
  18403. const x3 = (x1 + x2) / 2;
  18404. const y3 = (y1 + y2) / 2;
  18405. const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
  18406. const control2 = [x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3];
  18407. bezierPoints.push([[x0, y0], control1, control2, [x3, y3]]);
  18408. [x0, y0] = [x3, y3];
  18409. }
  18410. const [x1, y1] = path[i];
  18411. const [x2, y2] = path[i + 1];
  18412. const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
  18413. const control2 = [x2 + 2 * (x1 - x2) / 3, y2 + 2 * (y1 - y2) / 3];
  18414. bezierPoints.push([[x0, y0], control1, control2, [x2, y2]]);
  18415. return bezierPoints;
  18416. }
  18417. #redraw() {
  18418. if (this.isEmpty()) {
  18419. this.#updateTransform();
  18420. return;
  18421. }
  18422. this.#setStroke();
  18423. const {
  18424. canvas,
  18425. ctx
  18426. } = this;
  18427. ctx.setTransform(1, 0, 0, 1, 0, 0);
  18428. ctx.clearRect(0, 0, canvas.width, canvas.height);
  18429. this.#updateTransform();
  18430. for (const path of this.bezierPath2D) {
  18431. ctx.stroke(path);
  18432. }
  18433. }
  18434. commit() {
  18435. if (this.#disableEditing) {
  18436. return;
  18437. }
  18438. super.commit();
  18439. this.isEditing = false;
  18440. this.disableEditMode();
  18441. this.setInForeground();
  18442. this.#disableEditing = true;
  18443. this.div.classList.add("disabled");
  18444. this.#fitToContent(true);
  18445. this.select();
  18446. this.parent.addInkEditorIfNeeded(true);
  18447. this.moveInDOM();
  18448. this.div.focus({
  18449. preventScroll: true
  18450. });
  18451. }
  18452. focusin(event) {
  18453. if (!this._focusEventsAllowed) {
  18454. return;
  18455. }
  18456. super.focusin(event);
  18457. this.enableEditMode();
  18458. }
  18459. #addPointerdownListener() {
  18460. if (this.#pointerdownAC) {
  18461. return;
  18462. }
  18463. this.#pointerdownAC = new AbortController();
  18464. const signal = this._uiManager.combinedSignal(this.#pointerdownAC);
  18465. this.canvas.addEventListener("pointerdown", this.canvasPointerdown.bind(this), {
  18466. signal
  18467. });
  18468. }
  18469. #removePointerdownListener() {
  18470. this.pointerdownAC?.abort();
  18471. this.pointerdownAC = null;
  18472. }
  18473. canvasPointerdown(event) {
  18474. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  18475. return;
  18476. }
  18477. this.setInForeground();
  18478. event.preventDefault();
  18479. if (!this.div.contains(document.activeElement)) {
  18480. this.div.focus({
  18481. preventScroll: true
  18482. });
  18483. }
  18484. this.#startDrawing(event.offsetX, event.offsetY);
  18485. }
  18486. canvasPointermove(event) {
  18487. event.preventDefault();
  18488. this.#draw(event.offsetX, event.offsetY);
  18489. }
  18490. canvasPointerup(event) {
  18491. event.preventDefault();
  18492. this.#endDrawing(event);
  18493. }
  18494. canvasPointerleave(event) {
  18495. this.#endDrawing(event);
  18496. }
  18497. #endDrawing(event) {
  18498. this.#drawingAC?.abort();
  18499. this.#drawingAC = null;
  18500. this.#addPointerdownListener();
  18501. if (this.#canvasContextMenuTimeoutId) {
  18502. clearTimeout(this.#canvasContextMenuTimeoutId);
  18503. }
  18504. this.#canvasContextMenuTimeoutId = setTimeout(() => {
  18505. this.#canvasContextMenuTimeoutId = null;
  18506. this.canvas.removeEventListener("contextmenu", noContextMenu);
  18507. }, 10);
  18508. this.#stopDrawing(event.offsetX, event.offsetY);
  18509. this.addToAnnotationStorage();
  18510. this.setInBackground();
  18511. }
  18512. #createCanvas() {
  18513. this.canvas = document.createElement("canvas");
  18514. this.canvas.width = this.canvas.height = 0;
  18515. this.canvas.className = "inkEditorCanvas";
  18516. this.canvas.setAttribute("data-l10n-id", "pdfjs-ink-canvas");
  18517. this.div.append(this.canvas);
  18518. this.ctx = this.canvas.getContext("2d");
  18519. }
  18520. #createObserver() {
  18521. this.#observer = new ResizeObserver(entries => {
  18522. const rect = entries[0].contentRect;
  18523. if (rect.width && rect.height) {
  18524. this.setDimensions(rect.width, rect.height);
  18525. }
  18526. });
  18527. this.#observer.observe(this.div);
  18528. this._uiManager._signal.addEventListener("abort", () => {
  18529. this.#observer?.disconnect();
  18530. this.#observer = null;
  18531. }, {
  18532. once: true
  18533. });
  18534. }
  18535. get isResizable() {
  18536. return !this.isEmpty() && this.#disableEditing;
  18537. }
  18538. render() {
  18539. if (this.div) {
  18540. return this.div;
  18541. }
  18542. let baseX, baseY;
  18543. if (this.width) {
  18544. baseX = this.x;
  18545. baseY = this.y;
  18546. }
  18547. super.render();
  18548. this.div.setAttribute("data-l10n-id", "pdfjs-ink");
  18549. const [x, y, w, h] = this.#getInitialBBox();
  18550. this.setAt(x, y, 0, 0);
  18551. this.setDims(w, h);
  18552. this.#createCanvas();
  18553. if (this.width) {
  18554. const [parentWidth, parentHeight] = this.parentDimensions;
  18555. this.setAspectRatio(this.width * parentWidth, this.height * parentHeight);
  18556. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  18557. this.#isCanvasInitialized = true;
  18558. this.#setCanvasDims();
  18559. this.setDims(this.width * parentWidth, this.height * parentHeight);
  18560. this.#redraw();
  18561. this.div.classList.add("disabled");
  18562. } else {
  18563. this.div.classList.add("editing");
  18564. this.enableEditMode();
  18565. }
  18566. this.#createObserver();
  18567. return this.div;
  18568. }
  18569. #setCanvasDims() {
  18570. if (!this.#isCanvasInitialized) {
  18571. return;
  18572. }
  18573. const [parentWidth, parentHeight] = this.parentDimensions;
  18574. this.canvas.width = Math.ceil(this.width * parentWidth);
  18575. this.canvas.height = Math.ceil(this.height * parentHeight);
  18576. this.#updateTransform();
  18577. }
  18578. setDimensions(width, height) {
  18579. const roundedWidth = Math.round(width);
  18580. const roundedHeight = Math.round(height);
  18581. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  18582. return;
  18583. }
  18584. this.#realWidth = roundedWidth;
  18585. this.#realHeight = roundedHeight;
  18586. this.canvas.style.visibility = "hidden";
  18587. const [parentWidth, parentHeight] = this.parentDimensions;
  18588. this.width = width / parentWidth;
  18589. this.height = height / parentHeight;
  18590. this.fixAndSetPosition();
  18591. if (this.#disableEditing) {
  18592. this.#setScaleFactor(width, height);
  18593. }
  18594. this.#setCanvasDims();
  18595. this.#redraw();
  18596. this.canvas.style.visibility = "visible";
  18597. this.fixDims();
  18598. }
  18599. #setScaleFactor(width, height) {
  18600. const padding = this.#getPadding();
  18601. const scaleFactorW = (width - padding) / this.#baseWidth;
  18602. const scaleFactorH = (height - padding) / this.#baseHeight;
  18603. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  18604. }
  18605. #updateTransform() {
  18606. const padding = this.#getPadding() / 2;
  18607. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  18608. }
  18609. static #buildPath2D(bezier) {
  18610. const path2D = new Path2D();
  18611. for (let i = 0, ii = bezier.length; i < ii; i++) {
  18612. const [first, control1, control2, second] = bezier[i];
  18613. if (i === 0) {
  18614. path2D.moveTo(...first);
  18615. }
  18616. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  18617. }
  18618. return path2D;
  18619. }
  18620. static #toPDFCoordinates(points, rect, rotation) {
  18621. const [blX, blY, trX, trY] = rect;
  18622. switch (rotation) {
  18623. case 0:
  18624. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18625. points[i] += blX;
  18626. points[i + 1] = trY - points[i + 1];
  18627. }
  18628. break;
  18629. case 90:
  18630. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18631. const x = points[i];
  18632. points[i] = points[i + 1] + blX;
  18633. points[i + 1] = x + blY;
  18634. }
  18635. break;
  18636. case 180:
  18637. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18638. points[i] = trX - points[i];
  18639. points[i + 1] += blY;
  18640. }
  18641. break;
  18642. case 270:
  18643. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18644. const x = points[i];
  18645. points[i] = trX - points[i + 1];
  18646. points[i + 1] = trY - x;
  18647. }
  18648. break;
  18649. default:
  18650. throw new Error("Invalid rotation");
  18651. }
  18652. return points;
  18653. }
  18654. static #fromPDFCoordinates(points, rect, rotation) {
  18655. const [blX, blY, trX, trY] = rect;
  18656. switch (rotation) {
  18657. case 0:
  18658. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18659. points[i] -= blX;
  18660. points[i + 1] = trY - points[i + 1];
  18661. }
  18662. break;
  18663. case 90:
  18664. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18665. const x = points[i];
  18666. points[i] = points[i + 1] - blY;
  18667. points[i + 1] = x - blX;
  18668. }
  18669. break;
  18670. case 180:
  18671. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18672. points[i] = trX - points[i];
  18673. points[i + 1] -= blY;
  18674. }
  18675. break;
  18676. case 270:
  18677. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18678. const x = points[i];
  18679. points[i] = trY - points[i + 1];
  18680. points[i + 1] = trX - x;
  18681. }
  18682. break;
  18683. default:
  18684. throw new Error("Invalid rotation");
  18685. }
  18686. return points;
  18687. }
  18688. #serializePaths(s, tx, ty, rect) {
  18689. const paths = [];
  18690. const padding = this.thickness / 2;
  18691. const shiftX = s * tx + padding;
  18692. const shiftY = s * ty + padding;
  18693. for (const bezier of this.paths) {
  18694. const buffer = [];
  18695. const points = [];
  18696. for (let j = 0, jj = bezier.length; j < jj; j++) {
  18697. const [first, control1, control2, second] = bezier[j];
  18698. if (first[0] === second[0] && first[1] === second[1] && jj === 1) {
  18699. const p0 = s * first[0] + shiftX;
  18700. const p1 = s * first[1] + shiftY;
  18701. buffer.push(p0, p1);
  18702. points.push(p0, p1);
  18703. break;
  18704. }
  18705. const p10 = s * first[0] + shiftX;
  18706. const p11 = s * first[1] + shiftY;
  18707. const p20 = s * control1[0] + shiftX;
  18708. const p21 = s * control1[1] + shiftY;
  18709. const p30 = s * control2[0] + shiftX;
  18710. const p31 = s * control2[1] + shiftY;
  18711. const p40 = s * second[0] + shiftX;
  18712. const p41 = s * second[1] + shiftY;
  18713. if (j === 0) {
  18714. buffer.push(p10, p11);
  18715. points.push(p10, p11);
  18716. }
  18717. buffer.push(p20, p21, p30, p31, p40, p41);
  18718. points.push(p20, p21);
  18719. if (j === jj - 1) {
  18720. points.push(p40, p41);
  18721. }
  18722. }
  18723. paths.push({
  18724. bezier: InkEditor.#toPDFCoordinates(buffer, rect, this.rotation),
  18725. points: InkEditor.#toPDFCoordinates(points, rect, this.rotation)
  18726. });
  18727. }
  18728. return paths;
  18729. }
  18730. #getBbox() {
  18731. let xMin = Infinity;
  18732. let xMax = -Infinity;
  18733. let yMin = Infinity;
  18734. let yMax = -Infinity;
  18735. for (const path of this.paths) {
  18736. for (const [first, control1, control2, second] of path) {
  18737. const bbox = Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  18738. xMin = Math.min(xMin, bbox[0]);
  18739. yMin = Math.min(yMin, bbox[1]);
  18740. xMax = Math.max(xMax, bbox[2]);
  18741. yMax = Math.max(yMax, bbox[3]);
  18742. }
  18743. }
  18744. return [xMin, yMin, xMax, yMax];
  18745. }
  18746. #getPadding() {
  18747. return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
  18748. }
  18749. #fitToContent(firstTime = false) {
  18750. if (this.isEmpty()) {
  18751. return;
  18752. }
  18753. if (!this.#disableEditing) {
  18754. this.#redraw();
  18755. return;
  18756. }
  18757. const bbox = this.#getBbox();
  18758. const padding = this.#getPadding();
  18759. this.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
  18760. this.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
  18761. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  18762. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  18763. const [parentWidth, parentHeight] = this.parentDimensions;
  18764. this.width = width / parentWidth;
  18765. this.height = height / parentHeight;
  18766. this.setAspectRatio(width, height);
  18767. const prevTranslationX = this.translationX;
  18768. const prevTranslationY = this.translationY;
  18769. this.translationX = -bbox[0];
  18770. this.translationY = -bbox[1];
  18771. this.#setCanvasDims();
  18772. this.#redraw();
  18773. this.#realWidth = width;
  18774. this.#realHeight = height;
  18775. this.setDims(width, height);
  18776. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  18777. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  18778. }
  18779. static async deserialize(data, parent, uiManager) {
  18780. if (data instanceof InkAnnotationElement) {
  18781. return null;
  18782. }
  18783. const editor = await super.deserialize(data, parent, uiManager);
  18784. editor.thickness = data.thickness;
  18785. editor.color = Util.makeHexColor(...data.color);
  18786. editor.opacity = data.opacity;
  18787. const [pageWidth, pageHeight] = editor.pageDimensions;
  18788. const width = editor.width * pageWidth;
  18789. const height = editor.height * pageHeight;
  18790. const scaleFactor = editor.parentScale;
  18791. const padding = data.thickness / 2;
  18792. editor.#disableEditing = true;
  18793. editor.#realWidth = Math.round(width);
  18794. editor.#realHeight = Math.round(height);
  18795. const {
  18796. paths,
  18797. rect,
  18798. rotation
  18799. } = data;
  18800. for (let {
  18801. bezier
  18802. } of paths) {
  18803. bezier = InkEditor.#fromPDFCoordinates(bezier, rect, rotation);
  18804. const path = [];
  18805. editor.paths.push(path);
  18806. let p0 = scaleFactor * (bezier[0] - padding);
  18807. let p1 = scaleFactor * (bezier[1] - padding);
  18808. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  18809. const p10 = scaleFactor * (bezier[i] - padding);
  18810. const p11 = scaleFactor * (bezier[i + 1] - padding);
  18811. const p20 = scaleFactor * (bezier[i + 2] - padding);
  18812. const p21 = scaleFactor * (bezier[i + 3] - padding);
  18813. const p30 = scaleFactor * (bezier[i + 4] - padding);
  18814. const p31 = scaleFactor * (bezier[i + 5] - padding);
  18815. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  18816. p0 = p30;
  18817. p1 = p31;
  18818. }
  18819. const path2D = this.#buildPath2D(path);
  18820. editor.bezierPath2D.push(path2D);
  18821. }
  18822. const bbox = editor.#getBbox();
  18823. editor.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
  18824. editor.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
  18825. editor.#setScaleFactor(width, height);
  18826. return editor;
  18827. }
  18828. serialize() {
  18829. if (this.isEmpty()) {
  18830. return null;
  18831. }
  18832. const rect = this.getRect(0, 0);
  18833. const color = AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  18834. return {
  18835. annotationType: AnnotationEditorType.INK,
  18836. color,
  18837. thickness: this.thickness,
  18838. opacity: this.opacity,
  18839. paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, rect),
  18840. pageIndex: this.pageIndex,
  18841. rect,
  18842. rotation: this.rotation,
  18843. structTreeParentId: this._structTreeParentId
  18844. };
  18845. }
  18846. }
  18847. ;// ./src/display/editor/stamp.js
  18848. class StampEditor extends AnnotationEditor {
  18849. #bitmap = null;
  18850. #bitmapId = null;
  18851. #bitmapPromise = null;
  18852. #bitmapUrl = null;
  18853. #bitmapFile = null;
  18854. #bitmapFileName = "";
  18855. #canvas = null;
  18856. #observer = null;
  18857. #resizeTimeoutId = null;
  18858. #isSvg = false;
  18859. #hasBeenAddedInUndoStack = false;
  18860. static _type = "stamp";
  18861. static _editorType = AnnotationEditorType.STAMP;
  18862. constructor(params) {
  18863. super({
  18864. ...params,
  18865. name: "stampEditor"
  18866. });
  18867. this.#bitmapUrl = params.bitmapUrl;
  18868. this.#bitmapFile = params.bitmapFile;
  18869. }
  18870. static initialize(l10n, uiManager) {
  18871. AnnotationEditor.initialize(l10n, uiManager);
  18872. }
  18873. static get supportedTypes() {
  18874. const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"];
  18875. return shadow(this, "supportedTypes", types.map(type => `image/${type}`));
  18876. }
  18877. static get supportedTypesStr() {
  18878. return shadow(this, "supportedTypesStr", this.supportedTypes.join(","));
  18879. }
  18880. static isHandlingMimeForPasting(mime) {
  18881. return this.supportedTypes.includes(mime);
  18882. }
  18883. static paste(item, parent) {
  18884. parent.pasteEditor(AnnotationEditorType.STAMP, {
  18885. bitmapFile: item.getAsFile()
  18886. });
  18887. }
  18888. altTextFinish() {
  18889. if (this._uiManager.useNewAltTextFlow) {
  18890. this.div.hidden = false;
  18891. }
  18892. super.altTextFinish();
  18893. }
  18894. get telemetryFinalData() {
  18895. return {
  18896. type: "stamp",
  18897. hasAltText: !!this.altTextData?.altText
  18898. };
  18899. }
  18900. static computeTelemetryFinalData(data) {
  18901. const hasAltTextStats = data.get("hasAltText");
  18902. return {
  18903. hasAltText: hasAltTextStats.get(true) ?? 0,
  18904. hasNoAltText: hasAltTextStats.get(false) ?? 0
  18905. };
  18906. }
  18907. #getBitmapFetched(data, fromId = false) {
  18908. if (!data) {
  18909. this.remove();
  18910. return;
  18911. }
  18912. this.#bitmap = data.bitmap;
  18913. if (!fromId) {
  18914. this.#bitmapId = data.id;
  18915. this.#isSvg = data.isSvg;
  18916. }
  18917. if (data.file) {
  18918. this.#bitmapFileName = data.file.name;
  18919. }
  18920. this.#createCanvas();
  18921. }
  18922. #getBitmapDone() {
  18923. this.#bitmapPromise = null;
  18924. this._uiManager.enableWaiting(false);
  18925. if (!this.#canvas) {
  18926. return;
  18927. }
  18928. if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  18929. this._editToolbar.hide();
  18930. this._uiManager.editAltText(this, true);
  18931. return;
  18932. }
  18933. if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  18934. this._reportTelemetry({
  18935. action: "pdfjs.image.image_added",
  18936. data: {
  18937. alt_text_modal: false,
  18938. alt_text_type: "empty"
  18939. }
  18940. });
  18941. try {
  18942. this.mlGuessAltText();
  18943. } catch {}
  18944. }
  18945. this.div.focus();
  18946. }
  18947. async mlGuessAltText(imageData = null, updateAltTextData = true) {
  18948. if (this.hasAltTextData()) {
  18949. return null;
  18950. }
  18951. const {
  18952. mlManager
  18953. } = this._uiManager;
  18954. if (!mlManager) {
  18955. throw new Error("No ML.");
  18956. }
  18957. if (!(await mlManager.isEnabledFor("altText"))) {
  18958. throw new Error("ML isn't enabled for alt text.");
  18959. }
  18960. const {
  18961. data,
  18962. width,
  18963. height
  18964. } = imageData || this.copyCanvas(null, null, true).imageData;
  18965. const response = await mlManager.guess({
  18966. name: "altText",
  18967. request: {
  18968. data,
  18969. width,
  18970. height,
  18971. channels: data.length / (width * height)
  18972. }
  18973. });
  18974. if (!response) {
  18975. throw new Error("No response from the AI service.");
  18976. }
  18977. if (response.error) {
  18978. throw new Error("Error from the AI service.");
  18979. }
  18980. if (response.cancel) {
  18981. return null;
  18982. }
  18983. if (!response.output) {
  18984. throw new Error("No valid response from the AI service.");
  18985. }
  18986. const altText = response.output;
  18987. await this.setGuessedAltText(altText);
  18988. if (updateAltTextData && !this.hasAltTextData()) {
  18989. this.altTextData = {
  18990. alt: altText,
  18991. decorative: false
  18992. };
  18993. }
  18994. return altText;
  18995. }
  18996. #getBitmap() {
  18997. if (this.#bitmapId) {
  18998. this._uiManager.enableWaiting(true);
  18999. this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
  19000. return;
  19001. }
  19002. if (this.#bitmapUrl) {
  19003. const url = this.#bitmapUrl;
  19004. this.#bitmapUrl = null;
  19005. this._uiManager.enableWaiting(true);
  19006. this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  19007. return;
  19008. }
  19009. if (this.#bitmapFile) {
  19010. const file = this.#bitmapFile;
  19011. this.#bitmapFile = null;
  19012. this._uiManager.enableWaiting(true);
  19013. this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  19014. return;
  19015. }
  19016. const input = document.createElement("input");
  19017. input.type = "file";
  19018. input.accept = StampEditor.supportedTypesStr;
  19019. const signal = this._uiManager._signal;
  19020. this.#bitmapPromise = new Promise(resolve => {
  19021. input.addEventListener("change", async () => {
  19022. if (!input.files || input.files.length === 0) {
  19023. this.remove();
  19024. } else {
  19025. this._uiManager.enableWaiting(true);
  19026. const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
  19027. this._reportTelemetry({
  19028. action: "pdfjs.image.image_selected",
  19029. data: {
  19030. alt_text_modal: this._uiManager.useNewAltTextFlow
  19031. }
  19032. });
  19033. this.#getBitmapFetched(data);
  19034. }
  19035. resolve();
  19036. }, {
  19037. signal
  19038. });
  19039. input.addEventListener("cancel", () => {
  19040. this.remove();
  19041. resolve();
  19042. }, {
  19043. signal
  19044. });
  19045. }).finally(() => this.#getBitmapDone());
  19046. input.click();
  19047. }
  19048. remove() {
  19049. if (this.#bitmapId) {
  19050. this.#bitmap = null;
  19051. this._uiManager.imageManager.deleteId(this.#bitmapId);
  19052. this.#canvas?.remove();
  19053. this.#canvas = null;
  19054. this.#observer?.disconnect();
  19055. this.#observer = null;
  19056. if (this.#resizeTimeoutId) {
  19057. clearTimeout(this.#resizeTimeoutId);
  19058. this.#resizeTimeoutId = null;
  19059. }
  19060. }
  19061. super.remove();
  19062. }
  19063. rebuild() {
  19064. if (!this.parent) {
  19065. if (this.#bitmapId) {
  19066. this.#getBitmap();
  19067. }
  19068. return;
  19069. }
  19070. super.rebuild();
  19071. if (this.div === null) {
  19072. return;
  19073. }
  19074. if (this.#bitmapId && this.#canvas === null) {
  19075. this.#getBitmap();
  19076. }
  19077. if (!this.isAttachedToDOM) {
  19078. this.parent.add(this);
  19079. }
  19080. }
  19081. onceAdded() {
  19082. this._isDraggable = true;
  19083. this.div.focus();
  19084. }
  19085. isEmpty() {
  19086. return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId);
  19087. }
  19088. get isResizable() {
  19089. return true;
  19090. }
  19091. render() {
  19092. if (this.div) {
  19093. return this.div;
  19094. }
  19095. let baseX, baseY;
  19096. if (this.width) {
  19097. baseX = this.x;
  19098. baseY = this.y;
  19099. }
  19100. super.render();
  19101. this.div.hidden = true;
  19102. this.div.setAttribute("role", "figure");
  19103. this.addAltTextButton();
  19104. if (this.#bitmap) {
  19105. this.#createCanvas();
  19106. } else {
  19107. this.#getBitmap();
  19108. }
  19109. if (this.width && !this.annotationElementId) {
  19110. const [parentWidth, parentHeight] = this.parentDimensions;
  19111. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  19112. }
  19113. return this.div;
  19114. }
  19115. #createCanvas() {
  19116. const {
  19117. div
  19118. } = this;
  19119. let {
  19120. width,
  19121. height
  19122. } = this.#bitmap;
  19123. const [pageWidth, pageHeight] = this.pageDimensions;
  19124. const MAX_RATIO = 0.75;
  19125. if (this.width) {
  19126. width = this.width * pageWidth;
  19127. height = this.height * pageHeight;
  19128. } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
  19129. const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
  19130. width *= factor;
  19131. height *= factor;
  19132. }
  19133. const [parentWidth, parentHeight] = this.parentDimensions;
  19134. this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight);
  19135. this._uiManager.enableWaiting(false);
  19136. const canvas = this.#canvas = document.createElement("canvas");
  19137. canvas.setAttribute("role", "img");
  19138. this.addContainer(canvas);
  19139. if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {
  19140. div.hidden = false;
  19141. }
  19142. this.#drawBitmap(width, height);
  19143. this.#createObserver();
  19144. if (!this.#hasBeenAddedInUndoStack) {
  19145. this.parent.addUndoableEditor(this);
  19146. this.#hasBeenAddedInUndoStack = true;
  19147. }
  19148. this._reportTelemetry({
  19149. action: "inserted_image"
  19150. });
  19151. if (this.#bitmapFileName) {
  19152. canvas.setAttribute("aria-label", this.#bitmapFileName);
  19153. }
  19154. }
  19155. copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {
  19156. if (!maxDataDimension) {
  19157. maxDataDimension = 224;
  19158. }
  19159. const {
  19160. width: bitmapWidth,
  19161. height: bitmapHeight
  19162. } = this.#bitmap;
  19163. const outputScale = new OutputScale();
  19164. let bitmap = this.#bitmap;
  19165. let width = bitmapWidth,
  19166. height = bitmapHeight;
  19167. let canvas = null;
  19168. if (maxPreviewDimension) {
  19169. if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {
  19170. const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);
  19171. width = Math.floor(bitmapWidth * ratio);
  19172. height = Math.floor(bitmapHeight * ratio);
  19173. }
  19174. canvas = document.createElement("canvas");
  19175. const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);
  19176. const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);
  19177. if (!this.#isSvg) {
  19178. bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);
  19179. }
  19180. const ctx = canvas.getContext("2d");
  19181. ctx.filter = this._uiManager.hcmFilter;
  19182. let white = "white",
  19183. black = "#cfcfd8";
  19184. if (this._uiManager.hcmFilter !== "none") {
  19185. black = "black";
  19186. } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
  19187. white = "#8f8f9d";
  19188. black = "#42414d";
  19189. }
  19190. const boxDim = 15;
  19191. const boxDimWidth = boxDim * outputScale.sx;
  19192. const boxDimHeight = boxDim * outputScale.sy;
  19193. const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);
  19194. const patternCtx = pattern.getContext("2d");
  19195. patternCtx.fillStyle = white;
  19196. patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);
  19197. patternCtx.fillStyle = black;
  19198. patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);
  19199. patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);
  19200. ctx.fillStyle = ctx.createPattern(pattern, "repeat");
  19201. ctx.fillRect(0, 0, scaledWidth, scaledHeight);
  19202. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  19203. }
  19204. let imageData = null;
  19205. if (createImageData) {
  19206. let dataWidth, dataHeight;
  19207. if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {
  19208. dataWidth = bitmap.width;
  19209. dataHeight = bitmap.height;
  19210. } else {
  19211. bitmap = this.#bitmap;
  19212. if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {
  19213. const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);
  19214. dataWidth = Math.floor(bitmapWidth * ratio);
  19215. dataHeight = Math.floor(bitmapHeight * ratio);
  19216. if (!this.#isSvg) {
  19217. bitmap = this.#scaleBitmap(dataWidth, dataHeight);
  19218. }
  19219. }
  19220. }
  19221. const offscreen = new OffscreenCanvas(dataWidth, dataHeight);
  19222. const offscreenCtx = offscreen.getContext("2d", {
  19223. willReadFrequently: true
  19224. });
  19225. offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);
  19226. imageData = {
  19227. width: dataWidth,
  19228. height: dataHeight,
  19229. data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data
  19230. };
  19231. }
  19232. return {
  19233. canvas,
  19234. width,
  19235. height,
  19236. imageData
  19237. };
  19238. }
  19239. #setDimensions(width, height) {
  19240. const [parentWidth, parentHeight] = this.parentDimensions;
  19241. this.width = width / parentWidth;
  19242. this.height = height / parentHeight;
  19243. if (this._initialOptions?.isCentered) {
  19244. this.center();
  19245. } else {
  19246. this.fixAndSetPosition();
  19247. }
  19248. this._initialOptions = null;
  19249. if (this.#resizeTimeoutId !== null) {
  19250. clearTimeout(this.#resizeTimeoutId);
  19251. }
  19252. const TIME_TO_WAIT = 200;
  19253. this.#resizeTimeoutId = setTimeout(() => {
  19254. this.#resizeTimeoutId = null;
  19255. this.#drawBitmap(width, height);
  19256. }, TIME_TO_WAIT);
  19257. }
  19258. #scaleBitmap(width, height) {
  19259. const {
  19260. width: bitmapWidth,
  19261. height: bitmapHeight
  19262. } = this.#bitmap;
  19263. let newWidth = bitmapWidth;
  19264. let newHeight = bitmapHeight;
  19265. let bitmap = this.#bitmap;
  19266. while (newWidth > 2 * width || newHeight > 2 * height) {
  19267. const prevWidth = newWidth;
  19268. const prevHeight = newHeight;
  19269. if (newWidth > 2 * width) {
  19270. newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
  19271. }
  19272. if (newHeight > 2 * height) {
  19273. newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
  19274. }
  19275. const offscreen = new OffscreenCanvas(newWidth, newHeight);
  19276. const ctx = offscreen.getContext("2d");
  19277. ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
  19278. bitmap = offscreen.transferToImageBitmap();
  19279. }
  19280. return bitmap;
  19281. }
  19282. #drawBitmap(width, height) {
  19283. const outputScale = new OutputScale();
  19284. const scaledWidth = Math.ceil(width * outputScale.sx);
  19285. const scaledHeight = Math.ceil(height * outputScale.sy);
  19286. const canvas = this.#canvas;
  19287. if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {
  19288. return;
  19289. }
  19290. canvas.width = scaledWidth;
  19291. canvas.height = scaledHeight;
  19292. const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);
  19293. const ctx = canvas.getContext("2d");
  19294. ctx.filter = this._uiManager.hcmFilter;
  19295. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  19296. }
  19297. getImageForAltText() {
  19298. return this.#canvas;
  19299. }
  19300. #serializeBitmap(toUrl) {
  19301. if (toUrl) {
  19302. if (this.#isSvg) {
  19303. const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
  19304. if (url) {
  19305. return url;
  19306. }
  19307. }
  19308. const canvas = document.createElement("canvas");
  19309. ({
  19310. width: canvas.width,
  19311. height: canvas.height
  19312. } = this.#bitmap);
  19313. const ctx = canvas.getContext("2d");
  19314. ctx.drawImage(this.#bitmap, 0, 0);
  19315. return canvas.toDataURL();
  19316. }
  19317. if (this.#isSvg) {
  19318. const [pageWidth, pageHeight] = this.pageDimensions;
  19319. const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
  19320. const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
  19321. const offscreen = new OffscreenCanvas(width, height);
  19322. const ctx = offscreen.getContext("2d");
  19323. ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
  19324. return offscreen.transferToImageBitmap();
  19325. }
  19326. return structuredClone(this.#bitmap);
  19327. }
  19328. #createObserver() {
  19329. if (!this._uiManager._signal) {
  19330. return;
  19331. }
  19332. this.#observer = new ResizeObserver(entries => {
  19333. const rect = entries[0].contentRect;
  19334. if (rect.width && rect.height) {
  19335. this.#setDimensions(rect.width, rect.height);
  19336. }
  19337. });
  19338. this.#observer.observe(this.div);
  19339. this._uiManager._signal.addEventListener("abort", () => {
  19340. this.#observer?.disconnect();
  19341. this.#observer = null;
  19342. }, {
  19343. once: true
  19344. });
  19345. }
  19346. static async deserialize(data, parent, uiManager) {
  19347. let initialData = null;
  19348. if (data instanceof StampAnnotationElement) {
  19349. const {
  19350. data: {
  19351. rect,
  19352. rotation,
  19353. id,
  19354. structParent,
  19355. popupRef
  19356. },
  19357. container,
  19358. parent: {
  19359. page: {
  19360. pageNumber
  19361. }
  19362. }
  19363. } = data;
  19364. const canvas = container.querySelector("canvas");
  19365. const imageData = uiManager.imageManager.getFromCanvas(container.id, canvas);
  19366. canvas.remove();
  19367. const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";
  19368. initialData = data = {
  19369. annotationType: AnnotationEditorType.STAMP,
  19370. bitmapId: imageData.id,
  19371. bitmap: imageData.bitmap,
  19372. pageIndex: pageNumber - 1,
  19373. rect: rect.slice(0),
  19374. rotation,
  19375. id,
  19376. deleted: false,
  19377. accessibilityData: {
  19378. decorative: false,
  19379. altText
  19380. },
  19381. isSvg: false,
  19382. structParent,
  19383. popupRef
  19384. };
  19385. }
  19386. const editor = await super.deserialize(data, parent, uiManager);
  19387. const {
  19388. rect,
  19389. bitmap,
  19390. bitmapUrl,
  19391. bitmapId,
  19392. isSvg,
  19393. accessibilityData
  19394. } = data;
  19395. if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
  19396. editor.#bitmapId = bitmapId;
  19397. if (bitmap) {
  19398. editor.#bitmap = bitmap;
  19399. }
  19400. } else {
  19401. editor.#bitmapUrl = bitmapUrl;
  19402. }
  19403. editor.#isSvg = isSvg;
  19404. const [parentWidth, parentHeight] = editor.pageDimensions;
  19405. editor.width = (rect[2] - rect[0]) / parentWidth;
  19406. editor.height = (rect[3] - rect[1]) / parentHeight;
  19407. editor.annotationElementId = data.id || null;
  19408. if (accessibilityData) {
  19409. editor.altTextData = accessibilityData;
  19410. }
  19411. editor._initialData = initialData;
  19412. editor.#hasBeenAddedInUndoStack = !!initialData;
  19413. return editor;
  19414. }
  19415. serialize(isForCopying = false, context = null) {
  19416. if (this.isEmpty()) {
  19417. return null;
  19418. }
  19419. if (this.deleted) {
  19420. return this.serializeDeleted();
  19421. }
  19422. const serialized = {
  19423. annotationType: AnnotationEditorType.STAMP,
  19424. bitmapId: this.#bitmapId,
  19425. pageIndex: this.pageIndex,
  19426. rect: this.getRect(0, 0),
  19427. rotation: this.rotation,
  19428. isSvg: this.#isSvg,
  19429. structTreeParentId: this._structTreeParentId
  19430. };
  19431. if (isForCopying) {
  19432. serialized.bitmapUrl = this.#serializeBitmap(true);
  19433. serialized.accessibilityData = this.serializeAltText(true);
  19434. return serialized;
  19435. }
  19436. const {
  19437. decorative,
  19438. altText
  19439. } = this.serializeAltText(false);
  19440. if (!decorative && altText) {
  19441. serialized.accessibilityData = {
  19442. type: "Figure",
  19443. alt: altText
  19444. };
  19445. }
  19446. if (this.annotationElementId) {
  19447. const changes = this.#hasElementChanged(serialized);
  19448. if (changes.isSame) {
  19449. return null;
  19450. }
  19451. if (changes.isSameAltText) {
  19452. delete serialized.accessibilityData;
  19453. } else {
  19454. serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;
  19455. }
  19456. }
  19457. serialized.id = this.annotationElementId;
  19458. if (context === null) {
  19459. return serialized;
  19460. }
  19461. context.stamps ||= new Map();
  19462. const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
  19463. if (!context.stamps.has(this.#bitmapId)) {
  19464. context.stamps.set(this.#bitmapId, {
  19465. area,
  19466. serialized
  19467. });
  19468. serialized.bitmap = this.#serializeBitmap(false);
  19469. } else if (this.#isSvg) {
  19470. const prevData = context.stamps.get(this.#bitmapId);
  19471. if (area > prevData.area) {
  19472. prevData.area = area;
  19473. prevData.serialized.bitmap.close();
  19474. prevData.serialized.bitmap = this.#serializeBitmap(false);
  19475. }
  19476. }
  19477. return serialized;
  19478. }
  19479. #hasElementChanged(serialized) {
  19480. const {
  19481. rect,
  19482. pageIndex,
  19483. accessibilityData: {
  19484. altText
  19485. }
  19486. } = this._initialData;
  19487. const isSameRect = serialized.rect.every((x, i) => Math.abs(x - rect[i]) < 1);
  19488. const isSamePageIndex = serialized.pageIndex === pageIndex;
  19489. const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;
  19490. return {
  19491. isSame: isSameRect && isSamePageIndex && isSameAltText,
  19492. isSameAltText
  19493. };
  19494. }
  19495. renderAnnotationElement(annotation) {
  19496. annotation.updateEdited({
  19497. rect: this.getRect(0, 0)
  19498. });
  19499. return null;
  19500. }
  19501. }
  19502. ;// ./src/display/editor/annotation_editor_layer.js
  19503. class AnnotationEditorLayer {
  19504. #accessibilityManager;
  19505. #allowClick = false;
  19506. #annotationLayer = null;
  19507. #clickAC = null;
  19508. #editorFocusTimeoutId = null;
  19509. #editors = new Map();
  19510. #hadPointerDown = false;
  19511. #isCleaningUp = false;
  19512. #isDisabling = false;
  19513. #textLayer = null;
  19514. #textSelectionAC = null;
  19515. #uiManager;
  19516. static _initialized = false;
  19517. static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor].map(type => [type._editorType, type]));
  19518. constructor({
  19519. uiManager,
  19520. pageIndex,
  19521. div,
  19522. structTreeLayer,
  19523. accessibilityManager,
  19524. annotationLayer,
  19525. drawLayer,
  19526. textLayer,
  19527. viewport,
  19528. l10n
  19529. }) {
  19530. const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()];
  19531. if (!AnnotationEditorLayer._initialized) {
  19532. AnnotationEditorLayer._initialized = true;
  19533. for (const editorType of editorTypes) {
  19534. editorType.initialize(l10n, uiManager);
  19535. }
  19536. }
  19537. uiManager.registerEditorTypes(editorTypes);
  19538. this.#uiManager = uiManager;
  19539. this.pageIndex = pageIndex;
  19540. this.div = div;
  19541. this.#accessibilityManager = accessibilityManager;
  19542. this.#annotationLayer = annotationLayer;
  19543. this.viewport = viewport;
  19544. this.#textLayer = textLayer;
  19545. this.drawLayer = drawLayer;
  19546. this._structTree = structTreeLayer;
  19547. this.#uiManager.addLayer(this);
  19548. }
  19549. get isEmpty() {
  19550. return this.#editors.size === 0;
  19551. }
  19552. get isInvisible() {
  19553. return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
  19554. }
  19555. updateToolbar(mode) {
  19556. this.#uiManager.updateToolbar(mode);
  19557. }
  19558. updateMode(mode = this.#uiManager.getMode()) {
  19559. this.#cleanup();
  19560. switch (mode) {
  19561. case AnnotationEditorType.NONE:
  19562. this.disableTextSelection();
  19563. this.togglePointerEvents(false);
  19564. this.toggleAnnotationLayerPointerEvents(true);
  19565. this.disableClick();
  19566. return;
  19567. case AnnotationEditorType.INK:
  19568. this.addInkEditorIfNeeded(false);
  19569. this.disableTextSelection();
  19570. this.togglePointerEvents(true);
  19571. this.disableClick();
  19572. break;
  19573. case AnnotationEditorType.HIGHLIGHT:
  19574. this.enableTextSelection();
  19575. this.togglePointerEvents(false);
  19576. this.disableClick();
  19577. break;
  19578. default:
  19579. this.disableTextSelection();
  19580. this.togglePointerEvents(true);
  19581. this.enableClick();
  19582. }
  19583. this.toggleAnnotationLayerPointerEvents(false);
  19584. const {
  19585. classList
  19586. } = this.div;
  19587. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  19588. classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
  19589. }
  19590. this.div.hidden = false;
  19591. }
  19592. hasTextLayer(textLayer) {
  19593. return textLayer === this.#textLayer?.div;
  19594. }
  19595. addInkEditorIfNeeded(isCommitting) {
  19596. if (this.#uiManager.getMode() !== AnnotationEditorType.INK) {
  19597. return;
  19598. }
  19599. if (!isCommitting) {
  19600. for (const editor of this.#editors.values()) {
  19601. if (editor.isEmpty()) {
  19602. editor.setInBackground();
  19603. return;
  19604. }
  19605. }
  19606. }
  19607. const editor = this.createAndAddNewEditor({
  19608. offsetX: 0,
  19609. offsetY: 0
  19610. }, false);
  19611. editor.setInBackground();
  19612. }
  19613. setEditingState(isEditing) {
  19614. this.#uiManager.setEditingState(isEditing);
  19615. }
  19616. addCommands(params) {
  19617. this.#uiManager.addCommands(params);
  19618. }
  19619. toggleDrawing(enabled = false) {
  19620. this.div.classList.toggle("drawing", !enabled);
  19621. }
  19622. togglePointerEvents(enabled = false) {
  19623. this.div.classList.toggle("disabled", !enabled);
  19624. }
  19625. toggleAnnotationLayerPointerEvents(enabled = false) {
  19626. this.#annotationLayer?.div.classList.toggle("disabled", !enabled);
  19627. }
  19628. async enable() {
  19629. this.div.tabIndex = 0;
  19630. this.togglePointerEvents(true);
  19631. const annotationElementIds = new Set();
  19632. for (const editor of this.#editors.values()) {
  19633. editor.enableEditing();
  19634. editor.show(true);
  19635. if (editor.annotationElementId) {
  19636. this.#uiManager.removeChangedExistingAnnotation(editor);
  19637. annotationElementIds.add(editor.annotationElementId);
  19638. }
  19639. }
  19640. if (!this.#annotationLayer) {
  19641. return;
  19642. }
  19643. const editables = this.#annotationLayer.getEditableAnnotations();
  19644. for (const editable of editables) {
  19645. editable.hide();
  19646. if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
  19647. continue;
  19648. }
  19649. if (annotationElementIds.has(editable.data.id)) {
  19650. continue;
  19651. }
  19652. const editor = await this.deserialize(editable);
  19653. if (!editor) {
  19654. continue;
  19655. }
  19656. this.addOrRebuild(editor);
  19657. editor.enableEditing();
  19658. }
  19659. }
  19660. disable() {
  19661. this.#isDisabling = true;
  19662. this.div.tabIndex = -1;
  19663. this.togglePointerEvents(false);
  19664. const changedAnnotations = new Map();
  19665. const resetAnnotations = new Map();
  19666. for (const editor of this.#editors.values()) {
  19667. editor.disableEditing();
  19668. if (!editor.annotationElementId) {
  19669. continue;
  19670. }
  19671. if (editor.serialize() !== null) {
  19672. changedAnnotations.set(editor.annotationElementId, editor);
  19673. continue;
  19674. } else {
  19675. resetAnnotations.set(editor.annotationElementId, editor);
  19676. }
  19677. this.getEditableAnnotation(editor.annotationElementId)?.show();
  19678. editor.remove();
  19679. }
  19680. if (this.#annotationLayer) {
  19681. const editables = this.#annotationLayer.getEditableAnnotations();
  19682. for (const editable of editables) {
  19683. const {
  19684. id
  19685. } = editable.data;
  19686. if (this.#uiManager.isDeletedAnnotationElement(id)) {
  19687. continue;
  19688. }
  19689. let editor = resetAnnotations.get(id);
  19690. if (editor) {
  19691. editor.resetAnnotationElement(editable);
  19692. editor.show(false);
  19693. editable.show();
  19694. continue;
  19695. }
  19696. editor = changedAnnotations.get(id);
  19697. if (editor) {
  19698. this.#uiManager.addChangedExistingAnnotation(editor);
  19699. if (editor.renderAnnotationElement(editable)) {
  19700. editor.show(false);
  19701. }
  19702. }
  19703. editable.show();
  19704. }
  19705. }
  19706. this.#cleanup();
  19707. if (this.isEmpty) {
  19708. this.div.hidden = true;
  19709. }
  19710. const {
  19711. classList
  19712. } = this.div;
  19713. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  19714. classList.remove(`${editorType._type}Editing`);
  19715. }
  19716. this.disableTextSelection();
  19717. this.toggleAnnotationLayerPointerEvents(true);
  19718. this.#isDisabling = false;
  19719. }
  19720. getEditableAnnotation(id) {
  19721. return this.#annotationLayer?.getEditableAnnotation(id) || null;
  19722. }
  19723. setActiveEditor(editor) {
  19724. const currentActive = this.#uiManager.getActive();
  19725. if (currentActive === editor) {
  19726. return;
  19727. }
  19728. this.#uiManager.setActiveEditor(editor);
  19729. }
  19730. enableTextSelection() {
  19731. this.div.tabIndex = -1;
  19732. if (this.#textLayer?.div && !this.#textSelectionAC) {
  19733. this.#textSelectionAC = new AbortController();
  19734. const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);
  19735. this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {
  19736. signal
  19737. });
  19738. this.#textLayer.div.classList.add("highlighting");
  19739. }
  19740. }
  19741. disableTextSelection() {
  19742. this.div.tabIndex = 0;
  19743. if (this.#textLayer?.div && this.#textSelectionAC) {
  19744. this.#textSelectionAC.abort();
  19745. this.#textSelectionAC = null;
  19746. this.#textLayer.div.classList.remove("highlighting");
  19747. }
  19748. }
  19749. #textLayerPointerDown(event) {
  19750. this.#uiManager.unselectAll();
  19751. const {
  19752. target
  19753. } = event;
  19754. if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {
  19755. const {
  19756. isMac
  19757. } = util_FeatureTest.platform;
  19758. if (event.button !== 0 || event.ctrlKey && isMac) {
  19759. return;
  19760. }
  19761. this.#uiManager.showAllEditors("highlight", true, true);
  19762. this.#textLayer.div.classList.add("free");
  19763. this.toggleDrawing();
  19764. HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {
  19765. target: this.#textLayer.div,
  19766. x: event.x,
  19767. y: event.y
  19768. });
  19769. this.#textLayer.div.addEventListener("pointerup", () => {
  19770. this.#textLayer.div.classList.remove("free");
  19771. this.toggleDrawing(true);
  19772. }, {
  19773. once: true,
  19774. signal: this.#uiManager._signal
  19775. });
  19776. event.preventDefault();
  19777. }
  19778. }
  19779. enableClick() {
  19780. if (this.#clickAC) {
  19781. return;
  19782. }
  19783. this.#clickAC = new AbortController();
  19784. const signal = this.#uiManager.combinedSignal(this.#clickAC);
  19785. this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {
  19786. signal
  19787. });
  19788. this.div.addEventListener("pointerup", this.pointerup.bind(this), {
  19789. signal
  19790. });
  19791. }
  19792. disableClick() {
  19793. this.#clickAC?.abort();
  19794. this.#clickAC = null;
  19795. }
  19796. attach(editor) {
  19797. this.#editors.set(editor.id, editor);
  19798. const {
  19799. annotationElementId
  19800. } = editor;
  19801. if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
  19802. this.#uiManager.removeDeletedAnnotationElement(editor);
  19803. }
  19804. }
  19805. detach(editor) {
  19806. this.#editors.delete(editor.id);
  19807. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  19808. if (!this.#isDisabling && editor.annotationElementId) {
  19809. this.#uiManager.addDeletedAnnotationElement(editor);
  19810. }
  19811. }
  19812. remove(editor) {
  19813. this.detach(editor);
  19814. this.#uiManager.removeEditor(editor);
  19815. editor.div.remove();
  19816. editor.isAttachedToDOM = false;
  19817. if (!this.#isCleaningUp) {
  19818. this.addInkEditorIfNeeded(false);
  19819. }
  19820. }
  19821. changeParent(editor) {
  19822. if (editor.parent === this) {
  19823. return;
  19824. }
  19825. if (editor.parent && editor.annotationElementId) {
  19826. this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
  19827. AnnotationEditor.deleteAnnotationElement(editor);
  19828. editor.annotationElementId = null;
  19829. }
  19830. this.attach(editor);
  19831. editor.parent?.detach(editor);
  19832. editor.setParent(this);
  19833. if (editor.div && editor.isAttachedToDOM) {
  19834. editor.div.remove();
  19835. this.div.append(editor.div);
  19836. }
  19837. }
  19838. add(editor) {
  19839. if (editor.parent === this && editor.isAttachedToDOM) {
  19840. return;
  19841. }
  19842. this.changeParent(editor);
  19843. this.#uiManager.addEditor(editor);
  19844. this.attach(editor);
  19845. if (!editor.isAttachedToDOM) {
  19846. const div = editor.render();
  19847. this.div.append(div);
  19848. editor.isAttachedToDOM = true;
  19849. }
  19850. editor.fixAndSetPosition();
  19851. editor.onceAdded();
  19852. this.#uiManager.addToAnnotationStorage(editor);
  19853. editor._reportTelemetry(editor.telemetryInitialData);
  19854. }
  19855. moveEditorInDOM(editor) {
  19856. if (!editor.isAttachedToDOM) {
  19857. return;
  19858. }
  19859. const {
  19860. activeElement
  19861. } = document;
  19862. if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
  19863. editor._focusEventsAllowed = false;
  19864. this.#editorFocusTimeoutId = setTimeout(() => {
  19865. this.#editorFocusTimeoutId = null;
  19866. if (!editor.div.contains(document.activeElement)) {
  19867. editor.div.addEventListener("focusin", () => {
  19868. editor._focusEventsAllowed = true;
  19869. }, {
  19870. once: true,
  19871. signal: this.#uiManager._signal
  19872. });
  19873. activeElement.focus();
  19874. } else {
  19875. editor._focusEventsAllowed = true;
  19876. }
  19877. }, 0);
  19878. }
  19879. editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  19880. }
  19881. addOrRebuild(editor) {
  19882. if (editor.needsToBeRebuilt()) {
  19883. editor.parent ||= this;
  19884. editor.rebuild();
  19885. editor.show();
  19886. } else {
  19887. this.add(editor);
  19888. }
  19889. }
  19890. addUndoableEditor(editor) {
  19891. const cmd = () => editor._uiManager.rebuild(editor);
  19892. const undo = () => {
  19893. editor.remove();
  19894. };
  19895. this.addCommands({
  19896. cmd,
  19897. undo,
  19898. mustExec: false
  19899. });
  19900. }
  19901. getNextId() {
  19902. return this.#uiManager.getId();
  19903. }
  19904. get #currentEditorType() {
  19905. return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
  19906. }
  19907. combinedSignal(ac) {
  19908. return this.#uiManager.combinedSignal(ac);
  19909. }
  19910. #createNewEditor(params) {
  19911. const editorType = this.#currentEditorType;
  19912. return editorType ? new editorType.prototype.constructor(params) : null;
  19913. }
  19914. canCreateNewEmptyEditor() {
  19915. return this.#currentEditorType?.canCreateNewEmptyEditor();
  19916. }
  19917. pasteEditor(mode, params) {
  19918. this.#uiManager.updateToolbar(mode);
  19919. this.#uiManager.updateMode(mode);
  19920. const {
  19921. offsetX,
  19922. offsetY
  19923. } = this.#getCenterPoint();
  19924. const id = this.getNextId();
  19925. const editor = this.#createNewEditor({
  19926. parent: this,
  19927. id,
  19928. x: offsetX,
  19929. y: offsetY,
  19930. uiManager: this.#uiManager,
  19931. isCentered: true,
  19932. ...params
  19933. });
  19934. if (editor) {
  19935. this.add(editor);
  19936. }
  19937. }
  19938. async deserialize(data) {
  19939. return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null;
  19940. }
  19941. createAndAddNewEditor(event, isCentered, data = {}) {
  19942. const id = this.getNextId();
  19943. const editor = this.#createNewEditor({
  19944. parent: this,
  19945. id,
  19946. x: event.offsetX,
  19947. y: event.offsetY,
  19948. uiManager: this.#uiManager,
  19949. isCentered,
  19950. ...data
  19951. });
  19952. if (editor) {
  19953. this.add(editor);
  19954. }
  19955. return editor;
  19956. }
  19957. #getCenterPoint() {
  19958. const {
  19959. x,
  19960. y,
  19961. width,
  19962. height
  19963. } = this.div.getBoundingClientRect();
  19964. const tlX = Math.max(0, x);
  19965. const tlY = Math.max(0, y);
  19966. const brX = Math.min(window.innerWidth, x + width);
  19967. const brY = Math.min(window.innerHeight, y + height);
  19968. const centerX = (tlX + brX) / 2 - x;
  19969. const centerY = (tlY + brY) / 2 - y;
  19970. const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
  19971. return {
  19972. offsetX,
  19973. offsetY
  19974. };
  19975. }
  19976. addNewEditor() {
  19977. this.createAndAddNewEditor(this.#getCenterPoint(), true);
  19978. }
  19979. setSelected(editor) {
  19980. this.#uiManager.setSelected(editor);
  19981. }
  19982. toggleSelected(editor) {
  19983. this.#uiManager.toggleSelected(editor);
  19984. }
  19985. unselect(editor) {
  19986. this.#uiManager.unselect(editor);
  19987. }
  19988. pointerup(event) {
  19989. const {
  19990. isMac
  19991. } = util_FeatureTest.platform;
  19992. if (event.button !== 0 || event.ctrlKey && isMac) {
  19993. return;
  19994. }
  19995. if (event.target !== this.div) {
  19996. return;
  19997. }
  19998. if (!this.#hadPointerDown) {
  19999. return;
  20000. }
  20001. this.#hadPointerDown = false;
  20002. if (!this.#allowClick) {
  20003. this.#allowClick = true;
  20004. return;
  20005. }
  20006. if (this.#uiManager.getMode() === AnnotationEditorType.STAMP) {
  20007. this.#uiManager.unselectAll();
  20008. return;
  20009. }
  20010. this.createAndAddNewEditor(event, false);
  20011. }
  20012. pointerdown(event) {
  20013. if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
  20014. this.enableTextSelection();
  20015. }
  20016. if (this.#hadPointerDown) {
  20017. this.#hadPointerDown = false;
  20018. return;
  20019. }
  20020. const {
  20021. isMac
  20022. } = util_FeatureTest.platform;
  20023. if (event.button !== 0 || event.ctrlKey && isMac) {
  20024. return;
  20025. }
  20026. if (event.target !== this.div) {
  20027. return;
  20028. }
  20029. this.#hadPointerDown = true;
  20030. const editor = this.#uiManager.getActive();
  20031. this.#allowClick = !editor || editor.isEmpty();
  20032. }
  20033. findNewParent(editor, x, y) {
  20034. const layer = this.#uiManager.findParent(x, y);
  20035. if (layer === null || layer === this) {
  20036. return false;
  20037. }
  20038. layer.changeParent(editor);
  20039. return true;
  20040. }
  20041. destroy() {
  20042. if (this.#uiManager.getActive()?.parent === this) {
  20043. this.#uiManager.commitOrRemove();
  20044. this.#uiManager.setActiveEditor(null);
  20045. }
  20046. if (this.#editorFocusTimeoutId) {
  20047. clearTimeout(this.#editorFocusTimeoutId);
  20048. this.#editorFocusTimeoutId = null;
  20049. }
  20050. for (const editor of this.#editors.values()) {
  20051. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  20052. editor.setParent(null);
  20053. editor.isAttachedToDOM = false;
  20054. editor.div.remove();
  20055. }
  20056. this.div = null;
  20057. this.#editors.clear();
  20058. this.#uiManager.removeLayer(this);
  20059. }
  20060. #cleanup() {
  20061. this.#isCleaningUp = true;
  20062. for (const editor of this.#editors.values()) {
  20063. if (editor.isEmpty()) {
  20064. editor.remove();
  20065. }
  20066. }
  20067. this.#isCleaningUp = false;
  20068. }
  20069. render({
  20070. viewport
  20071. }) {
  20072. this.viewport = viewport;
  20073. setLayerDimensions(this.div, viewport);
  20074. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  20075. this.add(editor);
  20076. editor.rebuild();
  20077. }
  20078. this.updateMode();
  20079. }
  20080. update({
  20081. viewport
  20082. }) {
  20083. this.#uiManager.commitOrRemove();
  20084. this.#cleanup();
  20085. const oldRotation = this.viewport.rotation;
  20086. const rotation = viewport.rotation;
  20087. this.viewport = viewport;
  20088. setLayerDimensions(this.div, {
  20089. rotation
  20090. });
  20091. if (oldRotation !== rotation) {
  20092. for (const editor of this.#editors.values()) {
  20093. editor.rotate(rotation);
  20094. }
  20095. }
  20096. this.addInkEditorIfNeeded(false);
  20097. }
  20098. get pageDimensions() {
  20099. const {
  20100. pageWidth,
  20101. pageHeight
  20102. } = this.viewport.rawDims;
  20103. return [pageWidth, pageHeight];
  20104. }
  20105. get scale() {
  20106. return this.#uiManager.viewParameters.realScale;
  20107. }
  20108. }
  20109. ;// ./src/display/draw_layer.js
  20110. class DrawLayer {
  20111. #parent = null;
  20112. #id = 0;
  20113. #mapping = new Map();
  20114. #toUpdate = new Map();
  20115. constructor({
  20116. pageIndex
  20117. }) {
  20118. this.pageIndex = pageIndex;
  20119. }
  20120. setParent(parent) {
  20121. if (!this.#parent) {
  20122. this.#parent = parent;
  20123. return;
  20124. }
  20125. if (this.#parent !== parent) {
  20126. if (this.#mapping.size > 0) {
  20127. for (const root of this.#mapping.values()) {
  20128. root.remove();
  20129. parent.append(root);
  20130. }
  20131. }
  20132. this.#parent = parent;
  20133. }
  20134. }
  20135. static get _svgFactory() {
  20136. return shadow(this, "_svgFactory", new DOMSVGFactory());
  20137. }
  20138. static #setBox(element, {
  20139. x = 0,
  20140. y = 0,
  20141. width = 1,
  20142. height = 1
  20143. } = {}) {
  20144. const {
  20145. style
  20146. } = element;
  20147. style.top = `${100 * y}%`;
  20148. style.left = `${100 * x}%`;
  20149. style.width = `${100 * width}%`;
  20150. style.height = `${100 * height}%`;
  20151. }
  20152. #createSVG(box) {
  20153. const svg = DrawLayer._svgFactory.create(1, 1, true);
  20154. this.#parent.append(svg);
  20155. svg.setAttribute("aria-hidden", true);
  20156. DrawLayer.#setBox(svg, box);
  20157. return svg;
  20158. }
  20159. #createClipPath(defs, pathId) {
  20160. const clipPath = DrawLayer._svgFactory.createElement("clipPath");
  20161. defs.append(clipPath);
  20162. const clipPathId = `clip_${pathId}`;
  20163. clipPath.setAttribute("id", clipPathId);
  20164. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  20165. const clipPathUse = DrawLayer._svgFactory.createElement("use");
  20166. clipPath.append(clipPathUse);
  20167. clipPathUse.setAttribute("href", `#${pathId}`);
  20168. clipPathUse.classList.add("clip");
  20169. return clipPathId;
  20170. }
  20171. draw(outlines, color, opacity, isPathUpdatable = false) {
  20172. const id = this.#id++;
  20173. const root = this.#createSVG(outlines.box);
  20174. root.classList.add(...outlines.classNamesForDrawing);
  20175. const defs = DrawLayer._svgFactory.createElement("defs");
  20176. root.append(defs);
  20177. const path = DrawLayer._svgFactory.createElement("path");
  20178. defs.append(path);
  20179. const pathId = `path_p${this.pageIndex}_${id}`;
  20180. path.setAttribute("id", pathId);
  20181. path.setAttribute("d", outlines.toSVGPath());
  20182. if (isPathUpdatable) {
  20183. this.#toUpdate.set(id, path);
  20184. }
  20185. const clipPathId = this.#createClipPath(defs, pathId);
  20186. const use = DrawLayer._svgFactory.createElement("use");
  20187. root.append(use);
  20188. root.setAttribute("fill", color);
  20189. root.setAttribute("fill-opacity", opacity);
  20190. use.setAttribute("href", `#${pathId}`);
  20191. this.#mapping.set(id, root);
  20192. return {
  20193. id,
  20194. clipPathId: `url(#${clipPathId})`
  20195. };
  20196. }
  20197. drawOutline(outlines) {
  20198. const id = this.#id++;
  20199. const root = this.#createSVG(outlines.box);
  20200. root.classList.add(...outlines.classNamesForOutlining);
  20201. const defs = DrawLayer._svgFactory.createElement("defs");
  20202. root.append(defs);
  20203. const path = DrawLayer._svgFactory.createElement("path");
  20204. defs.append(path);
  20205. const pathId = `path_p${this.pageIndex}_${id}`;
  20206. path.setAttribute("id", pathId);
  20207. path.setAttribute("d", outlines.toSVGPath());
  20208. path.setAttribute("vector-effect", "non-scaling-stroke");
  20209. let maskId;
  20210. if (outlines.mustRemoveSelfIntersections) {
  20211. const mask = DrawLayer._svgFactory.createElement("mask");
  20212. defs.append(mask);
  20213. maskId = `mask_p${this.pageIndex}_${id}`;
  20214. mask.setAttribute("id", maskId);
  20215. mask.setAttribute("maskUnits", "objectBoundingBox");
  20216. const rect = DrawLayer._svgFactory.createElement("rect");
  20217. mask.append(rect);
  20218. rect.setAttribute("width", "1");
  20219. rect.setAttribute("height", "1");
  20220. rect.setAttribute("fill", "white");
  20221. const use = DrawLayer._svgFactory.createElement("use");
  20222. mask.append(use);
  20223. use.setAttribute("href", `#${pathId}`);
  20224. use.setAttribute("stroke", "none");
  20225. use.setAttribute("fill", "black");
  20226. use.setAttribute("fill-rule", "nonzero");
  20227. use.classList.add("mask");
  20228. }
  20229. const use1 = DrawLayer._svgFactory.createElement("use");
  20230. root.append(use1);
  20231. use1.setAttribute("href", `#${pathId}`);
  20232. if (maskId) {
  20233. use1.setAttribute("mask", `url(#${maskId})`);
  20234. }
  20235. const use2 = use1.cloneNode();
  20236. root.append(use2);
  20237. use1.classList.add("mainOutline");
  20238. use2.classList.add("secondaryOutline");
  20239. this.#mapping.set(id, root);
  20240. return id;
  20241. }
  20242. finalizeLine(id, line) {
  20243. const path = this.#toUpdate.get(id);
  20244. this.#toUpdate.delete(id);
  20245. this.updateBox(id, line.box);
  20246. path.setAttribute("d", line.toSVGPath());
  20247. }
  20248. updateLine(id, line) {
  20249. const root = this.#mapping.get(id);
  20250. const defs = root.firstChild;
  20251. const path = defs.firstChild;
  20252. path.setAttribute("d", line.toSVGPath());
  20253. }
  20254. updatePath(id, line) {
  20255. this.#toUpdate.get(id).setAttribute("d", line.toSVGPath());
  20256. }
  20257. updateBox(id, box) {
  20258. DrawLayer.#setBox(this.#mapping.get(id), box);
  20259. }
  20260. show(id, visible) {
  20261. this.#mapping.get(id).classList.toggle("hidden", !visible);
  20262. }
  20263. rotate(id, angle) {
  20264. this.#mapping.get(id).setAttribute("data-main-rotation", angle);
  20265. }
  20266. changeColor(id, color) {
  20267. this.#mapping.get(id).setAttribute("fill", color);
  20268. }
  20269. changeOpacity(id, opacity) {
  20270. this.#mapping.get(id).setAttribute("fill-opacity", opacity);
  20271. }
  20272. addClass(id, className) {
  20273. this.#mapping.get(id).classList.add(className);
  20274. }
  20275. removeClass(id, className) {
  20276. this.#mapping.get(id).classList.remove(className);
  20277. }
  20278. getSVGRoot(id) {
  20279. return this.#mapping.get(id);
  20280. }
  20281. remove(id) {
  20282. this.#toUpdate.delete(id);
  20283. if (this.#parent === null) {
  20284. return;
  20285. }
  20286. this.#mapping.get(id).remove();
  20287. this.#mapping.delete(id);
  20288. }
  20289. destroy() {
  20290. this.#parent = null;
  20291. for (const root of this.#mapping.values()) {
  20292. root.remove();
  20293. }
  20294. this.#mapping.clear();
  20295. this.#toUpdate.clear();
  20296. }
  20297. }
  20298. ;// ./src/pdf.js
  20299. const pdfjsVersion = "4.8.69";
  20300. const pdfjsBuild = "3634dab10";
  20301. var __webpack_exports__AbortException = __webpack_exports__.AbortException;
  20302. var __webpack_exports__AnnotationEditorLayer = __webpack_exports__.AnnotationEditorLayer;
  20303. var __webpack_exports__AnnotationEditorParamsType = __webpack_exports__.AnnotationEditorParamsType;
  20304. var __webpack_exports__AnnotationEditorType = __webpack_exports__.AnnotationEditorType;
  20305. var __webpack_exports__AnnotationEditorUIManager = __webpack_exports__.AnnotationEditorUIManager;
  20306. var __webpack_exports__AnnotationLayer = __webpack_exports__.AnnotationLayer;
  20307. var __webpack_exports__AnnotationMode = __webpack_exports__.AnnotationMode;
  20308. var __webpack_exports__ColorPicker = __webpack_exports__.ColorPicker;
  20309. var __webpack_exports__DOMSVGFactory = __webpack_exports__.DOMSVGFactory;
  20310. var __webpack_exports__DrawLayer = __webpack_exports__.DrawLayer;
  20311. var __webpack_exports__FeatureTest = __webpack_exports__.FeatureTest;
  20312. var __webpack_exports__GlobalWorkerOptions = __webpack_exports__.GlobalWorkerOptions;
  20313. var __webpack_exports__ImageKind = __webpack_exports__.ImageKind;
  20314. var __webpack_exports__InvalidPDFException = __webpack_exports__.InvalidPDFException;
  20315. var __webpack_exports__MissingPDFException = __webpack_exports__.MissingPDFException;
  20316. var __webpack_exports__OPS = __webpack_exports__.OPS;
  20317. var __webpack_exports__OutputScale = __webpack_exports__.OutputScale;
  20318. var __webpack_exports__PDFDataRangeTransport = __webpack_exports__.PDFDataRangeTransport;
  20319. var __webpack_exports__PDFDateString = __webpack_exports__.PDFDateString;
  20320. var __webpack_exports__PDFWorker = __webpack_exports__.PDFWorker;
  20321. var __webpack_exports__PasswordResponses = __webpack_exports__.PasswordResponses;
  20322. var __webpack_exports__PermissionFlag = __webpack_exports__.PermissionFlag;
  20323. var __webpack_exports__PixelsPerInch = __webpack_exports__.PixelsPerInch;
  20324. var __webpack_exports__RenderingCancelledException = __webpack_exports__.RenderingCancelledException;
  20325. var __webpack_exports__TextLayer = __webpack_exports__.TextLayer;
  20326. var __webpack_exports__UnexpectedResponseException = __webpack_exports__.UnexpectedResponseException;
  20327. var __webpack_exports__Util = __webpack_exports__.Util;
  20328. var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel;
  20329. var __webpack_exports__XfaLayer = __webpack_exports__.XfaLayer;
  20330. var __webpack_exports__build = __webpack_exports__.build;
  20331. var __webpack_exports__createValidAbsoluteUrl = __webpack_exports__.createValidAbsoluteUrl;
  20332. var __webpack_exports__fetchData = __webpack_exports__.fetchData;
  20333. var __webpack_exports__getDocument = __webpack_exports__.getDocument;
  20334. var __webpack_exports__getFilenameFromUrl = __webpack_exports__.getFilenameFromUrl;
  20335. var __webpack_exports__getPdfFilenameFromUrl = __webpack_exports__.getPdfFilenameFromUrl;
  20336. var __webpack_exports__getXfaPageViewport = __webpack_exports__.getXfaPageViewport;
  20337. var __webpack_exports__isDataScheme = __webpack_exports__.isDataScheme;
  20338. var __webpack_exports__isPdfFile = __webpack_exports__.isPdfFile;
  20339. var __webpack_exports__noContextMenu = __webpack_exports__.noContextMenu;
  20340. var __webpack_exports__normalizeUnicode = __webpack_exports__.normalizeUnicode;
  20341. var __webpack_exports__setLayerDimensions = __webpack_exports__.setLayerDimensions;
  20342. var __webpack_exports__shadow = __webpack_exports__.shadow;
  20343. var __webpack_exports__version = __webpack_exports__.version;
  20344. export { __webpack_exports__AbortException as AbortException, __webpack_exports__AnnotationEditorLayer as AnnotationEditorLayer, __webpack_exports__AnnotationEditorParamsType as AnnotationEditorParamsType, __webpack_exports__AnnotationEditorType as AnnotationEditorType, __webpack_exports__AnnotationEditorUIManager as AnnotationEditorUIManager, __webpack_exports__AnnotationLayer as AnnotationLayer, __webpack_exports__AnnotationMode as AnnotationMode, __webpack_exports__ColorPicker as ColorPicker, __webpack_exports__DOMSVGFactory as DOMSVGFactory, __webpack_exports__DrawLayer as DrawLayer, __webpack_exports__FeatureTest as FeatureTest, __webpack_exports__GlobalWorkerOptions as GlobalWorkerOptions, __webpack_exports__ImageKind as ImageKind, __webpack_exports__InvalidPDFException as InvalidPDFException, __webpack_exports__MissingPDFException as MissingPDFException, __webpack_exports__OPS as OPS, __webpack_exports__OutputScale as OutputScale, __webpack_exports__PDFDataRangeTransport as PDFDataRangeTransport, __webpack_exports__PDFDateString as PDFDateString, __webpack_exports__PDFWorker as PDFWorker, __webpack_exports__PasswordResponses as PasswordResponses, __webpack_exports__PermissionFlag as PermissionFlag, __webpack_exports__PixelsPerInch as PixelsPerInch, __webpack_exports__RenderingCancelledException as RenderingCancelledException, __webpack_exports__TextLayer as TextLayer, __webpack_exports__UnexpectedResponseException as UnexpectedResponseException, __webpack_exports__Util as Util, __webpack_exports__VerbosityLevel as VerbosityLevel, __webpack_exports__XfaLayer as XfaLayer, __webpack_exports__build as build, __webpack_exports__createValidAbsoluteUrl as createValidAbsoluteUrl, __webpack_exports__fetchData as fetchData, __webpack_exports__getDocument as getDocument, __webpack_exports__getFilenameFromUrl as getFilenameFromUrl, __webpack_exports__getPdfFilenameFromUrl as getPdfFilenameFromUrl, __webpack_exports__getXfaPageViewport as getXfaPageViewport, __webpack_exports__isDataScheme as isDataScheme, __webpack_exports__isPdfFile as isPdfFile, __webpack_exports__noContextMenu as noContextMenu, __webpack_exports__normalizeUnicode as normalizeUnicode, __webpack_exports__setLayerDimensions as setLayerDimensions, __webpack_exports__shadow as shadow, __webpack_exports__version as version };
  20345. //# sourceMappingURL=pdf.mjs.map