pdf.mjs 643 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576
  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. TouchManager: () => (/* reexport */ TouchManager),
  73. UnexpectedResponseException: () => (/* reexport */ UnexpectedResponseException),
  74. Util: () => (/* reexport */ Util),
  75. VerbosityLevel: () => (/* reexport */ VerbosityLevel),
  76. XfaLayer: () => (/* reexport */ XfaLayer),
  77. build: () => (/* reexport */ build),
  78. createValidAbsoluteUrl: () => (/* reexport */ createValidAbsoluteUrl),
  79. fetchData: () => (/* reexport */ fetchData),
  80. getDocument: () => (/* reexport */ getDocument),
  81. getFilenameFromUrl: () => (/* reexport */ getFilenameFromUrl),
  82. getPdfFilenameFromUrl: () => (/* reexport */ getPdfFilenameFromUrl),
  83. getXfaPageViewport: () => (/* reexport */ getXfaPageViewport),
  84. isDataScheme: () => (/* reexport */ isDataScheme),
  85. isPdfFile: () => (/* reexport */ isPdfFile),
  86. noContextMenu: () => (/* reexport */ noContextMenu),
  87. normalizeUnicode: () => (/* reexport */ normalizeUnicode),
  88. setLayerDimensions: () => (/* reexport */ setLayerDimensions),
  89. shadow: () => (/* reexport */ shadow),
  90. stopEvent: () => (/* reexport */ stopEvent),
  91. version: () => (/* reexport */ version)
  92. });
  93. ;// ./src/shared/util.js
  94. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  95. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  96. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  97. const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
  98. const LINE_FACTOR = 1.35;
  99. const LINE_DESCENT_FACTOR = 0.35;
  100. const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
  101. const RenderingIntentFlag = {
  102. ANY: 0x01,
  103. DISPLAY: 0x02,
  104. PRINT: 0x04,
  105. SAVE: 0x08,
  106. ANNOTATIONS_FORMS: 0x10,
  107. ANNOTATIONS_STORAGE: 0x20,
  108. ANNOTATIONS_DISABLE: 0x40,
  109. IS_EDITING: 0x80,
  110. OPLIST: 0x100
  111. };
  112. const AnnotationMode = {
  113. DISABLE: 0,
  114. ENABLE: 1,
  115. ENABLE_FORMS: 2,
  116. ENABLE_STORAGE: 3
  117. };
  118. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  119. const AnnotationEditorType = {
  120. DISABLE: -1,
  121. NONE: 0,
  122. FREETEXT: 3,
  123. HIGHLIGHT: 9,
  124. STAMP: 13,
  125. INK: 15
  126. };
  127. const AnnotationEditorParamsType = {
  128. RESIZE: 1,
  129. CREATE: 2,
  130. FREETEXT_SIZE: 11,
  131. FREETEXT_COLOR: 12,
  132. FREETEXT_OPACITY: 13,
  133. INK_COLOR: 21,
  134. INK_THICKNESS: 22,
  135. INK_OPACITY: 23,
  136. HIGHLIGHT_COLOR: 31,
  137. HIGHLIGHT_DEFAULT_COLOR: 32,
  138. HIGHLIGHT_THICKNESS: 33,
  139. HIGHLIGHT_FREE: 34,
  140. HIGHLIGHT_SHOW_ALL: 35,
  141. DRAW_STEP: 41
  142. };
  143. const PermissionFlag = {
  144. PRINT: 0x04,
  145. MODIFY_CONTENTS: 0x08,
  146. COPY: 0x10,
  147. MODIFY_ANNOTATIONS: 0x20,
  148. FILL_INTERACTIVE_FORMS: 0x100,
  149. COPY_FOR_ACCESSIBILITY: 0x200,
  150. ASSEMBLE: 0x400,
  151. PRINT_HIGH_QUALITY: 0x800
  152. };
  153. const TextRenderingMode = {
  154. FILL: 0,
  155. STROKE: 1,
  156. FILL_STROKE: 2,
  157. INVISIBLE: 3,
  158. FILL_ADD_TO_PATH: 4,
  159. STROKE_ADD_TO_PATH: 5,
  160. FILL_STROKE_ADD_TO_PATH: 6,
  161. ADD_TO_PATH: 7,
  162. FILL_STROKE_MASK: 3,
  163. ADD_TO_PATH_FLAG: 4
  164. };
  165. const util_ImageKind = {
  166. GRAYSCALE_1BPP: 1,
  167. RGB_24BPP: 2,
  168. RGBA_32BPP: 3
  169. };
  170. const AnnotationType = {
  171. TEXT: 1,
  172. LINK: 2,
  173. FREETEXT: 3,
  174. LINE: 4,
  175. SQUARE: 5,
  176. CIRCLE: 6,
  177. POLYGON: 7,
  178. POLYLINE: 8,
  179. HIGHLIGHT: 9,
  180. UNDERLINE: 10,
  181. SQUIGGLY: 11,
  182. STRIKEOUT: 12,
  183. STAMP: 13,
  184. CARET: 14,
  185. INK: 15,
  186. POPUP: 16,
  187. FILEATTACHMENT: 17,
  188. SOUND: 18,
  189. MOVIE: 19,
  190. WIDGET: 20,
  191. SCREEN: 21,
  192. PRINTERMARK: 22,
  193. TRAPNET: 23,
  194. WATERMARK: 24,
  195. THREED: 25,
  196. REDACT: 26
  197. };
  198. const AnnotationReplyType = {
  199. GROUP: "Group",
  200. REPLY: "R"
  201. };
  202. const AnnotationFlag = {
  203. INVISIBLE: 0x01,
  204. HIDDEN: 0x02,
  205. PRINT: 0x04,
  206. NOZOOM: 0x08,
  207. NOROTATE: 0x10,
  208. NOVIEW: 0x20,
  209. READONLY: 0x40,
  210. LOCKED: 0x80,
  211. TOGGLENOVIEW: 0x100,
  212. LOCKEDCONTENTS: 0x200
  213. };
  214. const AnnotationFieldFlag = {
  215. READONLY: 0x0000001,
  216. REQUIRED: 0x0000002,
  217. NOEXPORT: 0x0000004,
  218. MULTILINE: 0x0001000,
  219. PASSWORD: 0x0002000,
  220. NOTOGGLETOOFF: 0x0004000,
  221. RADIO: 0x0008000,
  222. PUSHBUTTON: 0x0010000,
  223. COMBO: 0x0020000,
  224. EDIT: 0x0040000,
  225. SORT: 0x0080000,
  226. FILESELECT: 0x0100000,
  227. MULTISELECT: 0x0200000,
  228. DONOTSPELLCHECK: 0x0400000,
  229. DONOTSCROLL: 0x0800000,
  230. COMB: 0x1000000,
  231. RICHTEXT: 0x2000000,
  232. RADIOSINUNISON: 0x2000000,
  233. COMMITONSELCHANGE: 0x4000000
  234. };
  235. const AnnotationBorderStyleType = {
  236. SOLID: 1,
  237. DASHED: 2,
  238. BEVELED: 3,
  239. INSET: 4,
  240. UNDERLINE: 5
  241. };
  242. const AnnotationActionEventType = {
  243. E: "Mouse Enter",
  244. X: "Mouse Exit",
  245. D: "Mouse Down",
  246. U: "Mouse Up",
  247. Fo: "Focus",
  248. Bl: "Blur",
  249. PO: "PageOpen",
  250. PC: "PageClose",
  251. PV: "PageVisible",
  252. PI: "PageInvisible",
  253. K: "Keystroke",
  254. F: "Format",
  255. V: "Validate",
  256. C: "Calculate"
  257. };
  258. const DocumentActionEventType = {
  259. WC: "WillClose",
  260. WS: "WillSave",
  261. DS: "DidSave",
  262. WP: "WillPrint",
  263. DP: "DidPrint"
  264. };
  265. const PageActionEventType = {
  266. O: "PageOpen",
  267. C: "PageClose"
  268. };
  269. const VerbosityLevel = {
  270. ERRORS: 0,
  271. WARNINGS: 1,
  272. INFOS: 5
  273. };
  274. const OPS = {
  275. dependency: 1,
  276. setLineWidth: 2,
  277. setLineCap: 3,
  278. setLineJoin: 4,
  279. setMiterLimit: 5,
  280. setDash: 6,
  281. setRenderingIntent: 7,
  282. setFlatness: 8,
  283. setGState: 9,
  284. save: 10,
  285. restore: 11,
  286. transform: 12,
  287. moveTo: 13,
  288. lineTo: 14,
  289. curveTo: 15,
  290. curveTo2: 16,
  291. curveTo3: 17,
  292. closePath: 18,
  293. rectangle: 19,
  294. stroke: 20,
  295. closeStroke: 21,
  296. fill: 22,
  297. eoFill: 23,
  298. fillStroke: 24,
  299. eoFillStroke: 25,
  300. closeFillStroke: 26,
  301. closeEOFillStroke: 27,
  302. endPath: 28,
  303. clip: 29,
  304. eoClip: 30,
  305. beginText: 31,
  306. endText: 32,
  307. setCharSpacing: 33,
  308. setWordSpacing: 34,
  309. setHScale: 35,
  310. setLeading: 36,
  311. setFont: 37,
  312. setTextRenderingMode: 38,
  313. setTextRise: 39,
  314. moveText: 40,
  315. setLeadingMoveText: 41,
  316. setTextMatrix: 42,
  317. nextLine: 43,
  318. showText: 44,
  319. showSpacedText: 45,
  320. nextLineShowText: 46,
  321. nextLineSetSpacingShowText: 47,
  322. setCharWidth: 48,
  323. setCharWidthAndBounds: 49,
  324. setStrokeColorSpace: 50,
  325. setFillColorSpace: 51,
  326. setStrokeColor: 52,
  327. setStrokeColorN: 53,
  328. setFillColor: 54,
  329. setFillColorN: 55,
  330. setStrokeGray: 56,
  331. setFillGray: 57,
  332. setStrokeRGBColor: 58,
  333. setFillRGBColor: 59,
  334. setStrokeCMYKColor: 60,
  335. setFillCMYKColor: 61,
  336. shadingFill: 62,
  337. beginInlineImage: 63,
  338. beginImageData: 64,
  339. endInlineImage: 65,
  340. paintXObject: 66,
  341. markPoint: 67,
  342. markPointProps: 68,
  343. beginMarkedContent: 69,
  344. beginMarkedContentProps: 70,
  345. endMarkedContent: 71,
  346. beginCompat: 72,
  347. endCompat: 73,
  348. paintFormXObjectBegin: 74,
  349. paintFormXObjectEnd: 75,
  350. beginGroup: 76,
  351. endGroup: 77,
  352. beginAnnotation: 80,
  353. endAnnotation: 81,
  354. paintImageMaskXObject: 83,
  355. paintImageMaskXObjectGroup: 84,
  356. paintImageXObject: 85,
  357. paintInlineImageXObject: 86,
  358. paintInlineImageXObjectGroup: 87,
  359. paintImageXObjectRepeat: 88,
  360. paintImageMaskXObjectRepeat: 89,
  361. paintSolidColorImageMask: 90,
  362. constructPath: 91,
  363. setStrokeTransparent: 92,
  364. setFillTransparent: 93
  365. };
  366. const PasswordResponses = {
  367. NEED_PASSWORD: 1,
  368. INCORRECT_PASSWORD: 2
  369. };
  370. let verbosity = VerbosityLevel.WARNINGS;
  371. function setVerbosityLevel(level) {
  372. if (Number.isInteger(level)) {
  373. verbosity = level;
  374. }
  375. }
  376. function getVerbosityLevel() {
  377. return verbosity;
  378. }
  379. function info(msg) {
  380. if (verbosity >= VerbosityLevel.INFOS) {
  381. console.log(`Info: ${msg}`);
  382. }
  383. }
  384. function warn(msg) {
  385. if (verbosity >= VerbosityLevel.WARNINGS) {
  386. console.log(`Warning: ${msg}`);
  387. }
  388. }
  389. function unreachable(msg) {
  390. throw new Error(msg);
  391. }
  392. function assert(cond, msg) {
  393. if (!cond) {
  394. unreachable(msg);
  395. }
  396. }
  397. function _isValidProtocol(url) {
  398. switch (url?.protocol) {
  399. case "http:":
  400. case "https:":
  401. case "ftp:":
  402. case "mailto:":
  403. case "tel:":
  404. return true;
  405. default:
  406. return false;
  407. }
  408. }
  409. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  410. if (!url) {
  411. return null;
  412. }
  413. try {
  414. if (options && typeof url === "string") {
  415. if (options.addDefaultProtocol && url.startsWith("www.")) {
  416. const dots = url.match(/\./g);
  417. if (dots?.length >= 2) {
  418. url = `http://${url}`;
  419. }
  420. }
  421. if (options.tryConvertEncoding) {
  422. try {
  423. url = stringToUTF8String(url);
  424. } catch {}
  425. }
  426. }
  427. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  428. if (_isValidProtocol(absoluteUrl)) {
  429. return absoluteUrl;
  430. }
  431. } catch {}
  432. return null;
  433. }
  434. function shadow(obj, prop, value, nonSerializable = false) {
  435. Object.defineProperty(obj, prop, {
  436. value,
  437. enumerable: !nonSerializable,
  438. configurable: true,
  439. writable: false
  440. });
  441. return value;
  442. }
  443. const BaseException = function BaseExceptionClosure() {
  444. function BaseException(message, name) {
  445. this.message = message;
  446. this.name = name;
  447. }
  448. BaseException.prototype = new Error();
  449. BaseException.constructor = BaseException;
  450. return BaseException;
  451. }();
  452. class PasswordException extends BaseException {
  453. constructor(msg, code) {
  454. super(msg, "PasswordException");
  455. this.code = code;
  456. }
  457. }
  458. class UnknownErrorException extends BaseException {
  459. constructor(msg, details) {
  460. super(msg, "UnknownErrorException");
  461. this.details = details;
  462. }
  463. }
  464. class InvalidPDFException extends BaseException {
  465. constructor(msg) {
  466. super(msg, "InvalidPDFException");
  467. }
  468. }
  469. class MissingPDFException extends BaseException {
  470. constructor(msg) {
  471. super(msg, "MissingPDFException");
  472. }
  473. }
  474. class UnexpectedResponseException extends BaseException {
  475. constructor(msg, status) {
  476. super(msg, "UnexpectedResponseException");
  477. this.status = status;
  478. }
  479. }
  480. class FormatError extends BaseException {
  481. constructor(msg) {
  482. super(msg, "FormatError");
  483. }
  484. }
  485. class AbortException extends BaseException {
  486. constructor(msg) {
  487. super(msg, "AbortException");
  488. }
  489. }
  490. function bytesToString(bytes) {
  491. if (typeof bytes !== "object" || bytes?.length === undefined) {
  492. unreachable("Invalid argument for bytesToString");
  493. }
  494. const length = bytes.length;
  495. const MAX_ARGUMENT_COUNT = 8192;
  496. if (length < MAX_ARGUMENT_COUNT) {
  497. return String.fromCharCode.apply(null, bytes);
  498. }
  499. const strBuf = [];
  500. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  501. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  502. const chunk = bytes.subarray(i, chunkEnd);
  503. strBuf.push(String.fromCharCode.apply(null, chunk));
  504. }
  505. return strBuf.join("");
  506. }
  507. function stringToBytes(str) {
  508. if (typeof str !== "string") {
  509. unreachable("Invalid argument for stringToBytes");
  510. }
  511. const length = str.length;
  512. const bytes = new Uint8Array(length);
  513. for (let i = 0; i < length; ++i) {
  514. bytes[i] = str.charCodeAt(i) & 0xff;
  515. }
  516. return bytes;
  517. }
  518. function string32(value) {
  519. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  520. }
  521. function objectSize(obj) {
  522. return Object.keys(obj).length;
  523. }
  524. function objectFromMap(map) {
  525. const obj = Object.create(null);
  526. for (const [key, value] of map) {
  527. obj[key] = value;
  528. }
  529. return obj;
  530. }
  531. function isLittleEndian() {
  532. const buffer8 = new Uint8Array(4);
  533. buffer8[0] = 1;
  534. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  535. return view32[0] === 1;
  536. }
  537. function isEvalSupported() {
  538. try {
  539. new Function("");
  540. return true;
  541. } catch {
  542. return false;
  543. }
  544. }
  545. class util_FeatureTest {
  546. static get isLittleEndian() {
  547. return shadow(this, "isLittleEndian", isLittleEndian());
  548. }
  549. static get isEvalSupported() {
  550. return shadow(this, "isEvalSupported", isEvalSupported());
  551. }
  552. static get isOffscreenCanvasSupported() {
  553. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  554. }
  555. static get isImageDecoderSupported() {
  556. return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined");
  557. }
  558. static get platform() {
  559. if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") {
  560. return shadow(this, "platform", {
  561. isMac: navigator.platform.includes("Mac"),
  562. isWindows: navigator.platform.includes("Win"),
  563. isFirefox: typeof navigator?.userAgent === "string" && navigator.userAgent.includes("Firefox")
  564. });
  565. }
  566. return shadow(this, "platform", {
  567. isMac: false,
  568. isWindows: false,
  569. isFirefox: false
  570. });
  571. }
  572. static get isCSSRoundSupported() {
  573. return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
  574. }
  575. }
  576. const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));
  577. class Util {
  578. static makeHexColor(r, g, b) {
  579. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  580. }
  581. static scaleMinMax(transform, minMax) {
  582. let temp;
  583. if (transform[0]) {
  584. if (transform[0] < 0) {
  585. temp = minMax[0];
  586. minMax[0] = minMax[2];
  587. minMax[2] = temp;
  588. }
  589. minMax[0] *= transform[0];
  590. minMax[2] *= transform[0];
  591. if (transform[3] < 0) {
  592. temp = minMax[1];
  593. minMax[1] = minMax[3];
  594. minMax[3] = temp;
  595. }
  596. minMax[1] *= transform[3];
  597. minMax[3] *= transform[3];
  598. } else {
  599. temp = minMax[0];
  600. minMax[0] = minMax[1];
  601. minMax[1] = temp;
  602. temp = minMax[2];
  603. minMax[2] = minMax[3];
  604. minMax[3] = temp;
  605. if (transform[1] < 0) {
  606. temp = minMax[1];
  607. minMax[1] = minMax[3];
  608. minMax[3] = temp;
  609. }
  610. minMax[1] *= transform[1];
  611. minMax[3] *= transform[1];
  612. if (transform[2] < 0) {
  613. temp = minMax[0];
  614. minMax[0] = minMax[2];
  615. minMax[2] = temp;
  616. }
  617. minMax[0] *= transform[2];
  618. minMax[2] *= transform[2];
  619. }
  620. minMax[0] += transform[4];
  621. minMax[1] += transform[5];
  622. minMax[2] += transform[4];
  623. minMax[3] += transform[5];
  624. }
  625. static transform(m1, m2) {
  626. 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]];
  627. }
  628. static applyTransform(p, m) {
  629. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  630. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  631. return [xt, yt];
  632. }
  633. static applyInverseTransform(p, m) {
  634. const d = m[0] * m[3] - m[1] * m[2];
  635. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  636. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  637. return [xt, yt];
  638. }
  639. static getAxialAlignedBoundingBox(r, m) {
  640. const p1 = this.applyTransform(r, m);
  641. const p2 = this.applyTransform(r.slice(2, 4), m);
  642. const p3 = this.applyTransform([r[0], r[3]], m);
  643. const p4 = this.applyTransform([r[2], r[1]], m);
  644. 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])];
  645. }
  646. static inverseTransform(m) {
  647. const d = m[0] * m[3] - m[1] * m[2];
  648. 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];
  649. }
  650. static singularValueDecompose2dScale(m) {
  651. const transpose = [m[0], m[2], m[1], m[3]];
  652. const a = m[0] * transpose[0] + m[1] * transpose[2];
  653. const b = m[0] * transpose[1] + m[1] * transpose[3];
  654. const c = m[2] * transpose[0] + m[3] * transpose[2];
  655. const d = m[2] * transpose[1] + m[3] * transpose[3];
  656. const first = (a + d) / 2;
  657. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  658. const sx = first + second || 1;
  659. const sy = first - second || 1;
  660. return [Math.sqrt(sx), Math.sqrt(sy)];
  661. }
  662. static normalizeRect(rect) {
  663. const r = rect.slice(0);
  664. if (rect[0] > rect[2]) {
  665. r[0] = rect[2];
  666. r[2] = rect[0];
  667. }
  668. if (rect[1] > rect[3]) {
  669. r[1] = rect[3];
  670. r[3] = rect[1];
  671. }
  672. return r;
  673. }
  674. static intersect(rect1, rect2) {
  675. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  676. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  677. if (xLow > xHigh) {
  678. return null;
  679. }
  680. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  681. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  682. if (yLow > yHigh) {
  683. return null;
  684. }
  685. return [xLow, yLow, xHigh, yHigh];
  686. }
  687. static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {
  688. if (t <= 0 || t >= 1) {
  689. return;
  690. }
  691. const mt = 1 - t;
  692. const tt = t * t;
  693. const ttt = tt * t;
  694. const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;
  695. const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;
  696. minMax[0] = Math.min(minMax[0], x);
  697. minMax[1] = Math.min(minMax[1], y);
  698. minMax[2] = Math.max(minMax[2], x);
  699. minMax[3] = Math.max(minMax[3], y);
  700. }
  701. static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {
  702. if (Math.abs(a) < 1e-12) {
  703. if (Math.abs(b) >= 1e-12) {
  704. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);
  705. }
  706. return;
  707. }
  708. const delta = b ** 2 - 4 * c * a;
  709. if (delta < 0) {
  710. return;
  711. }
  712. const sqrtDelta = Math.sqrt(delta);
  713. const a2 = 2 * a;
  714. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);
  715. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);
  716. }
  717. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  718. if (minMax) {
  719. minMax[0] = Math.min(minMax[0], x0, x3);
  720. minMax[1] = Math.min(minMax[1], y0, y3);
  721. minMax[2] = Math.max(minMax[2], x0, x3);
  722. minMax[3] = Math.max(minMax[3], y0, y3);
  723. } else {
  724. minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)];
  725. }
  726. 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);
  727. 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);
  728. return minMax;
  729. }
  730. }
  731. 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]));
  732. function stringToPDFString(str) {
  733. if (str[0] >= "\xEF") {
  734. let encoding;
  735. if (str[0] === "\xFE" && str[1] === "\xFF") {
  736. encoding = "utf-16be";
  737. if (str.length % 2 === 1) {
  738. str = str.slice(0, -1);
  739. }
  740. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  741. encoding = "utf-16le";
  742. if (str.length % 2 === 1) {
  743. str = str.slice(0, -1);
  744. }
  745. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  746. encoding = "utf-8";
  747. }
  748. if (encoding) {
  749. try {
  750. const decoder = new TextDecoder(encoding, {
  751. fatal: true
  752. });
  753. const buffer = stringToBytes(str);
  754. const decoded = decoder.decode(buffer);
  755. if (!decoded.includes("\x1b")) {
  756. return decoded;
  757. }
  758. return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, "");
  759. } catch (ex) {
  760. warn(`stringToPDFString: "${ex}".`);
  761. }
  762. }
  763. }
  764. const strBuf = [];
  765. for (let i = 0, ii = str.length; i < ii; i++) {
  766. const charCode = str.charCodeAt(i);
  767. if (charCode === 0x1b) {
  768. while (++i < ii && str.charCodeAt(i) !== 0x1b) {}
  769. continue;
  770. }
  771. const code = PDFStringTranslateTable[charCode];
  772. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  773. }
  774. return strBuf.join("");
  775. }
  776. function stringToUTF8String(str) {
  777. return decodeURIComponent(escape(str));
  778. }
  779. function utf8StringToString(str) {
  780. return unescape(encodeURIComponent(str));
  781. }
  782. function isArrayEqual(arr1, arr2) {
  783. if (arr1.length !== arr2.length) {
  784. return false;
  785. }
  786. for (let i = 0, ii = arr1.length; i < ii; i++) {
  787. if (arr1[i] !== arr2[i]) {
  788. return false;
  789. }
  790. }
  791. return true;
  792. }
  793. function getModificationDate(date = new Date()) {
  794. 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")];
  795. return buffer.join("");
  796. }
  797. let NormalizeRegex = null;
  798. let NormalizationMap = null;
  799. function normalizeUnicode(str) {
  800. if (!NormalizeRegex) {
  801. 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;
  802. NormalizationMap = new Map([["ſt", "ſt"]]);
  803. }
  804. return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));
  805. }
  806. function getUuid() {
  807. if (typeof crypto.randomUUID === "function") {
  808. return crypto.randomUUID();
  809. }
  810. const buf = new Uint8Array(32);
  811. crypto.getRandomValues(buf);
  812. return bytesToString(buf);
  813. }
  814. const AnnotationPrefix = "pdfjs_internal_id_";
  815. function toHexUtil(arr) {
  816. if (Uint8Array.prototype.toHex) {
  817. return arr.toHex();
  818. }
  819. return Array.from(arr, num => hexNumbers[num]).join("");
  820. }
  821. function toBase64Util(arr) {
  822. if (Uint8Array.prototype.toBase64) {
  823. return arr.toBase64();
  824. }
  825. return btoa(bytesToString(arr));
  826. }
  827. function fromBase64Util(str) {
  828. if (Uint8Array.fromBase64) {
  829. return Uint8Array.fromBase64(str);
  830. }
  831. return stringToBytes(atob(str));
  832. }
  833. if (typeof Promise.try !== "function") {
  834. Promise.try = function (fn, ...args) {
  835. return new Promise(resolve => {
  836. resolve(fn(...args));
  837. });
  838. };
  839. }
  840. ;// ./src/display/display_utils.js
  841. const SVG_NS = "http://www.w3.org/2000/svg";
  842. class PixelsPerInch {
  843. static CSS = 96.0;
  844. static PDF = 72.0;
  845. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  846. }
  847. async function fetchData(url, type = "text") {
  848. if (isValidFetchUrl(url, document.baseURI)) {
  849. const response = await fetch(url);
  850. if (!response.ok) {
  851. throw new Error(response.statusText);
  852. }
  853. switch (type) {
  854. case "arraybuffer":
  855. return response.arrayBuffer();
  856. case "blob":
  857. return response.blob();
  858. case "json":
  859. return response.json();
  860. }
  861. return response.text();
  862. }
  863. return new Promise((resolve, reject) => {
  864. const request = new XMLHttpRequest();
  865. request.open("GET", url, true);
  866. request.responseType = type;
  867. request.onreadystatechange = () => {
  868. if (request.readyState !== XMLHttpRequest.DONE) {
  869. return;
  870. }
  871. if (request.status === 200 || request.status === 0) {
  872. switch (type) {
  873. case "arraybuffer":
  874. case "blob":
  875. case "json":
  876. resolve(request.response);
  877. return;
  878. }
  879. resolve(request.responseText);
  880. return;
  881. }
  882. reject(new Error(request.statusText));
  883. };
  884. request.send(null);
  885. });
  886. }
  887. class PageViewport {
  888. constructor({
  889. viewBox,
  890. userUnit,
  891. scale,
  892. rotation,
  893. offsetX = 0,
  894. offsetY = 0,
  895. dontFlip = false
  896. }) {
  897. this.viewBox = viewBox;
  898. this.userUnit = userUnit;
  899. this.scale = scale;
  900. this.rotation = rotation;
  901. this.offsetX = offsetX;
  902. this.offsetY = offsetY;
  903. scale *= userUnit;
  904. const centerX = (viewBox[2] + viewBox[0]) / 2;
  905. const centerY = (viewBox[3] + viewBox[1]) / 2;
  906. let rotateA, rotateB, rotateC, rotateD;
  907. rotation %= 360;
  908. if (rotation < 0) {
  909. rotation += 360;
  910. }
  911. switch (rotation) {
  912. case 180:
  913. rotateA = -1;
  914. rotateB = 0;
  915. rotateC = 0;
  916. rotateD = 1;
  917. break;
  918. case 90:
  919. rotateA = 0;
  920. rotateB = 1;
  921. rotateC = 1;
  922. rotateD = 0;
  923. break;
  924. case 270:
  925. rotateA = 0;
  926. rotateB = -1;
  927. rotateC = -1;
  928. rotateD = 0;
  929. break;
  930. case 0:
  931. rotateA = 1;
  932. rotateB = 0;
  933. rotateC = 0;
  934. rotateD = -1;
  935. break;
  936. default:
  937. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  938. }
  939. if (dontFlip) {
  940. rotateC = -rotateC;
  941. rotateD = -rotateD;
  942. }
  943. let offsetCanvasX, offsetCanvasY;
  944. let width, height;
  945. if (rotateA === 0) {
  946. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  947. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  948. width = (viewBox[3] - viewBox[1]) * scale;
  949. height = (viewBox[2] - viewBox[0]) * scale;
  950. } else {
  951. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  952. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  953. width = (viewBox[2] - viewBox[0]) * scale;
  954. height = (viewBox[3] - viewBox[1]) * scale;
  955. }
  956. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  957. this.width = width;
  958. this.height = height;
  959. }
  960. get rawDims() {
  961. const {
  962. userUnit,
  963. viewBox
  964. } = this;
  965. const dims = viewBox.map(x => x * userUnit);
  966. return shadow(this, "rawDims", {
  967. pageWidth: dims[2] - dims[0],
  968. pageHeight: dims[3] - dims[1],
  969. pageX: dims[0],
  970. pageY: dims[1]
  971. });
  972. }
  973. clone({
  974. scale = this.scale,
  975. rotation = this.rotation,
  976. offsetX = this.offsetX,
  977. offsetY = this.offsetY,
  978. dontFlip = false
  979. } = {}) {
  980. return new PageViewport({
  981. viewBox: this.viewBox.slice(),
  982. userUnit: this.userUnit,
  983. scale,
  984. rotation,
  985. offsetX,
  986. offsetY,
  987. dontFlip
  988. });
  989. }
  990. convertToViewportPoint(x, y) {
  991. return Util.applyTransform([x, y], this.transform);
  992. }
  993. convertToViewportRectangle(rect) {
  994. const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);
  995. const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);
  996. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  997. }
  998. convertToPdfPoint(x, y) {
  999. return Util.applyInverseTransform([x, y], this.transform);
  1000. }
  1001. }
  1002. class RenderingCancelledException extends BaseException {
  1003. constructor(msg, extraDelay = 0) {
  1004. super(msg, "RenderingCancelledException");
  1005. this.extraDelay = extraDelay;
  1006. }
  1007. }
  1008. function isDataScheme(url) {
  1009. const ii = url.length;
  1010. let i = 0;
  1011. while (i < ii && url[i].trim() === "") {
  1012. i++;
  1013. }
  1014. return url.substring(i, i + 5).toLowerCase() === "data:";
  1015. }
  1016. function isPdfFile(filename) {
  1017. return typeof filename === "string" && /\.pdf$/i.test(filename);
  1018. }
  1019. function getFilenameFromUrl(url) {
  1020. [url] = url.split(/[#?]/, 1);
  1021. return url.substring(url.lastIndexOf("/") + 1);
  1022. }
  1023. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  1024. if (typeof url !== "string") {
  1025. return defaultFilename;
  1026. }
  1027. if (isDataScheme(url)) {
  1028. warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  1029. return defaultFilename;
  1030. }
  1031. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  1032. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  1033. const splitURI = reURI.exec(url);
  1034. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  1035. if (suggestedFilename) {
  1036. suggestedFilename = suggestedFilename[0];
  1037. if (suggestedFilename.includes("%")) {
  1038. try {
  1039. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  1040. } catch {}
  1041. }
  1042. }
  1043. return suggestedFilename || defaultFilename;
  1044. }
  1045. class StatTimer {
  1046. started = Object.create(null);
  1047. times = [];
  1048. time(name) {
  1049. if (name in this.started) {
  1050. warn(`Timer is already running for ${name}`);
  1051. }
  1052. this.started[name] = Date.now();
  1053. }
  1054. timeEnd(name) {
  1055. if (!(name in this.started)) {
  1056. warn(`Timer has not been started for ${name}`);
  1057. }
  1058. this.times.push({
  1059. name,
  1060. start: this.started[name],
  1061. end: Date.now()
  1062. });
  1063. delete this.started[name];
  1064. }
  1065. toString() {
  1066. const outBuf = [];
  1067. let longest = 0;
  1068. for (const {
  1069. name
  1070. } of this.times) {
  1071. longest = Math.max(name.length, longest);
  1072. }
  1073. for (const {
  1074. name,
  1075. start,
  1076. end
  1077. } of this.times) {
  1078. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  1079. }
  1080. return outBuf.join("");
  1081. }
  1082. }
  1083. function isValidFetchUrl(url, baseUrl) {
  1084. try {
  1085. const {
  1086. protocol
  1087. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  1088. return protocol === "http:" || protocol === "https:";
  1089. } catch {
  1090. return false;
  1091. }
  1092. }
  1093. function noContextMenu(e) {
  1094. e.preventDefault();
  1095. }
  1096. function stopEvent(e) {
  1097. e.preventDefault();
  1098. e.stopPropagation();
  1099. }
  1100. function deprecated(details) {
  1101. console.log("Deprecated API usage: " + details);
  1102. }
  1103. class PDFDateString {
  1104. static #regex;
  1105. static toDateObject(input) {
  1106. if (!input || typeof input !== "string") {
  1107. return null;
  1108. }
  1109. this.#regex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  1110. const matches = this.#regex.exec(input);
  1111. if (!matches) {
  1112. return null;
  1113. }
  1114. const year = parseInt(matches[1], 10);
  1115. let month = parseInt(matches[2], 10);
  1116. month = month >= 1 && month <= 12 ? month - 1 : 0;
  1117. let day = parseInt(matches[3], 10);
  1118. day = day >= 1 && day <= 31 ? day : 1;
  1119. let hour = parseInt(matches[4], 10);
  1120. hour = hour >= 0 && hour <= 23 ? hour : 0;
  1121. let minute = parseInt(matches[5], 10);
  1122. minute = minute >= 0 && minute <= 59 ? minute : 0;
  1123. let second = parseInt(matches[6], 10);
  1124. second = second >= 0 && second <= 59 ? second : 0;
  1125. const universalTimeRelation = matches[7] || "Z";
  1126. let offsetHour = parseInt(matches[8], 10);
  1127. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  1128. let offsetMinute = parseInt(matches[9], 10) || 0;
  1129. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  1130. if (universalTimeRelation === "-") {
  1131. hour += offsetHour;
  1132. minute += offsetMinute;
  1133. } else if (universalTimeRelation === "+") {
  1134. hour -= offsetHour;
  1135. minute -= offsetMinute;
  1136. }
  1137. return new Date(Date.UTC(year, month, day, hour, minute, second));
  1138. }
  1139. }
  1140. function getXfaPageViewport(xfaPage, {
  1141. scale = 1,
  1142. rotation = 0
  1143. }) {
  1144. const {
  1145. width,
  1146. height
  1147. } = xfaPage.attributes.style;
  1148. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  1149. return new PageViewport({
  1150. viewBox,
  1151. userUnit: 1,
  1152. scale,
  1153. rotation
  1154. });
  1155. }
  1156. function getRGB(color) {
  1157. if (color.startsWith("#")) {
  1158. const colorRGB = parseInt(color.slice(1), 16);
  1159. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  1160. }
  1161. if (color.startsWith("rgb(")) {
  1162. return color.slice(4, -1).split(",").map(x => parseInt(x));
  1163. }
  1164. if (color.startsWith("rgba(")) {
  1165. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  1166. }
  1167. warn(`Not a valid color format: "${color}"`);
  1168. return [0, 0, 0];
  1169. }
  1170. function getColorValues(colors) {
  1171. const span = document.createElement("span");
  1172. span.style.visibility = "hidden";
  1173. document.body.append(span);
  1174. for (const name of colors.keys()) {
  1175. span.style.color = name;
  1176. const computedColor = window.getComputedStyle(span).color;
  1177. colors.set(name, getRGB(computedColor));
  1178. }
  1179. span.remove();
  1180. }
  1181. function getCurrentTransform(ctx) {
  1182. const {
  1183. a,
  1184. b,
  1185. c,
  1186. d,
  1187. e,
  1188. f
  1189. } = ctx.getTransform();
  1190. return [a, b, c, d, e, f];
  1191. }
  1192. function getCurrentTransformInverse(ctx) {
  1193. const {
  1194. a,
  1195. b,
  1196. c,
  1197. d,
  1198. e,
  1199. f
  1200. } = ctx.getTransform().invertSelf();
  1201. return [a, b, c, d, e, f];
  1202. }
  1203. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  1204. if (viewport instanceof PageViewport) {
  1205. const {
  1206. pageWidth,
  1207. pageHeight
  1208. } = viewport.rawDims;
  1209. const {
  1210. style
  1211. } = div;
  1212. const useRound = util_FeatureTest.isCSSRoundSupported;
  1213. const w = `var(--scale-factor) * ${pageWidth}px`,
  1214. h = `var(--scale-factor) * ${pageHeight}px`;
  1215. const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x, 1px))` : `calc(${w})`,
  1216. heightStr = useRound ? `round(down, ${h}, var(--scale-round-y, 1px))` : `calc(${h})`;
  1217. if (!mustFlip || viewport.rotation % 180 === 0) {
  1218. style.width = widthStr;
  1219. style.height = heightStr;
  1220. } else {
  1221. style.width = heightStr;
  1222. style.height = widthStr;
  1223. }
  1224. }
  1225. if (mustRotate) {
  1226. div.setAttribute("data-main-rotation", viewport.rotation);
  1227. }
  1228. }
  1229. class OutputScale {
  1230. constructor() {
  1231. const pixelRatio = window.devicePixelRatio || 1;
  1232. this.sx = pixelRatio;
  1233. this.sy = pixelRatio;
  1234. }
  1235. get scaled() {
  1236. return this.sx !== 1 || this.sy !== 1;
  1237. }
  1238. get symmetric() {
  1239. return this.sx === this.sy;
  1240. }
  1241. }
  1242. ;// ./src/display/editor/toolbar.js
  1243. class EditorToolbar {
  1244. #toolbar = null;
  1245. #colorPicker = null;
  1246. #editor;
  1247. #buttons = null;
  1248. #altText = null;
  1249. static #l10nRemove = null;
  1250. constructor(editor) {
  1251. this.#editor = editor;
  1252. EditorToolbar.#l10nRemove ||= Object.freeze({
  1253. freetext: "pdfjs-editor-remove-freetext-button",
  1254. highlight: "pdfjs-editor-remove-highlight-button",
  1255. ink: "pdfjs-editor-remove-ink-button",
  1256. stamp: "pdfjs-editor-remove-stamp-button"
  1257. });
  1258. }
  1259. render() {
  1260. const editToolbar = this.#toolbar = document.createElement("div");
  1261. editToolbar.classList.add("editToolbar", "hidden");
  1262. editToolbar.setAttribute("role", "toolbar");
  1263. const signal = this.#editor._uiManager._signal;
  1264. editToolbar.addEventListener("contextmenu", noContextMenu, {
  1265. signal
  1266. });
  1267. editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, {
  1268. signal
  1269. });
  1270. const buttons = this.#buttons = document.createElement("div");
  1271. buttons.className = "buttons";
  1272. editToolbar.append(buttons);
  1273. const position = this.#editor.toolbarPosition;
  1274. if (position) {
  1275. const {
  1276. style
  1277. } = editToolbar;
  1278. const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
  1279. style.insetInlineEnd = `${100 * x}%`;
  1280. style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
  1281. }
  1282. this.#addDeleteButton();
  1283. return editToolbar;
  1284. }
  1285. get div() {
  1286. return this.#toolbar;
  1287. }
  1288. static #pointerDown(e) {
  1289. e.stopPropagation();
  1290. }
  1291. #focusIn(e) {
  1292. this.#editor._focusEventsAllowed = false;
  1293. stopEvent(e);
  1294. }
  1295. #focusOut(e) {
  1296. this.#editor._focusEventsAllowed = true;
  1297. stopEvent(e);
  1298. }
  1299. #addListenersToElement(element) {
  1300. const signal = this.#editor._uiManager._signal;
  1301. element.addEventListener("focusin", this.#focusIn.bind(this), {
  1302. capture: true,
  1303. signal
  1304. });
  1305. element.addEventListener("focusout", this.#focusOut.bind(this), {
  1306. capture: true,
  1307. signal
  1308. });
  1309. element.addEventListener("contextmenu", noContextMenu, {
  1310. signal
  1311. });
  1312. }
  1313. hide() {
  1314. this.#toolbar.classList.add("hidden");
  1315. this.#colorPicker?.hideDropdown();
  1316. }
  1317. show() {
  1318. this.#toolbar.classList.remove("hidden");
  1319. this.#altText?.shown();
  1320. }
  1321. #addDeleteButton() {
  1322. const {
  1323. editorType,
  1324. _uiManager
  1325. } = this.#editor;
  1326. const button = document.createElement("button");
  1327. button.className = "delete";
  1328. button.tabIndex = 0;
  1329. button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]);
  1330. this.#addListenersToElement(button);
  1331. button.addEventListener("click", e => {
  1332. _uiManager.delete();
  1333. }, {
  1334. signal: _uiManager._signal
  1335. });
  1336. this.#buttons.append(button);
  1337. }
  1338. get #divider() {
  1339. const divider = document.createElement("div");
  1340. divider.className = "divider";
  1341. return divider;
  1342. }
  1343. async addAltText(altText) {
  1344. const button = await altText.render();
  1345. this.#addListenersToElement(button);
  1346. this.#buttons.prepend(button, this.#divider);
  1347. this.#altText = altText;
  1348. }
  1349. addColorPicker(colorPicker) {
  1350. this.#colorPicker = colorPicker;
  1351. const button = colorPicker.renderButton();
  1352. this.#addListenersToElement(button);
  1353. this.#buttons.prepend(button, this.#divider);
  1354. }
  1355. remove() {
  1356. this.#toolbar.remove();
  1357. this.#colorPicker?.destroy();
  1358. this.#colorPicker = null;
  1359. }
  1360. }
  1361. class HighlightToolbar {
  1362. #buttons = null;
  1363. #toolbar = null;
  1364. #uiManager;
  1365. constructor(uiManager) {
  1366. this.#uiManager = uiManager;
  1367. }
  1368. #render() {
  1369. const editToolbar = this.#toolbar = document.createElement("div");
  1370. editToolbar.className = "editToolbar";
  1371. editToolbar.setAttribute("role", "toolbar");
  1372. editToolbar.addEventListener("contextmenu", noContextMenu, {
  1373. signal: this.#uiManager._signal
  1374. });
  1375. const buttons = this.#buttons = document.createElement("div");
  1376. buttons.className = "buttons";
  1377. editToolbar.append(buttons);
  1378. this.#addHighlightButton();
  1379. return editToolbar;
  1380. }
  1381. #getLastPoint(boxes, isLTR) {
  1382. let lastY = 0;
  1383. let lastX = 0;
  1384. for (const box of boxes) {
  1385. const y = box.y + box.height;
  1386. if (y < lastY) {
  1387. continue;
  1388. }
  1389. const x = box.x + (isLTR ? box.width : 0);
  1390. if (y > lastY) {
  1391. lastX = x;
  1392. lastY = y;
  1393. continue;
  1394. }
  1395. if (isLTR) {
  1396. if (x > lastX) {
  1397. lastX = x;
  1398. }
  1399. } else if (x < lastX) {
  1400. lastX = x;
  1401. }
  1402. }
  1403. return [isLTR ? 1 - lastX : lastX, lastY];
  1404. }
  1405. show(parent, boxes, isLTR) {
  1406. const [x, y] = this.#getLastPoint(boxes, isLTR);
  1407. const {
  1408. style
  1409. } = this.#toolbar ||= this.#render();
  1410. parent.append(this.#toolbar);
  1411. style.insetInlineEnd = `${100 * x}%`;
  1412. style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;
  1413. }
  1414. hide() {
  1415. this.#toolbar.remove();
  1416. }
  1417. #addHighlightButton() {
  1418. const button = document.createElement("button");
  1419. button.className = "highlightButton";
  1420. button.tabIndex = 0;
  1421. button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`);
  1422. const span = document.createElement("span");
  1423. button.append(span);
  1424. span.className = "visuallyHidden";
  1425. span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label");
  1426. const signal = this.#uiManager._signal;
  1427. button.addEventListener("contextmenu", noContextMenu, {
  1428. signal
  1429. });
  1430. button.addEventListener("click", () => {
  1431. this.#uiManager.highlightSelection("floating_button");
  1432. }, {
  1433. signal
  1434. });
  1435. this.#buttons.append(button);
  1436. }
  1437. }
  1438. ;// ./src/display/editor/tools.js
  1439. function bindEvents(obj, element, names) {
  1440. for (const name of names) {
  1441. element.addEventListener(name, obj[name].bind(obj));
  1442. }
  1443. }
  1444. function opacityToHex(opacity) {
  1445. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  1446. }
  1447. class IdManager {
  1448. #id = 0;
  1449. get id() {
  1450. return `${AnnotationEditorPrefix}${this.#id++}`;
  1451. }
  1452. }
  1453. class ImageManager {
  1454. #baseId = getUuid();
  1455. #id = 0;
  1456. #cache = null;
  1457. static get _isSVGFittingCanvas() {
  1458. 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>`;
  1459. const canvas = new OffscreenCanvas(1, 3);
  1460. const ctx = canvas.getContext("2d", {
  1461. willReadFrequently: true
  1462. });
  1463. const image = new Image();
  1464. image.src = svg;
  1465. const promise = image.decode().then(() => {
  1466. ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
  1467. return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
  1468. });
  1469. return shadow(this, "_isSVGFittingCanvas", promise);
  1470. }
  1471. async #get(key, rawData) {
  1472. this.#cache ||= new Map();
  1473. let data = this.#cache.get(key);
  1474. if (data === null) {
  1475. return null;
  1476. }
  1477. if (data?.bitmap) {
  1478. data.refCounter += 1;
  1479. return data;
  1480. }
  1481. try {
  1482. data ||= {
  1483. bitmap: null,
  1484. id: `image_${this.#baseId}_${this.#id++}`,
  1485. refCounter: 0,
  1486. isSvg: false
  1487. };
  1488. let image;
  1489. if (typeof rawData === "string") {
  1490. data.url = rawData;
  1491. image = await fetchData(rawData, "blob");
  1492. } else if (rawData instanceof File) {
  1493. image = data.file = rawData;
  1494. } else if (rawData instanceof Blob) {
  1495. image = rawData;
  1496. }
  1497. if (image.type === "image/svg+xml") {
  1498. const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;
  1499. const fileReader = new FileReader();
  1500. const imageElement = new Image();
  1501. const imagePromise = new Promise((resolve, reject) => {
  1502. imageElement.onload = () => {
  1503. data.bitmap = imageElement;
  1504. data.isSvg = true;
  1505. resolve();
  1506. };
  1507. fileReader.onload = async () => {
  1508. const url = data.svgUrl = fileReader.result;
  1509. imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;
  1510. };
  1511. imageElement.onerror = fileReader.onerror = reject;
  1512. });
  1513. fileReader.readAsDataURL(image);
  1514. await imagePromise;
  1515. } else {
  1516. data.bitmap = await createImageBitmap(image);
  1517. }
  1518. data.refCounter = 1;
  1519. } catch (e) {
  1520. warn(e);
  1521. data = null;
  1522. }
  1523. this.#cache.set(key, data);
  1524. if (data) {
  1525. this.#cache.set(data.id, data);
  1526. }
  1527. return data;
  1528. }
  1529. async getFromFile(file) {
  1530. const {
  1531. lastModified,
  1532. name,
  1533. size,
  1534. type
  1535. } = file;
  1536. return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
  1537. }
  1538. async getFromUrl(url) {
  1539. return this.#get(url, url);
  1540. }
  1541. async getFromBlob(id, blobPromise) {
  1542. const blob = await blobPromise;
  1543. return this.#get(id, blob);
  1544. }
  1545. async getFromId(id) {
  1546. this.#cache ||= new Map();
  1547. const data = this.#cache.get(id);
  1548. if (!data) {
  1549. return null;
  1550. }
  1551. if (data.bitmap) {
  1552. data.refCounter += 1;
  1553. return data;
  1554. }
  1555. if (data.file) {
  1556. return this.getFromFile(data.file);
  1557. }
  1558. if (data.blobPromise) {
  1559. const {
  1560. blobPromise
  1561. } = data;
  1562. delete data.blobPromise;
  1563. return this.getFromBlob(data.id, blobPromise);
  1564. }
  1565. return this.getFromUrl(data.url);
  1566. }
  1567. getFromCanvas(id, canvas) {
  1568. this.#cache ||= new Map();
  1569. let data = this.#cache.get(id);
  1570. if (data?.bitmap) {
  1571. data.refCounter += 1;
  1572. return data;
  1573. }
  1574. const offscreen = new OffscreenCanvas(canvas.width, canvas.height);
  1575. const ctx = offscreen.getContext("2d");
  1576. ctx.drawImage(canvas, 0, 0);
  1577. data = {
  1578. bitmap: offscreen.transferToImageBitmap(),
  1579. id: `image_${this.#baseId}_${this.#id++}`,
  1580. refCounter: 1,
  1581. isSvg: false
  1582. };
  1583. this.#cache.set(id, data);
  1584. this.#cache.set(data.id, data);
  1585. return data;
  1586. }
  1587. getSvgUrl(id) {
  1588. const data = this.#cache.get(id);
  1589. if (!data?.isSvg) {
  1590. return null;
  1591. }
  1592. return data.svgUrl;
  1593. }
  1594. deleteId(id) {
  1595. this.#cache ||= new Map();
  1596. const data = this.#cache.get(id);
  1597. if (!data) {
  1598. return;
  1599. }
  1600. data.refCounter -= 1;
  1601. if (data.refCounter !== 0) {
  1602. return;
  1603. }
  1604. const {
  1605. bitmap
  1606. } = data;
  1607. if (!data.url && !data.file) {
  1608. const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
  1609. const ctx = canvas.getContext("bitmaprenderer");
  1610. ctx.transferFromImageBitmap(bitmap);
  1611. data.blobPromise = canvas.convertToBlob();
  1612. }
  1613. bitmap.close?.();
  1614. data.bitmap = null;
  1615. }
  1616. isValidId(id) {
  1617. return id.startsWith(`image_${this.#baseId}_`);
  1618. }
  1619. }
  1620. class CommandManager {
  1621. #commands = [];
  1622. #locked = false;
  1623. #maxSize;
  1624. #position = -1;
  1625. constructor(maxSize = 128) {
  1626. this.#maxSize = maxSize;
  1627. }
  1628. add({
  1629. cmd,
  1630. undo,
  1631. post,
  1632. mustExec,
  1633. type = NaN,
  1634. overwriteIfSameType = false,
  1635. keepUndo = false
  1636. }) {
  1637. if (mustExec) {
  1638. cmd();
  1639. }
  1640. if (this.#locked) {
  1641. return;
  1642. }
  1643. const save = {
  1644. cmd,
  1645. undo,
  1646. post,
  1647. type
  1648. };
  1649. if (this.#position === -1) {
  1650. if (this.#commands.length > 0) {
  1651. this.#commands.length = 0;
  1652. }
  1653. this.#position = 0;
  1654. this.#commands.push(save);
  1655. return;
  1656. }
  1657. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  1658. if (keepUndo) {
  1659. save.undo = this.#commands[this.#position].undo;
  1660. }
  1661. this.#commands[this.#position] = save;
  1662. return;
  1663. }
  1664. const next = this.#position + 1;
  1665. if (next === this.#maxSize) {
  1666. this.#commands.splice(0, 1);
  1667. } else {
  1668. this.#position = next;
  1669. if (next < this.#commands.length) {
  1670. this.#commands.splice(next);
  1671. }
  1672. }
  1673. this.#commands.push(save);
  1674. }
  1675. undo() {
  1676. if (this.#position === -1) {
  1677. return;
  1678. }
  1679. this.#locked = true;
  1680. const {
  1681. undo,
  1682. post
  1683. } = this.#commands[this.#position];
  1684. undo();
  1685. post?.();
  1686. this.#locked = false;
  1687. this.#position -= 1;
  1688. }
  1689. redo() {
  1690. if (this.#position < this.#commands.length - 1) {
  1691. this.#position += 1;
  1692. this.#locked = true;
  1693. const {
  1694. cmd,
  1695. post
  1696. } = this.#commands[this.#position];
  1697. cmd();
  1698. post?.();
  1699. this.#locked = false;
  1700. }
  1701. }
  1702. hasSomethingToUndo() {
  1703. return this.#position !== -1;
  1704. }
  1705. hasSomethingToRedo() {
  1706. return this.#position < this.#commands.length - 1;
  1707. }
  1708. cleanType(type) {
  1709. if (this.#position === -1) {
  1710. return;
  1711. }
  1712. for (let i = this.#position; i >= 0; i--) {
  1713. if (this.#commands[i].type !== type) {
  1714. this.#commands.splice(i + 1, this.#position - i);
  1715. this.#position = i;
  1716. return;
  1717. }
  1718. }
  1719. this.#commands.length = 0;
  1720. this.#position = -1;
  1721. }
  1722. destroy() {
  1723. this.#commands = null;
  1724. }
  1725. }
  1726. class KeyboardManager {
  1727. constructor(callbacks) {
  1728. this.buffer = [];
  1729. this.callbacks = new Map();
  1730. this.allKeys = new Set();
  1731. const {
  1732. isMac
  1733. } = util_FeatureTest.platform;
  1734. for (const [keys, callback, options = {}] of callbacks) {
  1735. for (const key of keys) {
  1736. const isMacKey = key.startsWith("mac+");
  1737. if (isMac && isMacKey) {
  1738. this.callbacks.set(key.slice(4), {
  1739. callback,
  1740. options
  1741. });
  1742. this.allKeys.add(key.split("+").at(-1));
  1743. } else if (!isMac && !isMacKey) {
  1744. this.callbacks.set(key, {
  1745. callback,
  1746. options
  1747. });
  1748. this.allKeys.add(key.split("+").at(-1));
  1749. }
  1750. }
  1751. }
  1752. }
  1753. #serialize(event) {
  1754. if (event.altKey) {
  1755. this.buffer.push("alt");
  1756. }
  1757. if (event.ctrlKey) {
  1758. this.buffer.push("ctrl");
  1759. }
  1760. if (event.metaKey) {
  1761. this.buffer.push("meta");
  1762. }
  1763. if (event.shiftKey) {
  1764. this.buffer.push("shift");
  1765. }
  1766. this.buffer.push(event.key);
  1767. const str = this.buffer.join("+");
  1768. this.buffer.length = 0;
  1769. return str;
  1770. }
  1771. exec(self, event) {
  1772. if (!this.allKeys.has(event.key)) {
  1773. return;
  1774. }
  1775. const info = this.callbacks.get(this.#serialize(event));
  1776. if (!info) {
  1777. return;
  1778. }
  1779. const {
  1780. callback,
  1781. options: {
  1782. bubbles = false,
  1783. args = [],
  1784. checker = null
  1785. }
  1786. } = info;
  1787. if (checker && !checker(self, event)) {
  1788. return;
  1789. }
  1790. callback.bind(self, ...args, event)();
  1791. if (!bubbles) {
  1792. stopEvent(event);
  1793. }
  1794. }
  1795. }
  1796. class ColorManager {
  1797. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  1798. get _colors() {
  1799. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  1800. getColorValues(colors);
  1801. return shadow(this, "_colors", colors);
  1802. }
  1803. convert(color) {
  1804. const rgb = getRGB(color);
  1805. if (!window.matchMedia("(forced-colors: active)").matches) {
  1806. return rgb;
  1807. }
  1808. for (const [name, RGB] of this._colors) {
  1809. if (RGB.every((x, i) => x === rgb[i])) {
  1810. return ColorManager._colorsMapping.get(name);
  1811. }
  1812. }
  1813. return rgb;
  1814. }
  1815. getHexCode(name) {
  1816. const rgb = this._colors.get(name);
  1817. if (!rgb) {
  1818. return name;
  1819. }
  1820. return Util.makeHexColor(...rgb);
  1821. }
  1822. }
  1823. class AnnotationEditorUIManager {
  1824. #abortController = new AbortController();
  1825. #activeEditor = null;
  1826. #allEditors = new Map();
  1827. #allLayers = new Map();
  1828. #altTextManager = null;
  1829. #annotationStorage = null;
  1830. #changedExistingAnnotations = null;
  1831. #commandManager = new CommandManager();
  1832. #copyPasteAC = null;
  1833. #currentDrawingSession = null;
  1834. #currentPageIndex = 0;
  1835. #deletedAnnotationsElementIds = new Set();
  1836. #draggingEditors = null;
  1837. #editorTypes = null;
  1838. #editorsToRescale = new Set();
  1839. _editorUndoBar = null;
  1840. #enableHighlightFloatingButton = false;
  1841. #enableUpdatedAddImage = false;
  1842. #enableNewAltTextWhenAddingImage = false;
  1843. #filterFactory = null;
  1844. #focusMainContainerTimeoutId = null;
  1845. #focusManagerAC = null;
  1846. #highlightColors = null;
  1847. #highlightWhenShiftUp = false;
  1848. #highlightToolbar = null;
  1849. #idManager = new IdManager();
  1850. #isEnabled = false;
  1851. #isWaiting = false;
  1852. #keyboardManagerAC = null;
  1853. #lastActiveElement = null;
  1854. #mainHighlightColorPicker = null;
  1855. #mlManager = null;
  1856. #mode = AnnotationEditorType.NONE;
  1857. #selectedEditors = new Set();
  1858. #selectedTextNode = null;
  1859. #pageColors = null;
  1860. #showAllStates = null;
  1861. #previousStates = {
  1862. isEditing: false,
  1863. isEmpty: true,
  1864. hasSomethingToUndo: false,
  1865. hasSomethingToRedo: false,
  1866. hasSelectedEditor: false,
  1867. hasSelectedText: false
  1868. };
  1869. #translation = [0, 0];
  1870. #translationTimeoutId = null;
  1871. #container = null;
  1872. #viewer = null;
  1873. #updateModeCapability = null;
  1874. static TRANSLATE_SMALL = 1;
  1875. static TRANSLATE_BIG = 10;
  1876. static get _keyboardManager() {
  1877. const proto = AnnotationEditorUIManager.prototype;
  1878. const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl();
  1879. const textInputChecker = (_self, {
  1880. target: el
  1881. }) => {
  1882. if (el instanceof HTMLInputElement) {
  1883. const {
  1884. type
  1885. } = el;
  1886. return type !== "text" && type !== "number";
  1887. }
  1888. return true;
  1889. };
  1890. const small = this.TRANSLATE_SMALL;
  1891. const big = this.TRANSLATE_BIG;
  1892. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
  1893. checker: textInputChecker
  1894. }], [["ctrl+z", "mac+meta+z"], proto.undo, {
  1895. checker: textInputChecker
  1896. }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
  1897. checker: textInputChecker
  1898. }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
  1899. checker: textInputChecker
  1900. }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
  1901. checker: (self, {
  1902. target: el
  1903. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled
  1904. }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
  1905. checker: (self, {
  1906. target: el
  1907. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement)
  1908. }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
  1909. args: [-small, 0],
  1910. checker: arrowChecker
  1911. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
  1912. args: [-big, 0],
  1913. checker: arrowChecker
  1914. }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
  1915. args: [small, 0],
  1916. checker: arrowChecker
  1917. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
  1918. args: [big, 0],
  1919. checker: arrowChecker
  1920. }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
  1921. args: [0, -small],
  1922. checker: arrowChecker
  1923. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
  1924. args: [0, -big],
  1925. checker: arrowChecker
  1926. }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
  1927. args: [0, small],
  1928. checker: arrowChecker
  1929. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
  1930. args: [0, big],
  1931. checker: arrowChecker
  1932. }]]));
  1933. }
  1934. constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) {
  1935. const signal = this._signal = this.#abortController.signal;
  1936. this.#container = container;
  1937. this.#viewer = viewer;
  1938. this.#altTextManager = altTextManager;
  1939. this._eventBus = eventBus;
  1940. eventBus._on("editingaction", this.onEditingAction.bind(this), {
  1941. signal
  1942. });
  1943. eventBus._on("pagechanging", this.onPageChanging.bind(this), {
  1944. signal
  1945. });
  1946. eventBus._on("scalechanging", this.onScaleChanging.bind(this), {
  1947. signal
  1948. });
  1949. eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {
  1950. signal
  1951. });
  1952. eventBus._on("setpreference", this.onSetPreference.bind(this), {
  1953. signal
  1954. });
  1955. eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), {
  1956. signal
  1957. });
  1958. this.#addSelectionListener();
  1959. this.#addDragAndDropListeners();
  1960. this.#addKeyboardManager();
  1961. this.#annotationStorage = pdfDocument.annotationStorage;
  1962. this.#filterFactory = pdfDocument.filterFactory;
  1963. this.#pageColors = pageColors;
  1964. this.#highlightColors = highlightColors || null;
  1965. this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
  1966. this.#enableUpdatedAddImage = enableUpdatedAddImage;
  1967. this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;
  1968. this.#mlManager = mlManager || null;
  1969. this.viewParameters = {
  1970. realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
  1971. rotation: 0
  1972. };
  1973. this.isShiftKeyDown = false;
  1974. this._editorUndoBar = editorUndoBar || null;
  1975. this._supportsPinchToZoom = supportsPinchToZoom !== false;
  1976. }
  1977. destroy() {
  1978. this.#updateModeCapability?.resolve();
  1979. this.#updateModeCapability = null;
  1980. this.#abortController?.abort();
  1981. this.#abortController = null;
  1982. this._signal = null;
  1983. for (const layer of this.#allLayers.values()) {
  1984. layer.destroy();
  1985. }
  1986. this.#allLayers.clear();
  1987. this.#allEditors.clear();
  1988. this.#editorsToRescale.clear();
  1989. this.#activeEditor = null;
  1990. this.#selectedEditors.clear();
  1991. this.#commandManager.destroy();
  1992. this.#altTextManager?.destroy();
  1993. this.#highlightToolbar?.hide();
  1994. this.#highlightToolbar = null;
  1995. if (this.#focusMainContainerTimeoutId) {
  1996. clearTimeout(this.#focusMainContainerTimeoutId);
  1997. this.#focusMainContainerTimeoutId = null;
  1998. }
  1999. if (this.#translationTimeoutId) {
  2000. clearTimeout(this.#translationTimeoutId);
  2001. this.#translationTimeoutId = null;
  2002. }
  2003. this._editorUndoBar?.destroy();
  2004. }
  2005. combinedSignal(ac) {
  2006. return AbortSignal.any([this._signal, ac.signal]);
  2007. }
  2008. get mlManager() {
  2009. return this.#mlManager;
  2010. }
  2011. get useNewAltTextFlow() {
  2012. return this.#enableUpdatedAddImage;
  2013. }
  2014. get useNewAltTextWhenAddingImage() {
  2015. return this.#enableNewAltTextWhenAddingImage;
  2016. }
  2017. get hcmFilter() {
  2018. return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
  2019. }
  2020. get direction() {
  2021. return shadow(this, "direction", getComputedStyle(this.#container).direction);
  2022. }
  2023. get highlightColors() {
  2024. return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null);
  2025. }
  2026. get highlightColorNames() {
  2027. return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null);
  2028. }
  2029. setCurrentDrawingSession(layer) {
  2030. if (layer) {
  2031. this.unselectAll();
  2032. this.disableUserSelect(true);
  2033. } else {
  2034. this.disableUserSelect(false);
  2035. }
  2036. this.#currentDrawingSession = layer;
  2037. }
  2038. setMainHighlightColorPicker(colorPicker) {
  2039. this.#mainHighlightColorPicker = colorPicker;
  2040. }
  2041. editAltText(editor, firstTime = false) {
  2042. this.#altTextManager?.editAltText(this, editor, firstTime);
  2043. }
  2044. switchToMode(mode, callback) {
  2045. this._eventBus.on("annotationeditormodechanged", callback, {
  2046. once: true,
  2047. signal: this._signal
  2048. });
  2049. this._eventBus.dispatch("showannotationeditorui", {
  2050. source: this,
  2051. mode
  2052. });
  2053. }
  2054. setPreference(name, value) {
  2055. this._eventBus.dispatch("setpreference", {
  2056. source: this,
  2057. name,
  2058. value
  2059. });
  2060. }
  2061. onSetPreference({
  2062. name,
  2063. value
  2064. }) {
  2065. switch (name) {
  2066. case "enableNewAltTextWhenAddingImage":
  2067. this.#enableNewAltTextWhenAddingImage = value;
  2068. break;
  2069. }
  2070. }
  2071. onPageChanging({
  2072. pageNumber
  2073. }) {
  2074. this.#currentPageIndex = pageNumber - 1;
  2075. }
  2076. focusMainContainer() {
  2077. this.#container.focus();
  2078. }
  2079. findParent(x, y) {
  2080. for (const layer of this.#allLayers.values()) {
  2081. const {
  2082. x: layerX,
  2083. y: layerY,
  2084. width,
  2085. height
  2086. } = layer.div.getBoundingClientRect();
  2087. if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {
  2088. return layer;
  2089. }
  2090. }
  2091. return null;
  2092. }
  2093. disableUserSelect(value = false) {
  2094. this.#viewer.classList.toggle("noUserSelect", value);
  2095. }
  2096. addShouldRescale(editor) {
  2097. this.#editorsToRescale.add(editor);
  2098. }
  2099. removeShouldRescale(editor) {
  2100. this.#editorsToRescale.delete(editor);
  2101. }
  2102. onScaleChanging({
  2103. scale
  2104. }) {
  2105. this.commitOrRemove();
  2106. this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
  2107. for (const editor of this.#editorsToRescale) {
  2108. editor.onScaleChanging();
  2109. }
  2110. this.#currentDrawingSession?.onScaleChanging();
  2111. }
  2112. onRotationChanging({
  2113. pagesRotation
  2114. }) {
  2115. this.commitOrRemove();
  2116. this.viewParameters.rotation = pagesRotation;
  2117. }
  2118. #getAnchorElementForSelection({
  2119. anchorNode
  2120. }) {
  2121. return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
  2122. }
  2123. #getLayerForTextLayer(textLayer) {
  2124. const {
  2125. currentLayer
  2126. } = this;
  2127. if (currentLayer.hasTextLayer(textLayer)) {
  2128. return currentLayer;
  2129. }
  2130. for (const layer of this.#allLayers.values()) {
  2131. if (layer.hasTextLayer(textLayer)) {
  2132. return layer;
  2133. }
  2134. }
  2135. return null;
  2136. }
  2137. highlightSelection(methodOfCreation = "") {
  2138. const selection = document.getSelection();
  2139. if (!selection || selection.isCollapsed) {
  2140. return;
  2141. }
  2142. const {
  2143. anchorNode,
  2144. anchorOffset,
  2145. focusNode,
  2146. focusOffset
  2147. } = selection;
  2148. const text = selection.toString();
  2149. const anchorElement = this.#getAnchorElementForSelection(selection);
  2150. const textLayer = anchorElement.closest(".textLayer");
  2151. const boxes = this.getSelectionBoxes(textLayer);
  2152. if (!boxes) {
  2153. return;
  2154. }
  2155. selection.empty();
  2156. const layer = this.#getLayerForTextLayer(textLayer);
  2157. const isNoneMode = this.#mode === AnnotationEditorType.NONE;
  2158. const callback = () => {
  2159. layer?.createAndAddNewEditor({
  2160. x: 0,
  2161. y: 0
  2162. }, false, {
  2163. methodOfCreation,
  2164. boxes,
  2165. anchorNode,
  2166. anchorOffset,
  2167. focusNode,
  2168. focusOffset,
  2169. text
  2170. });
  2171. if (isNoneMode) {
  2172. this.showAllEditors("highlight", true, true);
  2173. }
  2174. };
  2175. if (isNoneMode) {
  2176. this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);
  2177. return;
  2178. }
  2179. callback();
  2180. }
  2181. #displayHighlightToolbar() {
  2182. const selection = document.getSelection();
  2183. if (!selection || selection.isCollapsed) {
  2184. return;
  2185. }
  2186. const anchorElement = this.#getAnchorElementForSelection(selection);
  2187. const textLayer = anchorElement.closest(".textLayer");
  2188. const boxes = this.getSelectionBoxes(textLayer);
  2189. if (!boxes) {
  2190. return;
  2191. }
  2192. this.#highlightToolbar ||= new HighlightToolbar(this);
  2193. this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr");
  2194. }
  2195. addToAnnotationStorage(editor) {
  2196. if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
  2197. this.#annotationStorage.setValue(editor.id, editor);
  2198. }
  2199. }
  2200. #selectionChange() {
  2201. const selection = document.getSelection();
  2202. if (!selection || selection.isCollapsed) {
  2203. if (this.#selectedTextNode) {
  2204. this.#highlightToolbar?.hide();
  2205. this.#selectedTextNode = null;
  2206. this.#dispatchUpdateStates({
  2207. hasSelectedText: false
  2208. });
  2209. }
  2210. return;
  2211. }
  2212. const {
  2213. anchorNode
  2214. } = selection;
  2215. if (anchorNode === this.#selectedTextNode) {
  2216. return;
  2217. }
  2218. const anchorElement = this.#getAnchorElementForSelection(selection);
  2219. const textLayer = anchorElement.closest(".textLayer");
  2220. if (!textLayer) {
  2221. if (this.#selectedTextNode) {
  2222. this.#highlightToolbar?.hide();
  2223. this.#selectedTextNode = null;
  2224. this.#dispatchUpdateStates({
  2225. hasSelectedText: false
  2226. });
  2227. }
  2228. return;
  2229. }
  2230. this.#highlightToolbar?.hide();
  2231. this.#selectedTextNode = anchorNode;
  2232. this.#dispatchUpdateStates({
  2233. hasSelectedText: true
  2234. });
  2235. if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
  2236. return;
  2237. }
  2238. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  2239. this.showAllEditors("highlight", true, true);
  2240. }
  2241. this.#highlightWhenShiftUp = this.isShiftKeyDown;
  2242. if (!this.isShiftKeyDown) {
  2243. const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;
  2244. activeLayer?.toggleDrawing();
  2245. const ac = new AbortController();
  2246. const signal = this.combinedSignal(ac);
  2247. const pointerup = e => {
  2248. if (e.type === "pointerup" && e.button !== 0) {
  2249. return;
  2250. }
  2251. ac.abort();
  2252. activeLayer?.toggleDrawing(true);
  2253. if (e.type === "pointerup") {
  2254. this.#onSelectEnd("main_toolbar");
  2255. }
  2256. };
  2257. window.addEventListener("pointerup", pointerup, {
  2258. signal
  2259. });
  2260. window.addEventListener("blur", pointerup, {
  2261. signal
  2262. });
  2263. }
  2264. }
  2265. #onSelectEnd(methodOfCreation = "") {
  2266. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  2267. this.highlightSelection(methodOfCreation);
  2268. } else if (this.#enableHighlightFloatingButton) {
  2269. this.#displayHighlightToolbar();
  2270. }
  2271. }
  2272. #addSelectionListener() {
  2273. document.addEventListener("selectionchange", this.#selectionChange.bind(this), {
  2274. signal: this._signal
  2275. });
  2276. }
  2277. #addFocusManager() {
  2278. if (this.#focusManagerAC) {
  2279. return;
  2280. }
  2281. this.#focusManagerAC = new AbortController();
  2282. const signal = this.combinedSignal(this.#focusManagerAC);
  2283. window.addEventListener("focus", this.focus.bind(this), {
  2284. signal
  2285. });
  2286. window.addEventListener("blur", this.blur.bind(this), {
  2287. signal
  2288. });
  2289. }
  2290. #removeFocusManager() {
  2291. this.#focusManagerAC?.abort();
  2292. this.#focusManagerAC = null;
  2293. }
  2294. blur() {
  2295. this.isShiftKeyDown = false;
  2296. if (this.#highlightWhenShiftUp) {
  2297. this.#highlightWhenShiftUp = false;
  2298. this.#onSelectEnd("main_toolbar");
  2299. }
  2300. if (!this.hasSelection) {
  2301. return;
  2302. }
  2303. const {
  2304. activeElement
  2305. } = document;
  2306. for (const editor of this.#selectedEditors) {
  2307. if (editor.div.contains(activeElement)) {
  2308. this.#lastActiveElement = [editor, activeElement];
  2309. editor._focusEventsAllowed = false;
  2310. break;
  2311. }
  2312. }
  2313. }
  2314. focus() {
  2315. if (!this.#lastActiveElement) {
  2316. return;
  2317. }
  2318. const [lastEditor, lastActiveElement] = this.#lastActiveElement;
  2319. this.#lastActiveElement = null;
  2320. lastActiveElement.addEventListener("focusin", () => {
  2321. lastEditor._focusEventsAllowed = true;
  2322. }, {
  2323. once: true,
  2324. signal: this._signal
  2325. });
  2326. lastActiveElement.focus();
  2327. }
  2328. #addKeyboardManager() {
  2329. if (this.#keyboardManagerAC) {
  2330. return;
  2331. }
  2332. this.#keyboardManagerAC = new AbortController();
  2333. const signal = this.combinedSignal(this.#keyboardManagerAC);
  2334. window.addEventListener("keydown", this.keydown.bind(this), {
  2335. signal
  2336. });
  2337. window.addEventListener("keyup", this.keyup.bind(this), {
  2338. signal
  2339. });
  2340. }
  2341. #removeKeyboardManager() {
  2342. this.#keyboardManagerAC?.abort();
  2343. this.#keyboardManagerAC = null;
  2344. }
  2345. #addCopyPasteListeners() {
  2346. if (this.#copyPasteAC) {
  2347. return;
  2348. }
  2349. this.#copyPasteAC = new AbortController();
  2350. const signal = this.combinedSignal(this.#copyPasteAC);
  2351. document.addEventListener("copy", this.copy.bind(this), {
  2352. signal
  2353. });
  2354. document.addEventListener("cut", this.cut.bind(this), {
  2355. signal
  2356. });
  2357. document.addEventListener("paste", this.paste.bind(this), {
  2358. signal
  2359. });
  2360. }
  2361. #removeCopyPasteListeners() {
  2362. this.#copyPasteAC?.abort();
  2363. this.#copyPasteAC = null;
  2364. }
  2365. #addDragAndDropListeners() {
  2366. const signal = this._signal;
  2367. document.addEventListener("dragover", this.dragOver.bind(this), {
  2368. signal
  2369. });
  2370. document.addEventListener("drop", this.drop.bind(this), {
  2371. signal
  2372. });
  2373. }
  2374. addEditListeners() {
  2375. this.#addKeyboardManager();
  2376. this.#addCopyPasteListeners();
  2377. }
  2378. removeEditListeners() {
  2379. this.#removeKeyboardManager();
  2380. this.#removeCopyPasteListeners();
  2381. }
  2382. dragOver(event) {
  2383. for (const {
  2384. type
  2385. } of event.dataTransfer.items) {
  2386. for (const editorType of this.#editorTypes) {
  2387. if (editorType.isHandlingMimeForPasting(type)) {
  2388. event.dataTransfer.dropEffect = "copy";
  2389. event.preventDefault();
  2390. return;
  2391. }
  2392. }
  2393. }
  2394. }
  2395. drop(event) {
  2396. for (const item of event.dataTransfer.items) {
  2397. for (const editorType of this.#editorTypes) {
  2398. if (editorType.isHandlingMimeForPasting(item.type)) {
  2399. editorType.paste(item, this.currentLayer);
  2400. event.preventDefault();
  2401. return;
  2402. }
  2403. }
  2404. }
  2405. }
  2406. copy(event) {
  2407. event.preventDefault();
  2408. this.#activeEditor?.commitOrRemove();
  2409. if (!this.hasSelection) {
  2410. return;
  2411. }
  2412. const editors = [];
  2413. for (const editor of this.#selectedEditors) {
  2414. const serialized = editor.serialize(true);
  2415. if (serialized) {
  2416. editors.push(serialized);
  2417. }
  2418. }
  2419. if (editors.length === 0) {
  2420. return;
  2421. }
  2422. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  2423. }
  2424. cut(event) {
  2425. this.copy(event);
  2426. this.delete();
  2427. }
  2428. async paste(event) {
  2429. event.preventDefault();
  2430. const {
  2431. clipboardData
  2432. } = event;
  2433. for (const item of clipboardData.items) {
  2434. for (const editorType of this.#editorTypes) {
  2435. if (editorType.isHandlingMimeForPasting(item.type)) {
  2436. editorType.paste(item, this.currentLayer);
  2437. return;
  2438. }
  2439. }
  2440. }
  2441. let data = clipboardData.getData("application/pdfjs");
  2442. if (!data) {
  2443. return;
  2444. }
  2445. try {
  2446. data = JSON.parse(data);
  2447. } catch (ex) {
  2448. warn(`paste: "${ex.message}".`);
  2449. return;
  2450. }
  2451. if (!Array.isArray(data)) {
  2452. return;
  2453. }
  2454. this.unselectAll();
  2455. const layer = this.currentLayer;
  2456. try {
  2457. const newEditors = [];
  2458. for (const editor of data) {
  2459. const deserializedEditor = await layer.deserialize(editor);
  2460. if (!deserializedEditor) {
  2461. return;
  2462. }
  2463. newEditors.push(deserializedEditor);
  2464. }
  2465. const cmd = () => {
  2466. for (const editor of newEditors) {
  2467. this.#addEditorToLayer(editor);
  2468. }
  2469. this.#selectEditors(newEditors);
  2470. };
  2471. const undo = () => {
  2472. for (const editor of newEditors) {
  2473. editor.remove();
  2474. }
  2475. };
  2476. this.addCommands({
  2477. cmd,
  2478. undo,
  2479. mustExec: true
  2480. });
  2481. } catch (ex) {
  2482. warn(`paste: "${ex.message}".`);
  2483. }
  2484. }
  2485. keydown(event) {
  2486. if (!this.isShiftKeyDown && event.key === "Shift") {
  2487. this.isShiftKeyDown = true;
  2488. }
  2489. if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
  2490. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  2491. }
  2492. }
  2493. keyup(event) {
  2494. if (this.isShiftKeyDown && event.key === "Shift") {
  2495. this.isShiftKeyDown = false;
  2496. if (this.#highlightWhenShiftUp) {
  2497. this.#highlightWhenShiftUp = false;
  2498. this.#onSelectEnd("main_toolbar");
  2499. }
  2500. }
  2501. }
  2502. onEditingAction({
  2503. name
  2504. }) {
  2505. switch (name) {
  2506. case "undo":
  2507. case "redo":
  2508. case "delete":
  2509. case "selectAll":
  2510. this[name]();
  2511. break;
  2512. case "highlightSelection":
  2513. this.highlightSelection("context_menu");
  2514. break;
  2515. }
  2516. }
  2517. #dispatchUpdateStates(details) {
  2518. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  2519. if (hasChanged) {
  2520. this._eventBus.dispatch("annotationeditorstateschanged", {
  2521. source: this,
  2522. details: Object.assign(this.#previousStates, details)
  2523. });
  2524. if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
  2525. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
  2526. }
  2527. }
  2528. }
  2529. #dispatchUpdateUI(details) {
  2530. this._eventBus.dispatch("annotationeditorparamschanged", {
  2531. source: this,
  2532. details
  2533. });
  2534. }
  2535. setEditingState(isEditing) {
  2536. if (isEditing) {
  2537. this.#addFocusManager();
  2538. this.#addCopyPasteListeners();
  2539. this.#dispatchUpdateStates({
  2540. isEditing: this.#mode !== AnnotationEditorType.NONE,
  2541. isEmpty: this.#isEmpty(),
  2542. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  2543. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  2544. hasSelectedEditor: false
  2545. });
  2546. } else {
  2547. this.#removeFocusManager();
  2548. this.#removeCopyPasteListeners();
  2549. this.#dispatchUpdateStates({
  2550. isEditing: false
  2551. });
  2552. this.disableUserSelect(false);
  2553. }
  2554. }
  2555. registerEditorTypes(types) {
  2556. if (this.#editorTypes) {
  2557. return;
  2558. }
  2559. this.#editorTypes = types;
  2560. for (const editorType of this.#editorTypes) {
  2561. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  2562. }
  2563. }
  2564. getId() {
  2565. return this.#idManager.id;
  2566. }
  2567. get currentLayer() {
  2568. return this.#allLayers.get(this.#currentPageIndex);
  2569. }
  2570. getLayer(pageIndex) {
  2571. return this.#allLayers.get(pageIndex);
  2572. }
  2573. get currentPageIndex() {
  2574. return this.#currentPageIndex;
  2575. }
  2576. addLayer(layer) {
  2577. this.#allLayers.set(layer.pageIndex, layer);
  2578. if (this.#isEnabled) {
  2579. layer.enable();
  2580. } else {
  2581. layer.disable();
  2582. }
  2583. }
  2584. removeLayer(layer) {
  2585. this.#allLayers.delete(layer.pageIndex);
  2586. }
  2587. async updateMode(mode, editId = null, isFromKeyboard = false) {
  2588. if (this.#mode === mode) {
  2589. return;
  2590. }
  2591. if (this.#updateModeCapability) {
  2592. await this.#updateModeCapability.promise;
  2593. if (!this.#updateModeCapability) {
  2594. return;
  2595. }
  2596. }
  2597. this.#updateModeCapability = Promise.withResolvers();
  2598. this.#mode = mode;
  2599. if (mode === AnnotationEditorType.NONE) {
  2600. this.setEditingState(false);
  2601. this.#disableAll();
  2602. this._editorUndoBar?.hide();
  2603. this.#updateModeCapability.resolve();
  2604. return;
  2605. }
  2606. this.setEditingState(true);
  2607. await this.#enableAll();
  2608. this.unselectAll();
  2609. for (const layer of this.#allLayers.values()) {
  2610. layer.updateMode(mode);
  2611. }
  2612. if (!editId) {
  2613. if (isFromKeyboard) {
  2614. this.addNewEditorFromKeyboard();
  2615. }
  2616. this.#updateModeCapability.resolve();
  2617. return;
  2618. }
  2619. for (const editor of this.#allEditors.values()) {
  2620. if (editor.annotationElementId === editId) {
  2621. this.setSelected(editor);
  2622. editor.enterInEditMode();
  2623. } else {
  2624. editor.unselect();
  2625. }
  2626. }
  2627. this.#updateModeCapability.resolve();
  2628. }
  2629. addNewEditorFromKeyboard() {
  2630. if (this.currentLayer.canCreateNewEmptyEditor()) {
  2631. this.currentLayer.addNewEditor();
  2632. }
  2633. }
  2634. updateToolbar(mode) {
  2635. if (mode === this.#mode) {
  2636. return;
  2637. }
  2638. this._eventBus.dispatch("switchannotationeditormode", {
  2639. source: this,
  2640. mode
  2641. });
  2642. }
  2643. updateParams(type, value) {
  2644. if (!this.#editorTypes) {
  2645. return;
  2646. }
  2647. switch (type) {
  2648. case AnnotationEditorParamsType.CREATE:
  2649. this.currentLayer.addNewEditor();
  2650. return;
  2651. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  2652. this.#mainHighlightColorPicker?.updateColor(value);
  2653. break;
  2654. case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
  2655. this._eventBus.dispatch("reporttelemetry", {
  2656. source: this,
  2657. details: {
  2658. type: "editing",
  2659. data: {
  2660. type: "highlight",
  2661. action: "toggle_visibility"
  2662. }
  2663. }
  2664. });
  2665. (this.#showAllStates ||= new Map()).set(type, value);
  2666. this.showAllEditors("highlight", value);
  2667. break;
  2668. }
  2669. for (const editor of this.#selectedEditors) {
  2670. editor.updateParams(type, value);
  2671. }
  2672. for (const editorType of this.#editorTypes) {
  2673. editorType.updateDefaultParams(type, value);
  2674. }
  2675. }
  2676. showAllEditors(type, visible, updateButton = false) {
  2677. for (const editor of this.#allEditors.values()) {
  2678. if (editor.editorType === type) {
  2679. editor.show(visible);
  2680. }
  2681. }
  2682. const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
  2683. if (state !== visible) {
  2684. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
  2685. }
  2686. }
  2687. enableWaiting(mustWait = false) {
  2688. if (this.#isWaiting === mustWait) {
  2689. return;
  2690. }
  2691. this.#isWaiting = mustWait;
  2692. for (const layer of this.#allLayers.values()) {
  2693. if (mustWait) {
  2694. layer.disableClick();
  2695. } else {
  2696. layer.enableClick();
  2697. }
  2698. layer.div.classList.toggle("waiting", mustWait);
  2699. }
  2700. }
  2701. async #enableAll() {
  2702. if (!this.#isEnabled) {
  2703. this.#isEnabled = true;
  2704. const promises = [];
  2705. for (const layer of this.#allLayers.values()) {
  2706. promises.push(layer.enable());
  2707. }
  2708. await Promise.all(promises);
  2709. for (const editor of this.#allEditors.values()) {
  2710. editor.enable();
  2711. }
  2712. }
  2713. }
  2714. #disableAll() {
  2715. this.unselectAll();
  2716. if (this.#isEnabled) {
  2717. this.#isEnabled = false;
  2718. for (const layer of this.#allLayers.values()) {
  2719. layer.disable();
  2720. }
  2721. for (const editor of this.#allEditors.values()) {
  2722. editor.disable();
  2723. }
  2724. }
  2725. }
  2726. getEditors(pageIndex) {
  2727. const editors = [];
  2728. for (const editor of this.#allEditors.values()) {
  2729. if (editor.pageIndex === pageIndex) {
  2730. editors.push(editor);
  2731. }
  2732. }
  2733. return editors;
  2734. }
  2735. getEditor(id) {
  2736. return this.#allEditors.get(id);
  2737. }
  2738. addEditor(editor) {
  2739. this.#allEditors.set(editor.id, editor);
  2740. }
  2741. removeEditor(editor) {
  2742. if (editor.div.contains(document.activeElement)) {
  2743. if (this.#focusMainContainerTimeoutId) {
  2744. clearTimeout(this.#focusMainContainerTimeoutId);
  2745. }
  2746. this.#focusMainContainerTimeoutId = setTimeout(() => {
  2747. this.focusMainContainer();
  2748. this.#focusMainContainerTimeoutId = null;
  2749. }, 0);
  2750. }
  2751. this.#allEditors.delete(editor.id);
  2752. this.unselect(editor);
  2753. if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
  2754. this.#annotationStorage?.remove(editor.id);
  2755. }
  2756. }
  2757. addDeletedAnnotationElement(editor) {
  2758. this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
  2759. this.addChangedExistingAnnotation(editor);
  2760. editor.deleted = true;
  2761. }
  2762. isDeletedAnnotationElement(annotationElementId) {
  2763. return this.#deletedAnnotationsElementIds.has(annotationElementId);
  2764. }
  2765. removeDeletedAnnotationElement(editor) {
  2766. this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
  2767. this.removeChangedExistingAnnotation(editor);
  2768. editor.deleted = false;
  2769. }
  2770. #addEditorToLayer(editor) {
  2771. const layer = this.#allLayers.get(editor.pageIndex);
  2772. if (layer) {
  2773. layer.addOrRebuild(editor);
  2774. } else {
  2775. this.addEditor(editor);
  2776. this.addToAnnotationStorage(editor);
  2777. }
  2778. }
  2779. setActiveEditor(editor) {
  2780. if (this.#activeEditor === editor) {
  2781. return;
  2782. }
  2783. this.#activeEditor = editor;
  2784. if (editor) {
  2785. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2786. }
  2787. }
  2788. get #lastSelectedEditor() {
  2789. let ed = null;
  2790. for (ed of this.#selectedEditors) {}
  2791. return ed;
  2792. }
  2793. updateUI(editor) {
  2794. if (this.#lastSelectedEditor === editor) {
  2795. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2796. }
  2797. }
  2798. updateUIForDefaultProperties(editorType) {
  2799. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  2800. }
  2801. toggleSelected(editor) {
  2802. if (this.#selectedEditors.has(editor)) {
  2803. this.#selectedEditors.delete(editor);
  2804. editor.unselect();
  2805. this.#dispatchUpdateStates({
  2806. hasSelectedEditor: this.hasSelection
  2807. });
  2808. return;
  2809. }
  2810. this.#selectedEditors.add(editor);
  2811. editor.select();
  2812. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2813. this.#dispatchUpdateStates({
  2814. hasSelectedEditor: true
  2815. });
  2816. }
  2817. setSelected(editor) {
  2818. this.#currentDrawingSession?.commitOrRemove();
  2819. for (const ed of this.#selectedEditors) {
  2820. if (ed !== editor) {
  2821. ed.unselect();
  2822. }
  2823. }
  2824. this.#selectedEditors.clear();
  2825. this.#selectedEditors.add(editor);
  2826. editor.select();
  2827. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  2828. this.#dispatchUpdateStates({
  2829. hasSelectedEditor: true
  2830. });
  2831. }
  2832. isSelected(editor) {
  2833. return this.#selectedEditors.has(editor);
  2834. }
  2835. get firstSelectedEditor() {
  2836. return this.#selectedEditors.values().next().value;
  2837. }
  2838. unselect(editor) {
  2839. editor.unselect();
  2840. this.#selectedEditors.delete(editor);
  2841. this.#dispatchUpdateStates({
  2842. hasSelectedEditor: this.hasSelection
  2843. });
  2844. }
  2845. get hasSelection() {
  2846. return this.#selectedEditors.size !== 0;
  2847. }
  2848. get isEnterHandled() {
  2849. return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
  2850. }
  2851. undo() {
  2852. this.#commandManager.undo();
  2853. this.#dispatchUpdateStates({
  2854. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  2855. hasSomethingToRedo: true,
  2856. isEmpty: this.#isEmpty()
  2857. });
  2858. this._editorUndoBar?.hide();
  2859. }
  2860. redo() {
  2861. this.#commandManager.redo();
  2862. this.#dispatchUpdateStates({
  2863. hasSomethingToUndo: true,
  2864. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  2865. isEmpty: this.#isEmpty()
  2866. });
  2867. }
  2868. addCommands(params) {
  2869. this.#commandManager.add(params);
  2870. this.#dispatchUpdateStates({
  2871. hasSomethingToUndo: true,
  2872. hasSomethingToRedo: false,
  2873. isEmpty: this.#isEmpty()
  2874. });
  2875. }
  2876. cleanUndoStack(type) {
  2877. this.#commandManager.cleanType(type);
  2878. }
  2879. #isEmpty() {
  2880. if (this.#allEditors.size === 0) {
  2881. return true;
  2882. }
  2883. if (this.#allEditors.size === 1) {
  2884. for (const editor of this.#allEditors.values()) {
  2885. return editor.isEmpty();
  2886. }
  2887. }
  2888. return false;
  2889. }
  2890. delete() {
  2891. this.commitOrRemove();
  2892. const drawingEditor = this.currentLayer?.endDrawingSession(true);
  2893. if (!this.hasSelection && !drawingEditor) {
  2894. return;
  2895. }
  2896. const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors];
  2897. const cmd = () => {
  2898. this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length);
  2899. for (const editor of editors) {
  2900. editor.remove();
  2901. }
  2902. };
  2903. const undo = () => {
  2904. for (const editor of editors) {
  2905. this.#addEditorToLayer(editor);
  2906. }
  2907. };
  2908. this.addCommands({
  2909. cmd,
  2910. undo,
  2911. mustExec: true
  2912. });
  2913. }
  2914. commitOrRemove() {
  2915. this.#activeEditor?.commitOrRemove();
  2916. }
  2917. hasSomethingToControl() {
  2918. return this.#activeEditor || this.hasSelection;
  2919. }
  2920. #selectEditors(editors) {
  2921. for (const editor of this.#selectedEditors) {
  2922. editor.unselect();
  2923. }
  2924. this.#selectedEditors.clear();
  2925. for (const editor of editors) {
  2926. if (editor.isEmpty()) {
  2927. continue;
  2928. }
  2929. this.#selectedEditors.add(editor);
  2930. editor.select();
  2931. }
  2932. this.#dispatchUpdateStates({
  2933. hasSelectedEditor: this.hasSelection
  2934. });
  2935. }
  2936. selectAll() {
  2937. for (const editor of this.#selectedEditors) {
  2938. editor.commit();
  2939. }
  2940. this.#selectEditors(this.#allEditors.values());
  2941. }
  2942. unselectAll() {
  2943. if (this.#activeEditor) {
  2944. this.#activeEditor.commitOrRemove();
  2945. if (this.#mode !== AnnotationEditorType.NONE) {
  2946. return;
  2947. }
  2948. }
  2949. if (this.#currentDrawingSession?.commitOrRemove()) {
  2950. return;
  2951. }
  2952. if (!this.hasSelection) {
  2953. return;
  2954. }
  2955. for (const editor of this.#selectedEditors) {
  2956. editor.unselect();
  2957. }
  2958. this.#selectedEditors.clear();
  2959. this.#dispatchUpdateStates({
  2960. hasSelectedEditor: false
  2961. });
  2962. }
  2963. translateSelectedEditors(x, y, noCommit = false) {
  2964. if (!noCommit) {
  2965. this.commitOrRemove();
  2966. }
  2967. if (!this.hasSelection) {
  2968. return;
  2969. }
  2970. this.#translation[0] += x;
  2971. this.#translation[1] += y;
  2972. const [totalX, totalY] = this.#translation;
  2973. const editors = [...this.#selectedEditors];
  2974. const TIME_TO_WAIT = 1000;
  2975. if (this.#translationTimeoutId) {
  2976. clearTimeout(this.#translationTimeoutId);
  2977. }
  2978. this.#translationTimeoutId = setTimeout(() => {
  2979. this.#translationTimeoutId = null;
  2980. this.#translation[0] = this.#translation[1] = 0;
  2981. this.addCommands({
  2982. cmd: () => {
  2983. for (const editor of editors) {
  2984. if (this.#allEditors.has(editor.id)) {
  2985. editor.translateInPage(totalX, totalY);
  2986. }
  2987. }
  2988. },
  2989. undo: () => {
  2990. for (const editor of editors) {
  2991. if (this.#allEditors.has(editor.id)) {
  2992. editor.translateInPage(-totalX, -totalY);
  2993. }
  2994. }
  2995. },
  2996. mustExec: false
  2997. });
  2998. }, TIME_TO_WAIT);
  2999. for (const editor of editors) {
  3000. editor.translateInPage(x, y);
  3001. }
  3002. }
  3003. setUpDragSession() {
  3004. if (!this.hasSelection) {
  3005. return;
  3006. }
  3007. this.disableUserSelect(true);
  3008. this.#draggingEditors = new Map();
  3009. for (const editor of this.#selectedEditors) {
  3010. this.#draggingEditors.set(editor, {
  3011. savedX: editor.x,
  3012. savedY: editor.y,
  3013. savedPageIndex: editor.pageIndex,
  3014. newX: 0,
  3015. newY: 0,
  3016. newPageIndex: -1
  3017. });
  3018. }
  3019. }
  3020. endDragSession() {
  3021. if (!this.#draggingEditors) {
  3022. return false;
  3023. }
  3024. this.disableUserSelect(false);
  3025. const map = this.#draggingEditors;
  3026. this.#draggingEditors = null;
  3027. let mustBeAddedInUndoStack = false;
  3028. for (const [{
  3029. x,
  3030. y,
  3031. pageIndex
  3032. }, value] of map) {
  3033. value.newX = x;
  3034. value.newY = y;
  3035. value.newPageIndex = pageIndex;
  3036. mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex;
  3037. }
  3038. if (!mustBeAddedInUndoStack) {
  3039. return false;
  3040. }
  3041. const move = (editor, x, y, pageIndex) => {
  3042. if (this.#allEditors.has(editor.id)) {
  3043. const parent = this.#allLayers.get(pageIndex);
  3044. if (parent) {
  3045. editor._setParentAndPosition(parent, x, y);
  3046. } else {
  3047. editor.pageIndex = pageIndex;
  3048. editor.x = x;
  3049. editor.y = y;
  3050. }
  3051. }
  3052. };
  3053. this.addCommands({
  3054. cmd: () => {
  3055. for (const [editor, {
  3056. newX,
  3057. newY,
  3058. newPageIndex
  3059. }] of map) {
  3060. move(editor, newX, newY, newPageIndex);
  3061. }
  3062. },
  3063. undo: () => {
  3064. for (const [editor, {
  3065. savedX,
  3066. savedY,
  3067. savedPageIndex
  3068. }] of map) {
  3069. move(editor, savedX, savedY, savedPageIndex);
  3070. }
  3071. },
  3072. mustExec: true
  3073. });
  3074. return true;
  3075. }
  3076. dragSelectedEditors(tx, ty) {
  3077. if (!this.#draggingEditors) {
  3078. return;
  3079. }
  3080. for (const editor of this.#draggingEditors.keys()) {
  3081. editor.drag(tx, ty);
  3082. }
  3083. }
  3084. rebuild(editor) {
  3085. if (editor.parent === null) {
  3086. const parent = this.getLayer(editor.pageIndex);
  3087. if (parent) {
  3088. parent.changeParent(editor);
  3089. parent.addOrRebuild(editor);
  3090. } else {
  3091. this.addEditor(editor);
  3092. this.addToAnnotationStorage(editor);
  3093. editor.rebuild();
  3094. }
  3095. } else {
  3096. editor.parent.addOrRebuild(editor);
  3097. }
  3098. }
  3099. get isEditorHandlingKeyboard() {
  3100. return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
  3101. }
  3102. isActive(editor) {
  3103. return this.#activeEditor === editor;
  3104. }
  3105. getActive() {
  3106. return this.#activeEditor;
  3107. }
  3108. getMode() {
  3109. return this.#mode;
  3110. }
  3111. get imageManager() {
  3112. return shadow(this, "imageManager", new ImageManager());
  3113. }
  3114. getSelectionBoxes(textLayer) {
  3115. if (!textLayer) {
  3116. return null;
  3117. }
  3118. const selection = document.getSelection();
  3119. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  3120. if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) {
  3121. return null;
  3122. }
  3123. }
  3124. const {
  3125. x: layerX,
  3126. y: layerY,
  3127. width: parentWidth,
  3128. height: parentHeight
  3129. } = textLayer.getBoundingClientRect();
  3130. let rotator;
  3131. switch (textLayer.getAttribute("data-main-rotation")) {
  3132. case "90":
  3133. rotator = (x, y, w, h) => ({
  3134. x: (y - layerY) / parentHeight,
  3135. y: 1 - (x + w - layerX) / parentWidth,
  3136. width: h / parentHeight,
  3137. height: w / parentWidth
  3138. });
  3139. break;
  3140. case "180":
  3141. rotator = (x, y, w, h) => ({
  3142. x: 1 - (x + w - layerX) / parentWidth,
  3143. y: 1 - (y + h - layerY) / parentHeight,
  3144. width: w / parentWidth,
  3145. height: h / parentHeight
  3146. });
  3147. break;
  3148. case "270":
  3149. rotator = (x, y, w, h) => ({
  3150. x: 1 - (y + h - layerY) / parentHeight,
  3151. y: (x - layerX) / parentWidth,
  3152. width: h / parentHeight,
  3153. height: w / parentWidth
  3154. });
  3155. break;
  3156. default:
  3157. rotator = (x, y, w, h) => ({
  3158. x: (x - layerX) / parentWidth,
  3159. y: (y - layerY) / parentHeight,
  3160. width: w / parentWidth,
  3161. height: h / parentHeight
  3162. });
  3163. break;
  3164. }
  3165. const boxes = [];
  3166. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  3167. const range = selection.getRangeAt(i);
  3168. if (range.collapsed) {
  3169. continue;
  3170. }
  3171. for (const {
  3172. x,
  3173. y,
  3174. width,
  3175. height
  3176. } of range.getClientRects()) {
  3177. if (width === 0 || height === 0) {
  3178. continue;
  3179. }
  3180. boxes.push(rotator(x, y, width, height));
  3181. }
  3182. }
  3183. return boxes.length === 0 ? null : boxes;
  3184. }
  3185. addChangedExistingAnnotation({
  3186. annotationElementId,
  3187. id
  3188. }) {
  3189. (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id);
  3190. }
  3191. removeChangedExistingAnnotation({
  3192. annotationElementId
  3193. }) {
  3194. this.#changedExistingAnnotations?.delete(annotationElementId);
  3195. }
  3196. renderAnnotationElement(annotation) {
  3197. const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
  3198. if (!editorId) {
  3199. return;
  3200. }
  3201. const editor = this.#annotationStorage.getRawValue(editorId);
  3202. if (!editor) {
  3203. return;
  3204. }
  3205. if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
  3206. return;
  3207. }
  3208. editor.renderAnnotationElement(annotation);
  3209. }
  3210. }
  3211. ;// ./src/display/editor/alt_text.js
  3212. class AltText {
  3213. #altText = null;
  3214. #altTextDecorative = false;
  3215. #altTextButton = null;
  3216. #altTextButtonLabel = null;
  3217. #altTextTooltip = null;
  3218. #altTextTooltipTimeout = null;
  3219. #altTextWasFromKeyBoard = false;
  3220. #badge = null;
  3221. #editor = null;
  3222. #guessedText = null;
  3223. #textWithDisclaimer = null;
  3224. #useNewAltTextFlow = false;
  3225. static #l10nNewButton = null;
  3226. static _l10n = null;
  3227. constructor(editor) {
  3228. this.#editor = editor;
  3229. this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;
  3230. AltText.#l10nNewButton ||= Object.freeze({
  3231. added: "pdfjs-editor-new-alt-text-added-button",
  3232. "added-label": "pdfjs-editor-new-alt-text-added-button-label",
  3233. missing: "pdfjs-editor-new-alt-text-missing-button",
  3234. "missing-label": "pdfjs-editor-new-alt-text-missing-button-label",
  3235. review: "pdfjs-editor-new-alt-text-to-review-button",
  3236. "review-label": "pdfjs-editor-new-alt-text-to-review-button-label"
  3237. });
  3238. }
  3239. static initialize(l10n) {
  3240. AltText._l10n ??= l10n;
  3241. }
  3242. async render() {
  3243. const altText = this.#altTextButton = document.createElement("button");
  3244. altText.className = "altText";
  3245. altText.tabIndex = "0";
  3246. const label = this.#altTextButtonLabel = document.createElement("span");
  3247. altText.append(label);
  3248. if (this.#useNewAltTextFlow) {
  3249. altText.classList.add("new");
  3250. altText.setAttribute("data-l10n-id", AltText.#l10nNewButton.missing);
  3251. label.setAttribute("data-l10n-id", AltText.#l10nNewButton["missing-label"]);
  3252. } else {
  3253. altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button");
  3254. label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label");
  3255. }
  3256. const signal = this.#editor._uiManager._signal;
  3257. altText.addEventListener("contextmenu", noContextMenu, {
  3258. signal
  3259. });
  3260. altText.addEventListener("pointerdown", event => event.stopPropagation(), {
  3261. signal
  3262. });
  3263. const onClick = event => {
  3264. event.preventDefault();
  3265. this.#editor._uiManager.editAltText(this.#editor);
  3266. if (this.#useNewAltTextFlow) {
  3267. this.#editor._reportTelemetry({
  3268. action: "pdfjs.image.alt_text.image_status_label_clicked",
  3269. data: {
  3270. label: this.#label
  3271. }
  3272. });
  3273. }
  3274. };
  3275. altText.addEventListener("click", onClick, {
  3276. capture: true,
  3277. signal
  3278. });
  3279. altText.addEventListener("keydown", event => {
  3280. if (event.target === altText && event.key === "Enter") {
  3281. this.#altTextWasFromKeyBoard = true;
  3282. onClick(event);
  3283. }
  3284. }, {
  3285. signal
  3286. });
  3287. await this.#setState();
  3288. return altText;
  3289. }
  3290. get #label() {
  3291. return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";
  3292. }
  3293. finish() {
  3294. if (!this.#altTextButton) {
  3295. return;
  3296. }
  3297. this.#altTextButton.focus({
  3298. focusVisible: this.#altTextWasFromKeyBoard
  3299. });
  3300. this.#altTextWasFromKeyBoard = false;
  3301. }
  3302. isEmpty() {
  3303. if (this.#useNewAltTextFlow) {
  3304. return this.#altText === null;
  3305. }
  3306. return !this.#altText && !this.#altTextDecorative;
  3307. }
  3308. hasData() {
  3309. if (this.#useNewAltTextFlow) {
  3310. return this.#altText !== null || !!this.#guessedText;
  3311. }
  3312. return this.isEmpty();
  3313. }
  3314. get guessedText() {
  3315. return this.#guessedText;
  3316. }
  3317. async setGuessedText(guessedText) {
  3318. if (this.#altText !== null) {
  3319. return;
  3320. }
  3321. this.#guessedText = guessedText;
  3322. this.#textWithDisclaimer = await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", {
  3323. generatedAltText: guessedText
  3324. });
  3325. this.#setState();
  3326. }
  3327. toggleAltTextBadge(visibility = false) {
  3328. if (!this.#useNewAltTextFlow || this.#altText) {
  3329. this.#badge?.remove();
  3330. this.#badge = null;
  3331. return;
  3332. }
  3333. if (!this.#badge) {
  3334. const badge = this.#badge = document.createElement("div");
  3335. badge.className = "noAltTextBadge";
  3336. this.#editor.div.append(badge);
  3337. }
  3338. this.#badge.classList.toggle("hidden", !visibility);
  3339. }
  3340. serialize(isForCopying) {
  3341. let altText = this.#altText;
  3342. if (!isForCopying && this.#guessedText === altText) {
  3343. altText = this.#textWithDisclaimer;
  3344. }
  3345. return {
  3346. altText,
  3347. decorative: this.#altTextDecorative,
  3348. guessedText: this.#guessedText,
  3349. textWithDisclaimer: this.#textWithDisclaimer
  3350. };
  3351. }
  3352. get data() {
  3353. return {
  3354. altText: this.#altText,
  3355. decorative: this.#altTextDecorative
  3356. };
  3357. }
  3358. set data({
  3359. altText,
  3360. decorative,
  3361. guessedText,
  3362. textWithDisclaimer,
  3363. cancel = false
  3364. }) {
  3365. if (guessedText) {
  3366. this.#guessedText = guessedText;
  3367. this.#textWithDisclaimer = textWithDisclaimer;
  3368. }
  3369. if (this.#altText === altText && this.#altTextDecorative === decorative) {
  3370. return;
  3371. }
  3372. if (!cancel) {
  3373. this.#altText = altText;
  3374. this.#altTextDecorative = decorative;
  3375. }
  3376. this.#setState();
  3377. }
  3378. toggle(enabled = false) {
  3379. if (!this.#altTextButton) {
  3380. return;
  3381. }
  3382. if (!enabled && this.#altTextTooltipTimeout) {
  3383. clearTimeout(this.#altTextTooltipTimeout);
  3384. this.#altTextTooltipTimeout = null;
  3385. }
  3386. this.#altTextButton.disabled = !enabled;
  3387. }
  3388. shown() {
  3389. this.#editor._reportTelemetry({
  3390. action: "pdfjs.image.alt_text.image_status_label_displayed",
  3391. data: {
  3392. label: this.#label
  3393. }
  3394. });
  3395. }
  3396. destroy() {
  3397. this.#altTextButton?.remove();
  3398. this.#altTextButton = null;
  3399. this.#altTextButtonLabel = null;
  3400. this.#altTextTooltip = null;
  3401. this.#badge?.remove();
  3402. this.#badge = null;
  3403. }
  3404. async #setState() {
  3405. const button = this.#altTextButton;
  3406. if (!button) {
  3407. return;
  3408. }
  3409. if (this.#useNewAltTextFlow) {
  3410. button.classList.toggle("done", !!this.#altText);
  3411. button.setAttribute("data-l10n-id", AltText.#l10nNewButton[this.#label]);
  3412. this.#altTextButtonLabel?.setAttribute("data-l10n-id", AltText.#l10nNewButton[`${this.#label}-label`]);
  3413. if (!this.#altText) {
  3414. this.#altTextTooltip?.remove();
  3415. return;
  3416. }
  3417. } else {
  3418. if (!this.#altText && !this.#altTextDecorative) {
  3419. button.classList.remove("done");
  3420. this.#altTextTooltip?.remove();
  3421. return;
  3422. }
  3423. button.classList.add("done");
  3424. button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button");
  3425. }
  3426. let tooltip = this.#altTextTooltip;
  3427. if (!tooltip) {
  3428. this.#altTextTooltip = tooltip = document.createElement("span");
  3429. tooltip.className = "tooltip";
  3430. tooltip.setAttribute("role", "tooltip");
  3431. tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
  3432. const DELAY_TO_SHOW_TOOLTIP = 100;
  3433. const signal = this.#editor._uiManager._signal;
  3434. signal.addEventListener("abort", () => {
  3435. clearTimeout(this.#altTextTooltipTimeout);
  3436. this.#altTextTooltipTimeout = null;
  3437. }, {
  3438. once: true
  3439. });
  3440. button.addEventListener("mouseenter", () => {
  3441. this.#altTextTooltipTimeout = setTimeout(() => {
  3442. this.#altTextTooltipTimeout = null;
  3443. this.#altTextTooltip.classList.add("show");
  3444. this.#editor._reportTelemetry({
  3445. action: "alt_text_tooltip"
  3446. });
  3447. }, DELAY_TO_SHOW_TOOLTIP);
  3448. }, {
  3449. signal
  3450. });
  3451. button.addEventListener("mouseleave", () => {
  3452. if (this.#altTextTooltipTimeout) {
  3453. clearTimeout(this.#altTextTooltipTimeout);
  3454. this.#altTextTooltipTimeout = null;
  3455. }
  3456. this.#altTextTooltip?.classList.remove("show");
  3457. }, {
  3458. signal
  3459. });
  3460. }
  3461. if (this.#altTextDecorative) {
  3462. tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip");
  3463. } else {
  3464. tooltip.removeAttribute("data-l10n-id");
  3465. tooltip.textContent = this.#altText;
  3466. }
  3467. if (!tooltip.parentNode) {
  3468. button.append(tooltip);
  3469. }
  3470. const element = this.#editor.getImageForAltText();
  3471. element?.setAttribute("aria-describedby", tooltip.id);
  3472. }
  3473. }
  3474. ;// ./src/display/touch_manager.js
  3475. class TouchManager {
  3476. #container;
  3477. #isPinching = false;
  3478. #isPinchingStopped = null;
  3479. #isPinchingDisabled;
  3480. #onPinchStart;
  3481. #onPinching;
  3482. #onPinchEnd;
  3483. #signal;
  3484. #touchInfo = null;
  3485. #touchManagerAC;
  3486. #touchMoveAC = null;
  3487. constructor({
  3488. container,
  3489. isPinchingDisabled = null,
  3490. isPinchingStopped = null,
  3491. onPinchStart = null,
  3492. onPinching = null,
  3493. onPinchEnd = null,
  3494. signal
  3495. }) {
  3496. this.#container = container;
  3497. this.#isPinchingStopped = isPinchingStopped;
  3498. this.#isPinchingDisabled = isPinchingDisabled;
  3499. this.#onPinchStart = onPinchStart;
  3500. this.#onPinching = onPinching;
  3501. this.#onPinchEnd = onPinchEnd;
  3502. this.#touchManagerAC = new AbortController();
  3503. this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]);
  3504. container.addEventListener("touchstart", this.#onTouchStart.bind(this), {
  3505. passive: false,
  3506. signal: this.#signal
  3507. });
  3508. }
  3509. get MIN_TOUCH_DISTANCE_TO_PINCH() {
  3510. return shadow(this, "MIN_TOUCH_DISTANCE_TO_PINCH", 35 / (window.devicePixelRatio || 1));
  3511. }
  3512. #onTouchStart(evt) {
  3513. if (this.#isPinchingDisabled?.() || evt.touches.length < 2) {
  3514. return;
  3515. }
  3516. if (!this.#touchMoveAC) {
  3517. this.#touchMoveAC = new AbortController();
  3518. const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]);
  3519. const container = this.#container;
  3520. const opt = {
  3521. signal,
  3522. passive: false
  3523. };
  3524. container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt);
  3525. container.addEventListener("touchend", this.#onTouchEnd.bind(this), opt);
  3526. container.addEventListener("touchcancel", this.#onTouchEnd.bind(this), opt);
  3527. this.#onPinchStart?.();
  3528. }
  3529. stopEvent(evt);
  3530. if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) {
  3531. this.#touchInfo = null;
  3532. return;
  3533. }
  3534. let [touch0, touch1] = evt.touches;
  3535. if (touch0.identifier > touch1.identifier) {
  3536. [touch0, touch1] = [touch1, touch0];
  3537. }
  3538. this.#touchInfo = {
  3539. touch0X: touch0.screenX,
  3540. touch0Y: touch0.screenY,
  3541. touch1X: touch1.screenX,
  3542. touch1Y: touch1.screenY
  3543. };
  3544. }
  3545. #onTouchMove(evt) {
  3546. if (!this.#touchInfo || evt.touches.length !== 2) {
  3547. return;
  3548. }
  3549. let [touch0, touch1] = evt.touches;
  3550. if (touch0.identifier > touch1.identifier) {
  3551. [touch0, touch1] = [touch1, touch0];
  3552. }
  3553. const {
  3554. screenX: screen0X,
  3555. screenY: screen0Y
  3556. } = touch0;
  3557. const {
  3558. screenX: screen1X,
  3559. screenY: screen1Y
  3560. } = touch1;
  3561. const touchInfo = this.#touchInfo;
  3562. const {
  3563. touch0X: pTouch0X,
  3564. touch0Y: pTouch0Y,
  3565. touch1X: pTouch1X,
  3566. touch1Y: pTouch1Y
  3567. } = touchInfo;
  3568. const prevGapX = pTouch1X - pTouch0X;
  3569. const prevGapY = pTouch1Y - pTouch0Y;
  3570. const currGapX = screen1X - screen0X;
  3571. const currGapY = screen1Y - screen0Y;
  3572. const distance = Math.hypot(currGapX, currGapY) || 1;
  3573. const pDistance = Math.hypot(prevGapX, prevGapY) || 1;
  3574. if (!this.#isPinching && Math.abs(pDistance - distance) <= TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) {
  3575. return;
  3576. }
  3577. touchInfo.touch0X = screen0X;
  3578. touchInfo.touch0Y = screen0Y;
  3579. touchInfo.touch1X = screen1X;
  3580. touchInfo.touch1Y = screen1Y;
  3581. evt.preventDefault();
  3582. if (!this.#isPinching) {
  3583. this.#isPinching = true;
  3584. return;
  3585. }
  3586. const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2];
  3587. this.#onPinching?.(origin, pDistance, distance);
  3588. }
  3589. #onTouchEnd(evt) {
  3590. this.#touchMoveAC.abort();
  3591. this.#touchMoveAC = null;
  3592. this.#onPinchEnd?.();
  3593. if (!this.#touchInfo) {
  3594. return;
  3595. }
  3596. evt.preventDefault();
  3597. this.#touchInfo = null;
  3598. this.#isPinching = false;
  3599. }
  3600. destroy() {
  3601. this.#touchManagerAC?.abort();
  3602. this.#touchManagerAC = null;
  3603. }
  3604. }
  3605. ;// ./src/display/editor/editor.js
  3606. class AnnotationEditor {
  3607. #accessibilityData = null;
  3608. #allResizerDivs = null;
  3609. #altText = null;
  3610. #disabled = false;
  3611. #dragPointerId = null;
  3612. #dragPointerType = "";
  3613. #keepAspectRatio = false;
  3614. #resizersDiv = null;
  3615. #lastPointerCoords = null;
  3616. #savedDimensions = null;
  3617. #focusAC = null;
  3618. #focusedResizerName = "";
  3619. #hasBeenClicked = false;
  3620. #initialRect = null;
  3621. #isEditing = false;
  3622. #isInEditMode = false;
  3623. #isResizerEnabledForKeyboard = false;
  3624. #moveInDOMTimeout = null;
  3625. #prevDragX = 0;
  3626. #prevDragY = 0;
  3627. #telemetryTimeouts = null;
  3628. #touchManager = null;
  3629. _editToolbar = null;
  3630. _initialOptions = Object.create(null);
  3631. _initialData = null;
  3632. _isVisible = true;
  3633. _uiManager = null;
  3634. _focusEventsAllowed = true;
  3635. static _l10n = null;
  3636. static _l10nResizer = null;
  3637. #isDraggable = false;
  3638. #zIndex = AnnotationEditor._zIndex++;
  3639. static _borderLineWidth = -1;
  3640. static _colorManager = new ColorManager();
  3641. static _zIndex = 1;
  3642. static _telemetryTimeout = 1000;
  3643. static get _resizerKeyboardManager() {
  3644. const resize = AnnotationEditor.prototype._resizeWithKeyboard;
  3645. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  3646. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  3647. return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
  3648. args: [-small, 0]
  3649. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
  3650. args: [-big, 0]
  3651. }], [["ArrowRight", "mac+ArrowRight"], resize, {
  3652. args: [small, 0]
  3653. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
  3654. args: [big, 0]
  3655. }], [["ArrowUp", "mac+ArrowUp"], resize, {
  3656. args: [0, -small]
  3657. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
  3658. args: [0, -big]
  3659. }], [["ArrowDown", "mac+ArrowDown"], resize, {
  3660. args: [0, small]
  3661. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
  3662. args: [0, big]
  3663. }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]]));
  3664. }
  3665. constructor(parameters) {
  3666. this.parent = parameters.parent;
  3667. this.id = parameters.id;
  3668. this.width = this.height = null;
  3669. this.pageIndex = parameters.parent.pageIndex;
  3670. this.name = parameters.name;
  3671. this.div = null;
  3672. this._uiManager = parameters.uiManager;
  3673. this.annotationElementId = null;
  3674. this._willKeepAspectRatio = false;
  3675. this._initialOptions.isCentered = parameters.isCentered;
  3676. this._structTreeParentId = null;
  3677. const {
  3678. rotation,
  3679. rawDims: {
  3680. pageWidth,
  3681. pageHeight,
  3682. pageX,
  3683. pageY
  3684. }
  3685. } = this.parent.viewport;
  3686. this.rotation = rotation;
  3687. this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
  3688. this.pageDimensions = [pageWidth, pageHeight];
  3689. this.pageTranslation = [pageX, pageY];
  3690. const [width, height] = this.parentDimensions;
  3691. this.x = parameters.x / width;
  3692. this.y = parameters.y / height;
  3693. this.isAttachedToDOM = false;
  3694. this.deleted = false;
  3695. }
  3696. get editorType() {
  3697. return Object.getPrototypeOf(this).constructor._type;
  3698. }
  3699. static get isDrawer() {
  3700. return false;
  3701. }
  3702. static get _defaultLineColor() {
  3703. return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  3704. }
  3705. static deleteAnnotationElement(editor) {
  3706. const fakeEditor = new FakeEditor({
  3707. id: editor.parent.getNextId(),
  3708. parent: editor.parent,
  3709. uiManager: editor._uiManager
  3710. });
  3711. fakeEditor.annotationElementId = editor.annotationElementId;
  3712. fakeEditor.deleted = true;
  3713. fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
  3714. }
  3715. static initialize(l10n, _uiManager) {
  3716. AnnotationEditor._l10n ??= l10n;
  3717. AnnotationEditor._l10nResizer ||= Object.freeze({
  3718. topLeft: "pdfjs-editor-resizer-top-left",
  3719. topMiddle: "pdfjs-editor-resizer-top-middle",
  3720. topRight: "pdfjs-editor-resizer-top-right",
  3721. middleRight: "pdfjs-editor-resizer-middle-right",
  3722. bottomRight: "pdfjs-editor-resizer-bottom-right",
  3723. bottomMiddle: "pdfjs-editor-resizer-bottom-middle",
  3724. bottomLeft: "pdfjs-editor-resizer-bottom-left",
  3725. middleLeft: "pdfjs-editor-resizer-middle-left"
  3726. });
  3727. if (AnnotationEditor._borderLineWidth !== -1) {
  3728. return;
  3729. }
  3730. const style = getComputedStyle(document.documentElement);
  3731. AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
  3732. }
  3733. static updateDefaultParams(_type, _value) {}
  3734. static get defaultPropertiesToUpdate() {
  3735. return [];
  3736. }
  3737. static isHandlingMimeForPasting(mime) {
  3738. return false;
  3739. }
  3740. static paste(item, parent) {
  3741. unreachable("Not implemented");
  3742. }
  3743. get propertiesToUpdate() {
  3744. return [];
  3745. }
  3746. get _isDraggable() {
  3747. return this.#isDraggable;
  3748. }
  3749. set _isDraggable(value) {
  3750. this.#isDraggable = value;
  3751. this.div?.classList.toggle("draggable", value);
  3752. }
  3753. get isEnterHandled() {
  3754. return true;
  3755. }
  3756. center() {
  3757. const [pageWidth, pageHeight] = this.pageDimensions;
  3758. switch (this.parentRotation) {
  3759. case 90:
  3760. this.x -= this.height * pageHeight / (pageWidth * 2);
  3761. this.y += this.width * pageWidth / (pageHeight * 2);
  3762. break;
  3763. case 180:
  3764. this.x += this.width / 2;
  3765. this.y += this.height / 2;
  3766. break;
  3767. case 270:
  3768. this.x += this.height * pageHeight / (pageWidth * 2);
  3769. this.y -= this.width * pageWidth / (pageHeight * 2);
  3770. break;
  3771. default:
  3772. this.x -= this.width / 2;
  3773. this.y -= this.height / 2;
  3774. break;
  3775. }
  3776. this.fixAndSetPosition();
  3777. }
  3778. addCommands(params) {
  3779. this._uiManager.addCommands(params);
  3780. }
  3781. get currentLayer() {
  3782. return this._uiManager.currentLayer;
  3783. }
  3784. setInBackground() {
  3785. this.div.style.zIndex = 0;
  3786. }
  3787. setInForeground() {
  3788. this.div.style.zIndex = this.#zIndex;
  3789. }
  3790. setParent(parent) {
  3791. if (parent !== null) {
  3792. this.pageIndex = parent.pageIndex;
  3793. this.pageDimensions = parent.pageDimensions;
  3794. } else {
  3795. this.#stopResizing();
  3796. }
  3797. this.parent = parent;
  3798. }
  3799. focusin(event) {
  3800. if (!this._focusEventsAllowed) {
  3801. return;
  3802. }
  3803. if (!this.#hasBeenClicked) {
  3804. this.parent.setSelected(this);
  3805. } else {
  3806. this.#hasBeenClicked = false;
  3807. }
  3808. }
  3809. focusout(event) {
  3810. if (!this._focusEventsAllowed) {
  3811. return;
  3812. }
  3813. if (!this.isAttachedToDOM) {
  3814. return;
  3815. }
  3816. const target = event.relatedTarget;
  3817. if (target?.closest(`#${this.id}`)) {
  3818. return;
  3819. }
  3820. event.preventDefault();
  3821. if (!this.parent?.isMultipleSelection) {
  3822. this.commitOrRemove();
  3823. }
  3824. }
  3825. commitOrRemove() {
  3826. if (this.isEmpty()) {
  3827. this.remove();
  3828. } else {
  3829. this.commit();
  3830. }
  3831. }
  3832. commit() {
  3833. this.addToAnnotationStorage();
  3834. }
  3835. addToAnnotationStorage() {
  3836. this._uiManager.addToAnnotationStorage(this);
  3837. }
  3838. setAt(x, y, tx, ty) {
  3839. const [width, height] = this.parentDimensions;
  3840. [tx, ty] = this.screenToPageTranslation(tx, ty);
  3841. this.x = (x + tx) / width;
  3842. this.y = (y + ty) / height;
  3843. this.fixAndSetPosition();
  3844. }
  3845. #translate([width, height], x, y) {
  3846. [x, y] = this.screenToPageTranslation(x, y);
  3847. this.x += x / width;
  3848. this.y += y / height;
  3849. this._onTranslating(this.x, this.y);
  3850. this.fixAndSetPosition();
  3851. }
  3852. translate(x, y) {
  3853. this.#translate(this.parentDimensions, x, y);
  3854. }
  3855. translateInPage(x, y) {
  3856. this.#initialRect ||= [this.x, this.y, this.width, this.height];
  3857. this.#translate(this.pageDimensions, x, y);
  3858. this.div.scrollIntoView({
  3859. block: "nearest"
  3860. });
  3861. }
  3862. drag(tx, ty) {
  3863. this.#initialRect ||= [this.x, this.y, this.width, this.height];
  3864. const {
  3865. div,
  3866. parentDimensions: [parentWidth, parentHeight]
  3867. } = this;
  3868. this.x += tx / parentWidth;
  3869. this.y += ty / parentHeight;
  3870. if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
  3871. const {
  3872. x,
  3873. y
  3874. } = this.div.getBoundingClientRect();
  3875. if (this.parent.findNewParent(this, x, y)) {
  3876. this.x -= Math.floor(this.x);
  3877. this.y -= Math.floor(this.y);
  3878. }
  3879. }
  3880. let {
  3881. x,
  3882. y
  3883. } = this;
  3884. const [bx, by] = this.getBaseTranslation();
  3885. x += bx;
  3886. y += by;
  3887. const {
  3888. style
  3889. } = div;
  3890. style.left = `${(100 * x).toFixed(2)}%`;
  3891. style.top = `${(100 * y).toFixed(2)}%`;
  3892. this._onTranslating(x, y);
  3893. div.scrollIntoView({
  3894. block: "nearest"
  3895. });
  3896. }
  3897. _onTranslating(x, y) {}
  3898. _onTranslated(x, y) {}
  3899. get _hasBeenMoved() {
  3900. return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y);
  3901. }
  3902. get _hasBeenResized() {
  3903. return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height);
  3904. }
  3905. getBaseTranslation() {
  3906. const [parentWidth, parentHeight] = this.parentDimensions;
  3907. const {
  3908. _borderLineWidth
  3909. } = AnnotationEditor;
  3910. const x = _borderLineWidth / parentWidth;
  3911. const y = _borderLineWidth / parentHeight;
  3912. switch (this.rotation) {
  3913. case 90:
  3914. return [-x, y];
  3915. case 180:
  3916. return [x, y];
  3917. case 270:
  3918. return [x, -y];
  3919. default:
  3920. return [-x, -y];
  3921. }
  3922. }
  3923. get _mustFixPosition() {
  3924. return true;
  3925. }
  3926. fixAndSetPosition(rotation = this.rotation) {
  3927. const {
  3928. div: {
  3929. style
  3930. },
  3931. pageDimensions: [pageWidth, pageHeight]
  3932. } = this;
  3933. let {
  3934. x,
  3935. y,
  3936. width,
  3937. height
  3938. } = this;
  3939. width *= pageWidth;
  3940. height *= pageHeight;
  3941. x *= pageWidth;
  3942. y *= pageHeight;
  3943. if (this._mustFixPosition) {
  3944. switch (rotation) {
  3945. case 0:
  3946. x = Math.max(0, Math.min(pageWidth - width, x));
  3947. y = Math.max(0, Math.min(pageHeight - height, y));
  3948. break;
  3949. case 90:
  3950. x = Math.max(0, Math.min(pageWidth - height, x));
  3951. y = Math.min(pageHeight, Math.max(width, y));
  3952. break;
  3953. case 180:
  3954. x = Math.min(pageWidth, Math.max(width, x));
  3955. y = Math.min(pageHeight, Math.max(height, y));
  3956. break;
  3957. case 270:
  3958. x = Math.min(pageWidth, Math.max(height, x));
  3959. y = Math.max(0, Math.min(pageHeight - width, y));
  3960. break;
  3961. }
  3962. }
  3963. this.x = x /= pageWidth;
  3964. this.y = y /= pageHeight;
  3965. const [bx, by] = this.getBaseTranslation();
  3966. x += bx;
  3967. y += by;
  3968. style.left = `${(100 * x).toFixed(2)}%`;
  3969. style.top = `${(100 * y).toFixed(2)}%`;
  3970. this.moveInDOM();
  3971. }
  3972. static #rotatePoint(x, y, angle) {
  3973. switch (angle) {
  3974. case 90:
  3975. return [y, -x];
  3976. case 180:
  3977. return [-x, -y];
  3978. case 270:
  3979. return [-y, x];
  3980. default:
  3981. return [x, y];
  3982. }
  3983. }
  3984. screenToPageTranslation(x, y) {
  3985. return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);
  3986. }
  3987. pageTranslationToScreen(x, y) {
  3988. return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);
  3989. }
  3990. #getRotationMatrix(rotation) {
  3991. switch (rotation) {
  3992. case 90:
  3993. {
  3994. const [pageWidth, pageHeight] = this.pageDimensions;
  3995. return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
  3996. }
  3997. case 180:
  3998. return [-1, 0, 0, -1];
  3999. case 270:
  4000. {
  4001. const [pageWidth, pageHeight] = this.pageDimensions;
  4002. return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
  4003. }
  4004. default:
  4005. return [1, 0, 0, 1];
  4006. }
  4007. }
  4008. get parentScale() {
  4009. return this._uiManager.viewParameters.realScale;
  4010. }
  4011. get parentRotation() {
  4012. return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
  4013. }
  4014. get parentDimensions() {
  4015. const {
  4016. parentScale,
  4017. pageDimensions: [pageWidth, pageHeight]
  4018. } = this;
  4019. return [pageWidth * parentScale, pageHeight * parentScale];
  4020. }
  4021. setDims(width, height) {
  4022. const [parentWidth, parentHeight] = this.parentDimensions;
  4023. const {
  4024. style
  4025. } = this.div;
  4026. style.width = `${(100 * width / parentWidth).toFixed(2)}%`;
  4027. if (!this.#keepAspectRatio) {
  4028. style.height = `${(100 * height / parentHeight).toFixed(2)}%`;
  4029. }
  4030. }
  4031. fixDims() {
  4032. const {
  4033. style
  4034. } = this.div;
  4035. const {
  4036. height,
  4037. width
  4038. } = style;
  4039. const widthPercent = width.endsWith("%");
  4040. const heightPercent = !this.#keepAspectRatio && height.endsWith("%");
  4041. if (widthPercent && heightPercent) {
  4042. return;
  4043. }
  4044. const [parentWidth, parentHeight] = this.parentDimensions;
  4045. if (!widthPercent) {
  4046. style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`;
  4047. }
  4048. if (!this.#keepAspectRatio && !heightPercent) {
  4049. style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`;
  4050. }
  4051. }
  4052. getInitialTranslation() {
  4053. return [0, 0];
  4054. }
  4055. #createResizers() {
  4056. if (this.#resizersDiv) {
  4057. return;
  4058. }
  4059. this.#resizersDiv = document.createElement("div");
  4060. this.#resizersDiv.classList.add("resizers");
  4061. const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
  4062. const signal = this._uiManager._signal;
  4063. for (const name of classes) {
  4064. const div = document.createElement("div");
  4065. this.#resizersDiv.append(div);
  4066. div.classList.add("resizer", name);
  4067. div.setAttribute("data-resizer-name", name);
  4068. div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {
  4069. signal
  4070. });
  4071. div.addEventListener("contextmenu", noContextMenu, {
  4072. signal
  4073. });
  4074. div.tabIndex = -1;
  4075. }
  4076. this.div.prepend(this.#resizersDiv);
  4077. }
  4078. #resizerPointerdown(name, event) {
  4079. event.preventDefault();
  4080. const {
  4081. isMac
  4082. } = util_FeatureTest.platform;
  4083. if (event.button !== 0 || event.ctrlKey && isMac) {
  4084. return;
  4085. }
  4086. this.#altText?.toggle(false);
  4087. const savedDraggable = this._isDraggable;
  4088. this._isDraggable = false;
  4089. this.#lastPointerCoords = [event.screenX, event.screenY];
  4090. const ac = new AbortController();
  4091. const signal = this._uiManager.combinedSignal(ac);
  4092. this.parent.togglePointerEvents(false);
  4093. window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {
  4094. passive: true,
  4095. capture: true,
  4096. signal
  4097. });
  4098. window.addEventListener("touchmove", stopEvent, {
  4099. passive: false,
  4100. signal
  4101. });
  4102. window.addEventListener("contextmenu", noContextMenu, {
  4103. signal
  4104. });
  4105. this.#savedDimensions = {
  4106. savedX: this.x,
  4107. savedY: this.y,
  4108. savedWidth: this.width,
  4109. savedHeight: this.height
  4110. };
  4111. const savedParentCursor = this.parent.div.style.cursor;
  4112. const savedCursor = this.div.style.cursor;
  4113. this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
  4114. const pointerUpCallback = () => {
  4115. ac.abort();
  4116. this.parent.togglePointerEvents(true);
  4117. this.#altText?.toggle(true);
  4118. this._isDraggable = savedDraggable;
  4119. this.parent.div.style.cursor = savedParentCursor;
  4120. this.div.style.cursor = savedCursor;
  4121. this.#addResizeToUndoStack();
  4122. };
  4123. window.addEventListener("pointerup", pointerUpCallback, {
  4124. signal
  4125. });
  4126. window.addEventListener("blur", pointerUpCallback, {
  4127. signal
  4128. });
  4129. }
  4130. #resize(x, y, width, height) {
  4131. this.width = width;
  4132. this.height = height;
  4133. this.x = x;
  4134. this.y = y;
  4135. const [parentWidth, parentHeight] = this.parentDimensions;
  4136. this.setDims(parentWidth * width, parentHeight * height);
  4137. this.fixAndSetPosition();
  4138. this._onResized();
  4139. }
  4140. _onResized() {}
  4141. #addResizeToUndoStack() {
  4142. if (!this.#savedDimensions) {
  4143. return;
  4144. }
  4145. const {
  4146. savedX,
  4147. savedY,
  4148. savedWidth,
  4149. savedHeight
  4150. } = this.#savedDimensions;
  4151. this.#savedDimensions = null;
  4152. const newX = this.x;
  4153. const newY = this.y;
  4154. const newWidth = this.width;
  4155. const newHeight = this.height;
  4156. if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
  4157. return;
  4158. }
  4159. this.addCommands({
  4160. cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight),
  4161. undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight),
  4162. mustExec: true
  4163. });
  4164. }
  4165. static _round(x) {
  4166. return Math.round(x * 10000) / 10000;
  4167. }
  4168. #resizerPointermove(name, event) {
  4169. const [parentWidth, parentHeight] = this.parentDimensions;
  4170. const savedX = this.x;
  4171. const savedY = this.y;
  4172. const savedWidth = this.width;
  4173. const savedHeight = this.height;
  4174. const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
  4175. const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
  4176. const rotationMatrix = this.#getRotationMatrix(this.rotation);
  4177. const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
  4178. const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
  4179. const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];
  4180. let getPoint;
  4181. let getOpposite;
  4182. let isDiagonal = false;
  4183. let isHorizontal = false;
  4184. switch (name) {
  4185. case "topLeft":
  4186. isDiagonal = true;
  4187. getPoint = (w, h) => [0, 0];
  4188. getOpposite = (w, h) => [w, h];
  4189. break;
  4190. case "topMiddle":
  4191. getPoint = (w, h) => [w / 2, 0];
  4192. getOpposite = (w, h) => [w / 2, h];
  4193. break;
  4194. case "topRight":
  4195. isDiagonal = true;
  4196. getPoint = (w, h) => [w, 0];
  4197. getOpposite = (w, h) => [0, h];
  4198. break;
  4199. case "middleRight":
  4200. isHorizontal = true;
  4201. getPoint = (w, h) => [w, h / 2];
  4202. getOpposite = (w, h) => [0, h / 2];
  4203. break;
  4204. case "bottomRight":
  4205. isDiagonal = true;
  4206. getPoint = (w, h) => [w, h];
  4207. getOpposite = (w, h) => [0, 0];
  4208. break;
  4209. case "bottomMiddle":
  4210. getPoint = (w, h) => [w / 2, h];
  4211. getOpposite = (w, h) => [w / 2, 0];
  4212. break;
  4213. case "bottomLeft":
  4214. isDiagonal = true;
  4215. getPoint = (w, h) => [0, h];
  4216. getOpposite = (w, h) => [w, 0];
  4217. break;
  4218. case "middleLeft":
  4219. isHorizontal = true;
  4220. getPoint = (w, h) => [0, h / 2];
  4221. getOpposite = (w, h) => [w, h / 2];
  4222. break;
  4223. }
  4224. const point = getPoint(savedWidth, savedHeight);
  4225. const oppositePoint = getOpposite(savedWidth, savedHeight);
  4226. let transfOppositePoint = transf(...oppositePoint);
  4227. const oppositeX = AnnotationEditor._round(savedX + transfOppositePoint[0]);
  4228. const oppositeY = AnnotationEditor._round(savedY + transfOppositePoint[1]);
  4229. let ratioX = 1;
  4230. let ratioY = 1;
  4231. let deltaX, deltaY;
  4232. if (!event.fromKeyboard) {
  4233. const {
  4234. screenX,
  4235. screenY
  4236. } = event;
  4237. const [lastScreenX, lastScreenY] = this.#lastPointerCoords;
  4238. [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY);
  4239. this.#lastPointerCoords[0] = screenX;
  4240. this.#lastPointerCoords[1] = screenY;
  4241. } else {
  4242. ({
  4243. deltaX,
  4244. deltaY
  4245. } = event);
  4246. }
  4247. [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
  4248. if (isDiagonal) {
  4249. const oldDiag = Math.hypot(savedWidth, savedHeight);
  4250. 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);
  4251. } else if (isHorizontal) {
  4252. ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth;
  4253. } else {
  4254. ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight;
  4255. }
  4256. const newWidth = AnnotationEditor._round(savedWidth * ratioX);
  4257. const newHeight = AnnotationEditor._round(savedHeight * ratioY);
  4258. transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
  4259. const newX = oppositeX - transfOppositePoint[0];
  4260. const newY = oppositeY - transfOppositePoint[1];
  4261. this.#initialRect ||= [this.x, this.y, this.width, this.height];
  4262. this.width = newWidth;
  4263. this.height = newHeight;
  4264. this.x = newX;
  4265. this.y = newY;
  4266. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  4267. this.fixAndSetPosition();
  4268. this._onResizing();
  4269. }
  4270. _onResizing() {}
  4271. altTextFinish() {
  4272. this.#altText?.finish();
  4273. }
  4274. async addEditToolbar() {
  4275. if (this._editToolbar || this.#isInEditMode) {
  4276. return this._editToolbar;
  4277. }
  4278. this._editToolbar = new EditorToolbar(this);
  4279. this.div.append(this._editToolbar.render());
  4280. if (this.#altText) {
  4281. await this._editToolbar.addAltText(this.#altText);
  4282. }
  4283. return this._editToolbar;
  4284. }
  4285. removeEditToolbar() {
  4286. if (!this._editToolbar) {
  4287. return;
  4288. }
  4289. this._editToolbar.remove();
  4290. this._editToolbar = null;
  4291. this.#altText?.destroy();
  4292. }
  4293. addContainer(container) {
  4294. const editToolbarDiv = this._editToolbar?.div;
  4295. if (editToolbarDiv) {
  4296. editToolbarDiv.before(container);
  4297. } else {
  4298. this.div.append(container);
  4299. }
  4300. }
  4301. getClientDimensions() {
  4302. return this.div.getBoundingClientRect();
  4303. }
  4304. async addAltTextButton() {
  4305. if (this.#altText) {
  4306. return;
  4307. }
  4308. AltText.initialize(AnnotationEditor._l10n);
  4309. this.#altText = new AltText(this);
  4310. if (this.#accessibilityData) {
  4311. this.#altText.data = this.#accessibilityData;
  4312. this.#accessibilityData = null;
  4313. }
  4314. await this.addEditToolbar();
  4315. }
  4316. get altTextData() {
  4317. return this.#altText?.data;
  4318. }
  4319. set altTextData(data) {
  4320. if (!this.#altText) {
  4321. return;
  4322. }
  4323. this.#altText.data = data;
  4324. }
  4325. get guessedAltText() {
  4326. return this.#altText?.guessedText;
  4327. }
  4328. async setGuessedAltText(text) {
  4329. await this.#altText?.setGuessedText(text);
  4330. }
  4331. serializeAltText(isForCopying) {
  4332. return this.#altText?.serialize(isForCopying);
  4333. }
  4334. hasAltText() {
  4335. return !!this.#altText && !this.#altText.isEmpty();
  4336. }
  4337. hasAltTextData() {
  4338. return this.#altText?.hasData() ?? false;
  4339. }
  4340. render() {
  4341. this.div = document.createElement("div");
  4342. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  4343. this.div.className = this.name;
  4344. this.div.setAttribute("id", this.id);
  4345. this.div.tabIndex = this.#disabled ? -1 : 0;
  4346. if (!this._isVisible) {
  4347. this.div.classList.add("hidden");
  4348. }
  4349. this.setInForeground();
  4350. this.#addFocusListeners();
  4351. const [parentWidth, parentHeight] = this.parentDimensions;
  4352. if (this.parentRotation % 180 !== 0) {
  4353. this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
  4354. this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
  4355. }
  4356. const [tx, ty] = this.getInitialTranslation();
  4357. this.translate(tx, ty);
  4358. bindEvents(this, this.div, ["pointerdown"]);
  4359. if (this.isResizable && this._uiManager._supportsPinchToZoom) {
  4360. this.#touchManager ||= new TouchManager({
  4361. container: this.div,
  4362. isPinchingDisabled: () => !this.isSelected,
  4363. onPinchStart: this.#touchPinchStartCallback.bind(this),
  4364. onPinching: this.#touchPinchCallback.bind(this),
  4365. onPinchEnd: this.#touchPinchEndCallback.bind(this),
  4366. signal: this._uiManager._signal
  4367. });
  4368. }
  4369. this._uiManager._editorUndoBar?.hide();
  4370. return this.div;
  4371. }
  4372. #touchPinchStartCallback() {
  4373. this.#savedDimensions = {
  4374. savedX: this.x,
  4375. savedY: this.y,
  4376. savedWidth: this.width,
  4377. savedHeight: this.height
  4378. };
  4379. this.#altText?.toggle(false);
  4380. this.parent.togglePointerEvents(false);
  4381. }
  4382. #touchPinchCallback(_origin, prevDistance, distance) {
  4383. const slowDownFactor = 0.7;
  4384. let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor;
  4385. if (factor === 1) {
  4386. return;
  4387. }
  4388. const rotationMatrix = this.#getRotationMatrix(this.rotation);
  4389. const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
  4390. const [parentWidth, parentHeight] = this.parentDimensions;
  4391. const savedX = this.x;
  4392. const savedY = this.y;
  4393. const savedWidth = this.width;
  4394. const savedHeight = this.height;
  4395. const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
  4396. const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
  4397. factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
  4398. const newWidth = AnnotationEditor._round(savedWidth * factor);
  4399. const newHeight = AnnotationEditor._round(savedHeight * factor);
  4400. if (newWidth === savedWidth && newHeight === savedHeight) {
  4401. return;
  4402. }
  4403. this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight];
  4404. const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2);
  4405. const centerX = AnnotationEditor._round(savedX + transfCenterPoint[0]);
  4406. const centerY = AnnotationEditor._round(savedY + transfCenterPoint[1]);
  4407. const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2);
  4408. this.x = centerX - newTransfCenterPoint[0];
  4409. this.y = centerY - newTransfCenterPoint[1];
  4410. this.width = newWidth;
  4411. this.height = newHeight;
  4412. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  4413. this.fixAndSetPosition();
  4414. this._onResizing();
  4415. }
  4416. #touchPinchEndCallback() {
  4417. this.#altText?.toggle(true);
  4418. this.parent.togglePointerEvents(true);
  4419. this.#addResizeToUndoStack();
  4420. }
  4421. pointerdown(event) {
  4422. const {
  4423. isMac
  4424. } = util_FeatureTest.platform;
  4425. if (event.button !== 0 || event.ctrlKey && isMac) {
  4426. event.preventDefault();
  4427. return;
  4428. }
  4429. this.#hasBeenClicked = true;
  4430. if (this._isDraggable) {
  4431. this.#setUpDragSession(event);
  4432. return;
  4433. }
  4434. this.#selectOnPointerEvent(event);
  4435. }
  4436. get isSelected() {
  4437. return this._uiManager.isSelected(this);
  4438. }
  4439. #selectOnPointerEvent(event) {
  4440. const {
  4441. isMac
  4442. } = util_FeatureTest.platform;
  4443. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  4444. this.parent.toggleSelected(this);
  4445. } else {
  4446. this.parent.setSelected(this);
  4447. }
  4448. }
  4449. #setUpDragSession(event) {
  4450. const {
  4451. isSelected
  4452. } = this;
  4453. this._uiManager.setUpDragSession();
  4454. let hasDraggingStarted = false;
  4455. const ac = new AbortController();
  4456. const signal = this._uiManager.combinedSignal(ac);
  4457. const opts = {
  4458. capture: true,
  4459. passive: false,
  4460. signal
  4461. };
  4462. const cancelDrag = e => {
  4463. ac.abort();
  4464. this.#dragPointerId = null;
  4465. this.#hasBeenClicked = false;
  4466. if (!this._uiManager.endDragSession()) {
  4467. this.#selectOnPointerEvent(e);
  4468. }
  4469. if (hasDraggingStarted) {
  4470. this._onStopDragging();
  4471. }
  4472. };
  4473. if (isSelected) {
  4474. this.#prevDragX = event.clientX;
  4475. this.#prevDragY = event.clientY;
  4476. this.#dragPointerId = event.pointerId;
  4477. this.#dragPointerType = event.pointerType;
  4478. window.addEventListener("pointermove", e => {
  4479. if (!hasDraggingStarted) {
  4480. hasDraggingStarted = true;
  4481. this._onStartDragging();
  4482. }
  4483. const {
  4484. clientX: x,
  4485. clientY: y,
  4486. pointerId
  4487. } = e;
  4488. if (pointerId !== this.#dragPointerId) {
  4489. stopEvent(e);
  4490. return;
  4491. }
  4492. const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY);
  4493. this.#prevDragX = x;
  4494. this.#prevDragY = y;
  4495. this._uiManager.dragSelectedEditors(tx, ty);
  4496. }, opts);
  4497. window.addEventListener("touchmove", stopEvent, opts);
  4498. window.addEventListener("pointerdown", e => {
  4499. if (e.pointerType === this.#dragPointerType) {
  4500. if (this.#touchManager || e.isPrimary) {
  4501. cancelDrag(e);
  4502. }
  4503. }
  4504. stopEvent(e);
  4505. }, opts);
  4506. }
  4507. const pointerUpCallback = e => {
  4508. if (!this.#dragPointerId || this.#dragPointerId === e.pointerId) {
  4509. cancelDrag(e);
  4510. return;
  4511. }
  4512. stopEvent(e);
  4513. };
  4514. window.addEventListener("pointerup", pointerUpCallback, {
  4515. signal
  4516. });
  4517. window.addEventListener("blur", pointerUpCallback, {
  4518. signal
  4519. });
  4520. }
  4521. _onStartDragging() {}
  4522. _onStopDragging() {}
  4523. moveInDOM() {
  4524. if (this.#moveInDOMTimeout) {
  4525. clearTimeout(this.#moveInDOMTimeout);
  4526. }
  4527. this.#moveInDOMTimeout = setTimeout(() => {
  4528. this.#moveInDOMTimeout = null;
  4529. this.parent?.moveEditorInDOM(this);
  4530. }, 0);
  4531. }
  4532. _setParentAndPosition(parent, x, y) {
  4533. parent.changeParent(this);
  4534. this.x = x;
  4535. this.y = y;
  4536. this.fixAndSetPosition();
  4537. this._onTranslated();
  4538. }
  4539. getRect(tx, ty, rotation = this.rotation) {
  4540. const scale = this.parentScale;
  4541. const [pageWidth, pageHeight] = this.pageDimensions;
  4542. const [pageX, pageY] = this.pageTranslation;
  4543. const shiftX = tx / scale;
  4544. const shiftY = ty / scale;
  4545. const x = this.x * pageWidth;
  4546. const y = this.y * pageHeight;
  4547. const width = this.width * pageWidth;
  4548. const height = this.height * pageHeight;
  4549. switch (rotation) {
  4550. case 0:
  4551. return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
  4552. case 90:
  4553. return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
  4554. case 180:
  4555. return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
  4556. case 270:
  4557. return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
  4558. default:
  4559. throw new Error("Invalid rotation");
  4560. }
  4561. }
  4562. getRectInCurrentCoords(rect, pageHeight) {
  4563. const [x1, y1, x2, y2] = rect;
  4564. const width = x2 - x1;
  4565. const height = y2 - y1;
  4566. switch (this.rotation) {
  4567. case 0:
  4568. return [x1, pageHeight - y2, width, height];
  4569. case 90:
  4570. return [x1, pageHeight - y1, height, width];
  4571. case 180:
  4572. return [x2, pageHeight - y1, width, height];
  4573. case 270:
  4574. return [x2, pageHeight - y2, height, width];
  4575. default:
  4576. throw new Error("Invalid rotation");
  4577. }
  4578. }
  4579. onceAdded(focus) {}
  4580. isEmpty() {
  4581. return false;
  4582. }
  4583. enableEditMode() {
  4584. this.#isInEditMode = true;
  4585. }
  4586. disableEditMode() {
  4587. this.#isInEditMode = false;
  4588. }
  4589. isInEditMode() {
  4590. return this.#isInEditMode;
  4591. }
  4592. shouldGetKeyboardEvents() {
  4593. return this.#isResizerEnabledForKeyboard;
  4594. }
  4595. needsToBeRebuilt() {
  4596. return this.div && !this.isAttachedToDOM;
  4597. }
  4598. get isOnScreen() {
  4599. const {
  4600. top,
  4601. left,
  4602. bottom,
  4603. right
  4604. } = this.getClientDimensions();
  4605. const {
  4606. innerHeight,
  4607. innerWidth
  4608. } = window;
  4609. return left < innerWidth && right > 0 && top < innerHeight && bottom > 0;
  4610. }
  4611. #addFocusListeners() {
  4612. if (this.#focusAC || !this.div) {
  4613. return;
  4614. }
  4615. this.#focusAC = new AbortController();
  4616. const signal = this._uiManager.combinedSignal(this.#focusAC);
  4617. this.div.addEventListener("focusin", this.focusin.bind(this), {
  4618. signal
  4619. });
  4620. this.div.addEventListener("focusout", this.focusout.bind(this), {
  4621. signal
  4622. });
  4623. }
  4624. rebuild() {
  4625. this.#addFocusListeners();
  4626. }
  4627. rotate(_angle) {}
  4628. resize() {}
  4629. serializeDeleted() {
  4630. return {
  4631. id: this.annotationElementId,
  4632. deleted: true,
  4633. pageIndex: this.pageIndex,
  4634. popupRef: this._initialData?.popupRef || ""
  4635. };
  4636. }
  4637. serialize(isForCopying = false, context = null) {
  4638. unreachable("An editor must be serializable");
  4639. }
  4640. static async deserialize(data, parent, uiManager) {
  4641. const editor = new this.prototype.constructor({
  4642. parent,
  4643. id: parent.getNextId(),
  4644. uiManager
  4645. });
  4646. editor.rotation = data.rotation;
  4647. editor.#accessibilityData = data.accessibilityData;
  4648. const [pageWidth, pageHeight] = editor.pageDimensions;
  4649. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  4650. editor.x = x / pageWidth;
  4651. editor.y = y / pageHeight;
  4652. editor.width = width / pageWidth;
  4653. editor.height = height / pageHeight;
  4654. return editor;
  4655. }
  4656. get hasBeenModified() {
  4657. return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
  4658. }
  4659. remove() {
  4660. this.#focusAC?.abort();
  4661. this.#focusAC = null;
  4662. if (!this.isEmpty()) {
  4663. this.commit();
  4664. }
  4665. if (this.parent) {
  4666. this.parent.remove(this);
  4667. } else {
  4668. this._uiManager.removeEditor(this);
  4669. }
  4670. if (this.#moveInDOMTimeout) {
  4671. clearTimeout(this.#moveInDOMTimeout);
  4672. this.#moveInDOMTimeout = null;
  4673. }
  4674. this.#stopResizing();
  4675. this.removeEditToolbar();
  4676. if (this.#telemetryTimeouts) {
  4677. for (const timeout of this.#telemetryTimeouts.values()) {
  4678. clearTimeout(timeout);
  4679. }
  4680. this.#telemetryTimeouts = null;
  4681. }
  4682. this.parent = null;
  4683. this.#touchManager?.destroy();
  4684. this.#touchManager = null;
  4685. }
  4686. get isResizable() {
  4687. return false;
  4688. }
  4689. makeResizable() {
  4690. if (this.isResizable) {
  4691. this.#createResizers();
  4692. this.#resizersDiv.classList.remove("hidden");
  4693. bindEvents(this, this.div, ["keydown"]);
  4694. }
  4695. }
  4696. get toolbarPosition() {
  4697. return null;
  4698. }
  4699. keydown(event) {
  4700. if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
  4701. return;
  4702. }
  4703. this._uiManager.setSelected(this);
  4704. this.#savedDimensions = {
  4705. savedX: this.x,
  4706. savedY: this.y,
  4707. savedWidth: this.width,
  4708. savedHeight: this.height
  4709. };
  4710. const children = this.#resizersDiv.children;
  4711. if (!this.#allResizerDivs) {
  4712. this.#allResizerDivs = Array.from(children);
  4713. const boundResizerKeydown = this.#resizerKeydown.bind(this);
  4714. const boundResizerBlur = this.#resizerBlur.bind(this);
  4715. const signal = this._uiManager._signal;
  4716. for (const div of this.#allResizerDivs) {
  4717. const name = div.getAttribute("data-resizer-name");
  4718. div.setAttribute("role", "spinbutton");
  4719. div.addEventListener("keydown", boundResizerKeydown, {
  4720. signal
  4721. });
  4722. div.addEventListener("blur", boundResizerBlur, {
  4723. signal
  4724. });
  4725. div.addEventListener("focus", this.#resizerFocus.bind(this, name), {
  4726. signal
  4727. });
  4728. div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  4729. }
  4730. }
  4731. const first = this.#allResizerDivs[0];
  4732. let firstPosition = 0;
  4733. for (const div of children) {
  4734. if (div === first) {
  4735. break;
  4736. }
  4737. firstPosition++;
  4738. }
  4739. const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
  4740. if (nextFirstPosition !== firstPosition) {
  4741. if (nextFirstPosition < firstPosition) {
  4742. for (let i = 0; i < firstPosition - nextFirstPosition; i++) {
  4743. this.#resizersDiv.append(this.#resizersDiv.firstChild);
  4744. }
  4745. } else if (nextFirstPosition > firstPosition) {
  4746. for (let i = 0; i < nextFirstPosition - firstPosition; i++) {
  4747. this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
  4748. }
  4749. }
  4750. let i = 0;
  4751. for (const child of children) {
  4752. const div = this.#allResizerDivs[i++];
  4753. const name = div.getAttribute("data-resizer-name");
  4754. child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  4755. }
  4756. }
  4757. this.#setResizerTabIndex(0);
  4758. this.#isResizerEnabledForKeyboard = true;
  4759. this.#resizersDiv.firstChild.focus({
  4760. focusVisible: true
  4761. });
  4762. event.preventDefault();
  4763. event.stopImmediatePropagation();
  4764. }
  4765. #resizerKeydown(event) {
  4766. AnnotationEditor._resizerKeyboardManager.exec(this, event);
  4767. }
  4768. #resizerBlur(event) {
  4769. if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
  4770. this.#stopResizing();
  4771. }
  4772. }
  4773. #resizerFocus(name) {
  4774. this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
  4775. }
  4776. #setResizerTabIndex(value) {
  4777. if (!this.#allResizerDivs) {
  4778. return;
  4779. }
  4780. for (const div of this.#allResizerDivs) {
  4781. div.tabIndex = value;
  4782. }
  4783. }
  4784. _resizeWithKeyboard(x, y) {
  4785. if (!this.#isResizerEnabledForKeyboard) {
  4786. return;
  4787. }
  4788. this.#resizerPointermove(this.#focusedResizerName, {
  4789. deltaX: x,
  4790. deltaY: y,
  4791. fromKeyboard: true
  4792. });
  4793. }
  4794. #stopResizing() {
  4795. this.#isResizerEnabledForKeyboard = false;
  4796. this.#setResizerTabIndex(-1);
  4797. this.#addResizeToUndoStack();
  4798. }
  4799. _stopResizingWithKeyboard() {
  4800. this.#stopResizing();
  4801. this.div.focus();
  4802. }
  4803. select() {
  4804. this.makeResizable();
  4805. this.div?.classList.add("selectedEditor");
  4806. if (!this._editToolbar) {
  4807. this.addEditToolbar().then(() => {
  4808. if (this.div?.classList.contains("selectedEditor")) {
  4809. this._editToolbar?.show();
  4810. }
  4811. });
  4812. return;
  4813. }
  4814. this._editToolbar?.show();
  4815. this.#altText?.toggleAltTextBadge(false);
  4816. }
  4817. unselect() {
  4818. this.#resizersDiv?.classList.add("hidden");
  4819. this.div?.classList.remove("selectedEditor");
  4820. if (this.div?.contains(document.activeElement)) {
  4821. this._uiManager.currentLayer.div.focus({
  4822. preventScroll: true
  4823. });
  4824. }
  4825. this._editToolbar?.hide();
  4826. this.#altText?.toggleAltTextBadge(true);
  4827. }
  4828. updateParams(type, value) {}
  4829. disableEditing() {}
  4830. enableEditing() {}
  4831. enterInEditMode() {}
  4832. getImageForAltText() {
  4833. return null;
  4834. }
  4835. get contentDiv() {
  4836. return this.div;
  4837. }
  4838. get isEditing() {
  4839. return this.#isEditing;
  4840. }
  4841. set isEditing(value) {
  4842. this.#isEditing = value;
  4843. if (!this.parent) {
  4844. return;
  4845. }
  4846. if (value) {
  4847. this.parent.setSelected(this);
  4848. this.parent.setActiveEditor(this);
  4849. } else {
  4850. this.parent.setActiveEditor(null);
  4851. }
  4852. }
  4853. setAspectRatio(width, height) {
  4854. this.#keepAspectRatio = true;
  4855. const aspectRatio = width / height;
  4856. const {
  4857. style
  4858. } = this.div;
  4859. style.aspectRatio = aspectRatio;
  4860. style.height = "auto";
  4861. }
  4862. static get MIN_SIZE() {
  4863. return 16;
  4864. }
  4865. static canCreateNewEmptyEditor() {
  4866. return true;
  4867. }
  4868. get telemetryInitialData() {
  4869. return {
  4870. action: "added"
  4871. };
  4872. }
  4873. get telemetryFinalData() {
  4874. return null;
  4875. }
  4876. _reportTelemetry(data, mustWait = false) {
  4877. if (mustWait) {
  4878. this.#telemetryTimeouts ||= new Map();
  4879. const {
  4880. action
  4881. } = data;
  4882. let timeout = this.#telemetryTimeouts.get(action);
  4883. if (timeout) {
  4884. clearTimeout(timeout);
  4885. }
  4886. timeout = setTimeout(() => {
  4887. this._reportTelemetry(data);
  4888. this.#telemetryTimeouts.delete(action);
  4889. if (this.#telemetryTimeouts.size === 0) {
  4890. this.#telemetryTimeouts = null;
  4891. }
  4892. }, AnnotationEditor._telemetryTimeout);
  4893. this.#telemetryTimeouts.set(action, timeout);
  4894. return;
  4895. }
  4896. data.type ||= this.editorType;
  4897. this._uiManager._eventBus.dispatch("reporttelemetry", {
  4898. source: this,
  4899. details: {
  4900. type: "editing",
  4901. data
  4902. }
  4903. });
  4904. }
  4905. show(visible = this._isVisible) {
  4906. this.div.classList.toggle("hidden", !visible);
  4907. this._isVisible = visible;
  4908. }
  4909. enable() {
  4910. if (this.div) {
  4911. this.div.tabIndex = 0;
  4912. }
  4913. this.#disabled = false;
  4914. }
  4915. disable() {
  4916. if (this.div) {
  4917. this.div.tabIndex = -1;
  4918. }
  4919. this.#disabled = true;
  4920. }
  4921. renderAnnotationElement(annotation) {
  4922. let content = annotation.container.querySelector(".annotationContent");
  4923. if (!content) {
  4924. content = document.createElement("div");
  4925. content.classList.add("annotationContent", this.editorType);
  4926. annotation.container.prepend(content);
  4927. } else if (content.nodeName === "CANVAS") {
  4928. const canvas = content;
  4929. content = document.createElement("div");
  4930. content.classList.add("annotationContent", this.editorType);
  4931. canvas.before(content);
  4932. }
  4933. return content;
  4934. }
  4935. resetAnnotationElement(annotation) {
  4936. const {
  4937. firstChild
  4938. } = annotation.container;
  4939. if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
  4940. firstChild.remove();
  4941. }
  4942. }
  4943. }
  4944. class FakeEditor extends AnnotationEditor {
  4945. constructor(params) {
  4946. super(params);
  4947. this.annotationElementId = params.annotationElementId;
  4948. this.deleted = true;
  4949. }
  4950. serialize() {
  4951. return this.serializeDeleted();
  4952. }
  4953. }
  4954. ;// ./src/shared/murmurhash3.js
  4955. const SEED = 0xc3d2e1f0;
  4956. const MASK_HIGH = 0xffff0000;
  4957. const MASK_LOW = 0xffff;
  4958. class MurmurHash3_64 {
  4959. constructor(seed) {
  4960. this.h1 = seed ? seed & 0xffffffff : SEED;
  4961. this.h2 = seed ? seed & 0xffffffff : SEED;
  4962. }
  4963. update(input) {
  4964. let data, length;
  4965. if (typeof input === "string") {
  4966. data = new Uint8Array(input.length * 2);
  4967. length = 0;
  4968. for (let i = 0, ii = input.length; i < ii; i++) {
  4969. const code = input.charCodeAt(i);
  4970. if (code <= 0xff) {
  4971. data[length++] = code;
  4972. } else {
  4973. data[length++] = code >>> 8;
  4974. data[length++] = code & 0xff;
  4975. }
  4976. }
  4977. } else if (ArrayBuffer.isView(input)) {
  4978. data = input.slice();
  4979. length = data.byteLength;
  4980. } else {
  4981. throw new Error("Invalid data format, must be a string or TypedArray.");
  4982. }
  4983. const blockCounts = length >> 2;
  4984. const tailLength = length - blockCounts * 4;
  4985. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  4986. let k1 = 0,
  4987. k2 = 0;
  4988. let h1 = this.h1,
  4989. h2 = this.h2;
  4990. const C1 = 0xcc9e2d51,
  4991. C2 = 0x1b873593;
  4992. const C1_LOW = C1 & MASK_LOW,
  4993. C2_LOW = C2 & MASK_LOW;
  4994. for (let i = 0; i < blockCounts; i++) {
  4995. if (i & 1) {
  4996. k1 = dataUint32[i];
  4997. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4998. k1 = k1 << 15 | k1 >>> 17;
  4999. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  5000. h1 ^= k1;
  5001. h1 = h1 << 13 | h1 >>> 19;
  5002. h1 = h1 * 5 + 0xe6546b64;
  5003. } else {
  5004. k2 = dataUint32[i];
  5005. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  5006. k2 = k2 << 15 | k2 >>> 17;
  5007. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  5008. h2 ^= k2;
  5009. h2 = h2 << 13 | h2 >>> 19;
  5010. h2 = h2 * 5 + 0xe6546b64;
  5011. }
  5012. }
  5013. k1 = 0;
  5014. switch (tailLength) {
  5015. case 3:
  5016. k1 ^= data[blockCounts * 4 + 2] << 16;
  5017. case 2:
  5018. k1 ^= data[blockCounts * 4 + 1] << 8;
  5019. case 1:
  5020. k1 ^= data[blockCounts * 4];
  5021. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  5022. k1 = k1 << 15 | k1 >>> 17;
  5023. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  5024. if (blockCounts & 1) {
  5025. h1 ^= k1;
  5026. } else {
  5027. h2 ^= k1;
  5028. }
  5029. }
  5030. this.h1 = h1;
  5031. this.h2 = h2;
  5032. }
  5033. hexdigest() {
  5034. let h1 = this.h1,
  5035. h2 = this.h2;
  5036. h1 ^= h2 >>> 1;
  5037. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  5038. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  5039. h1 ^= h2 >>> 1;
  5040. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  5041. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  5042. h1 ^= h2 >>> 1;
  5043. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  5044. }
  5045. }
  5046. ;// ./src/display/annotation_storage.js
  5047. const SerializableEmpty = Object.freeze({
  5048. map: null,
  5049. hash: "",
  5050. transfer: undefined
  5051. });
  5052. class AnnotationStorage {
  5053. #modified = false;
  5054. #modifiedIds = null;
  5055. #storage = new Map();
  5056. constructor() {
  5057. this.onSetModified = null;
  5058. this.onResetModified = null;
  5059. this.onAnnotationEditor = null;
  5060. }
  5061. getValue(key, defaultValue) {
  5062. const value = this.#storage.get(key);
  5063. if (value === undefined) {
  5064. return defaultValue;
  5065. }
  5066. return Object.assign(defaultValue, value);
  5067. }
  5068. getRawValue(key) {
  5069. return this.#storage.get(key);
  5070. }
  5071. remove(key) {
  5072. this.#storage.delete(key);
  5073. if (this.#storage.size === 0) {
  5074. this.resetModified();
  5075. }
  5076. if (typeof this.onAnnotationEditor === "function") {
  5077. for (const value of this.#storage.values()) {
  5078. if (value instanceof AnnotationEditor) {
  5079. return;
  5080. }
  5081. }
  5082. this.onAnnotationEditor(null);
  5083. }
  5084. }
  5085. setValue(key, value) {
  5086. const obj = this.#storage.get(key);
  5087. let modified = false;
  5088. if (obj !== undefined) {
  5089. for (const [entry, val] of Object.entries(value)) {
  5090. if (obj[entry] !== val) {
  5091. modified = true;
  5092. obj[entry] = val;
  5093. }
  5094. }
  5095. } else {
  5096. modified = true;
  5097. this.#storage.set(key, value);
  5098. }
  5099. if (modified) {
  5100. this.#setModified();
  5101. }
  5102. if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  5103. this.onAnnotationEditor(value.constructor._type);
  5104. }
  5105. }
  5106. has(key) {
  5107. return this.#storage.has(key);
  5108. }
  5109. getAll() {
  5110. return this.#storage.size > 0 ? objectFromMap(this.#storage) : null;
  5111. }
  5112. setAll(obj) {
  5113. for (const [key, val] of Object.entries(obj)) {
  5114. this.setValue(key, val);
  5115. }
  5116. }
  5117. get size() {
  5118. return this.#storage.size;
  5119. }
  5120. #setModified() {
  5121. if (!this.#modified) {
  5122. this.#modified = true;
  5123. if (typeof this.onSetModified === "function") {
  5124. this.onSetModified();
  5125. }
  5126. }
  5127. }
  5128. resetModified() {
  5129. if (this.#modified) {
  5130. this.#modified = false;
  5131. if (typeof this.onResetModified === "function") {
  5132. this.onResetModified();
  5133. }
  5134. }
  5135. }
  5136. get print() {
  5137. return new PrintAnnotationStorage(this);
  5138. }
  5139. get serializable() {
  5140. if (this.#storage.size === 0) {
  5141. return SerializableEmpty;
  5142. }
  5143. const map = new Map(),
  5144. hash = new MurmurHash3_64(),
  5145. transfer = [];
  5146. const context = Object.create(null);
  5147. let hasBitmap = false;
  5148. for (const [key, val] of this.#storage) {
  5149. const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;
  5150. if (serialized) {
  5151. map.set(key, serialized);
  5152. hash.update(`${key}:${JSON.stringify(serialized)}`);
  5153. hasBitmap ||= !!serialized.bitmap;
  5154. }
  5155. }
  5156. if (hasBitmap) {
  5157. for (const value of map.values()) {
  5158. if (value.bitmap) {
  5159. transfer.push(value.bitmap);
  5160. }
  5161. }
  5162. }
  5163. return map.size > 0 ? {
  5164. map,
  5165. hash: hash.hexdigest(),
  5166. transfer
  5167. } : SerializableEmpty;
  5168. }
  5169. get editorStats() {
  5170. let stats = null;
  5171. const typeToEditor = new Map();
  5172. for (const value of this.#storage.values()) {
  5173. if (!(value instanceof AnnotationEditor)) {
  5174. continue;
  5175. }
  5176. const editorStats = value.telemetryFinalData;
  5177. if (!editorStats) {
  5178. continue;
  5179. }
  5180. const {
  5181. type
  5182. } = editorStats;
  5183. if (!typeToEditor.has(type)) {
  5184. typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
  5185. }
  5186. stats ||= Object.create(null);
  5187. const map = stats[type] ||= new Map();
  5188. for (const [key, val] of Object.entries(editorStats)) {
  5189. if (key === "type") {
  5190. continue;
  5191. }
  5192. let counters = map.get(key);
  5193. if (!counters) {
  5194. counters = new Map();
  5195. map.set(key, counters);
  5196. }
  5197. const count = counters.get(val) ?? 0;
  5198. counters.set(val, count + 1);
  5199. }
  5200. }
  5201. for (const [type, editor] of typeToEditor) {
  5202. stats[type] = editor.computeTelemetryFinalData(stats[type]);
  5203. }
  5204. return stats;
  5205. }
  5206. resetModifiedIds() {
  5207. this.#modifiedIds = null;
  5208. }
  5209. get modifiedIds() {
  5210. if (this.#modifiedIds) {
  5211. return this.#modifiedIds;
  5212. }
  5213. const ids = [];
  5214. for (const value of this.#storage.values()) {
  5215. if (!(value instanceof AnnotationEditor) || !value.annotationElementId || !value.serialize()) {
  5216. continue;
  5217. }
  5218. ids.push(value.annotationElementId);
  5219. }
  5220. return this.#modifiedIds = {
  5221. ids: new Set(ids),
  5222. hash: ids.join(",")
  5223. };
  5224. }
  5225. }
  5226. class PrintAnnotationStorage extends AnnotationStorage {
  5227. #serializable;
  5228. constructor(parent) {
  5229. super();
  5230. const {
  5231. map,
  5232. hash,
  5233. transfer
  5234. } = parent.serializable;
  5235. const clone = structuredClone(map, transfer ? {
  5236. transfer
  5237. } : null);
  5238. this.#serializable = {
  5239. map: clone,
  5240. hash,
  5241. transfer
  5242. };
  5243. }
  5244. get print() {
  5245. unreachable("Should not call PrintAnnotationStorage.print");
  5246. }
  5247. get serializable() {
  5248. return this.#serializable;
  5249. }
  5250. get modifiedIds() {
  5251. return shadow(this, "modifiedIds", {
  5252. ids: new Set(),
  5253. hash: ""
  5254. });
  5255. }
  5256. }
  5257. ;// ./src/display/font_loader.js
  5258. class FontLoader {
  5259. #systemFonts = new Set();
  5260. constructor({
  5261. ownerDocument = globalThis.document,
  5262. styleElement = null
  5263. }) {
  5264. this._document = ownerDocument;
  5265. this.nativeFontFaces = new Set();
  5266. this.styleElement = null;
  5267. this.loadingRequests = [];
  5268. this.loadTestFontId = 0;
  5269. }
  5270. addNativeFontFace(nativeFontFace) {
  5271. this.nativeFontFaces.add(nativeFontFace);
  5272. this._document.fonts.add(nativeFontFace);
  5273. }
  5274. removeNativeFontFace(nativeFontFace) {
  5275. this.nativeFontFaces.delete(nativeFontFace);
  5276. this._document.fonts.delete(nativeFontFace);
  5277. }
  5278. insertRule(rule) {
  5279. if (!this.styleElement) {
  5280. this.styleElement = this._document.createElement("style");
  5281. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  5282. }
  5283. const styleSheet = this.styleElement.sheet;
  5284. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5285. }
  5286. clear() {
  5287. for (const nativeFontFace of this.nativeFontFaces) {
  5288. this._document.fonts.delete(nativeFontFace);
  5289. }
  5290. this.nativeFontFaces.clear();
  5291. this.#systemFonts.clear();
  5292. if (this.styleElement) {
  5293. this.styleElement.remove();
  5294. this.styleElement = null;
  5295. }
  5296. }
  5297. async loadSystemFont({
  5298. systemFontInfo: info,
  5299. _inspectFont
  5300. }) {
  5301. if (!info || this.#systemFonts.has(info.loadedName)) {
  5302. return;
  5303. }
  5304. assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
  5305. if (this.isFontLoadingAPISupported) {
  5306. const {
  5307. loadedName,
  5308. src,
  5309. style
  5310. } = info;
  5311. const fontFace = new FontFace(loadedName, src, style);
  5312. this.addNativeFontFace(fontFace);
  5313. try {
  5314. await fontFace.load();
  5315. this.#systemFonts.add(loadedName);
  5316. _inspectFont?.(info);
  5317. } catch {
  5318. warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);
  5319. this.removeNativeFontFace(fontFace);
  5320. }
  5321. return;
  5322. }
  5323. unreachable("Not implemented: loadSystemFont without the Font Loading API.");
  5324. }
  5325. async bind(font) {
  5326. if (font.attached || font.missingFile && !font.systemFontInfo) {
  5327. return;
  5328. }
  5329. font.attached = true;
  5330. if (font.systemFontInfo) {
  5331. await this.loadSystemFont(font);
  5332. return;
  5333. }
  5334. if (this.isFontLoadingAPISupported) {
  5335. const nativeFontFace = font.createNativeFontFace();
  5336. if (nativeFontFace) {
  5337. this.addNativeFontFace(nativeFontFace);
  5338. try {
  5339. await nativeFontFace.loaded;
  5340. } catch (ex) {
  5341. warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  5342. font.disableFontFace = true;
  5343. throw ex;
  5344. }
  5345. }
  5346. return;
  5347. }
  5348. const rule = font.createFontFaceRule();
  5349. if (rule) {
  5350. this.insertRule(rule);
  5351. if (this.isSyncFontLoadingSupported) {
  5352. return;
  5353. }
  5354. await new Promise(resolve => {
  5355. const request = this._queueLoadingCallback(resolve);
  5356. this._prepareFontLoadEvent(font, request);
  5357. });
  5358. }
  5359. }
  5360. get isFontLoadingAPISupported() {
  5361. const hasFonts = !!this._document?.fonts;
  5362. return shadow(this, "isFontLoadingAPISupported", hasFonts);
  5363. }
  5364. get isSyncFontLoadingSupported() {
  5365. let supported = false;
  5366. if (isNodeJS) {
  5367. supported = true;
  5368. } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
  5369. supported = true;
  5370. }
  5371. return shadow(this, "isSyncFontLoadingSupported", supported);
  5372. }
  5373. _queueLoadingCallback(callback) {
  5374. function completeRequest() {
  5375. assert(!request.done, "completeRequest() cannot be called twice.");
  5376. request.done = true;
  5377. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  5378. const otherRequest = loadingRequests.shift();
  5379. setTimeout(otherRequest.callback, 0);
  5380. }
  5381. }
  5382. const {
  5383. loadingRequests
  5384. } = this;
  5385. const request = {
  5386. done: false,
  5387. complete: completeRequest,
  5388. callback
  5389. };
  5390. loadingRequests.push(request);
  5391. return request;
  5392. }
  5393. get _loadTestFont() {
  5394. 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==");
  5395. return shadow(this, "_loadTestFont", testFont);
  5396. }
  5397. _prepareFontLoadEvent(font, request) {
  5398. function int32(data, offset) {
  5399. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  5400. }
  5401. function spliceString(s, offset, remove, insert) {
  5402. const chunk1 = s.substring(0, offset);
  5403. const chunk2 = s.substring(offset + remove);
  5404. return chunk1 + insert + chunk2;
  5405. }
  5406. let i, ii;
  5407. const canvas = this._document.createElement("canvas");
  5408. canvas.width = 1;
  5409. canvas.height = 1;
  5410. const ctx = canvas.getContext("2d");
  5411. let called = 0;
  5412. function isFontReady(name, callback) {
  5413. if (++called > 30) {
  5414. warn("Load test font never loaded.");
  5415. callback();
  5416. return;
  5417. }
  5418. ctx.font = "30px " + name;
  5419. ctx.fillText(".", 0, 20);
  5420. const imageData = ctx.getImageData(0, 0, 1, 1);
  5421. if (imageData.data[3] > 0) {
  5422. callback();
  5423. return;
  5424. }
  5425. setTimeout(isFontReady.bind(null, name, callback));
  5426. }
  5427. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  5428. let data = this._loadTestFont;
  5429. const COMMENT_OFFSET = 976;
  5430. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  5431. const CFF_CHECKSUM_OFFSET = 16;
  5432. const XXXX_VALUE = 0x58585858;
  5433. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5434. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5435. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  5436. }
  5437. if (i < loadTestFontId.length) {
  5438. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  5439. }
  5440. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5441. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  5442. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  5443. this.insertRule(rule);
  5444. const div = this._document.createElement("div");
  5445. div.style.visibility = "hidden";
  5446. div.style.width = div.style.height = "10px";
  5447. div.style.position = "absolute";
  5448. div.style.top = div.style.left = "0px";
  5449. for (const name of [font.loadedName, loadTestFontId]) {
  5450. const span = this._document.createElement("span");
  5451. span.textContent = "Hi";
  5452. span.style.fontFamily = name;
  5453. div.append(span);
  5454. }
  5455. this._document.body.append(div);
  5456. isFontReady(loadTestFontId, () => {
  5457. div.remove();
  5458. request.complete();
  5459. });
  5460. }
  5461. }
  5462. class FontFaceObject {
  5463. constructor(translatedData, {
  5464. disableFontFace = false,
  5465. fontExtraProperties = false,
  5466. inspectFont = null
  5467. }) {
  5468. this.compiledGlyphs = Object.create(null);
  5469. for (const i in translatedData) {
  5470. this[i] = translatedData[i];
  5471. }
  5472. this.disableFontFace = disableFontFace === true;
  5473. this.fontExtraProperties = fontExtraProperties === true;
  5474. this._inspectFont = inspectFont;
  5475. }
  5476. createNativeFontFace() {
  5477. if (!this.data || this.disableFontFace) {
  5478. return null;
  5479. }
  5480. let nativeFontFace;
  5481. if (!this.cssFontInfo) {
  5482. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5483. } else {
  5484. const css = {
  5485. weight: this.cssFontInfo.fontWeight
  5486. };
  5487. if (this.cssFontInfo.italicAngle) {
  5488. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  5489. }
  5490. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  5491. }
  5492. this._inspectFont?.(this);
  5493. return nativeFontFace;
  5494. }
  5495. createFontFaceRule() {
  5496. if (!this.data || this.disableFontFace) {
  5497. return null;
  5498. }
  5499. const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;
  5500. let rule;
  5501. if (!this.cssFontInfo) {
  5502. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  5503. } else {
  5504. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  5505. if (this.cssFontInfo.italicAngle) {
  5506. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  5507. }
  5508. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  5509. }
  5510. this._inspectFont?.(this, url);
  5511. return rule;
  5512. }
  5513. getPathGenerator(objs, character) {
  5514. if (this.compiledGlyphs[character] !== undefined) {
  5515. return this.compiledGlyphs[character];
  5516. }
  5517. const objId = this.loadedName + "_path_" + character;
  5518. let cmds;
  5519. try {
  5520. cmds = objs.get(objId);
  5521. } catch (ex) {
  5522. warn(`getPathGenerator - ignoring character: "${ex}".`);
  5523. }
  5524. const path = new Path2D(cmds || "");
  5525. if (!this.fontExtraProperties) {
  5526. objs.delete(objId);
  5527. }
  5528. return this.compiledGlyphs[character] = path;
  5529. }
  5530. }
  5531. ;// ./src/shared/message_handler.js
  5532. const CallbackKind = {
  5533. DATA: 1,
  5534. ERROR: 2
  5535. };
  5536. const StreamKind = {
  5537. CANCEL: 1,
  5538. CANCEL_COMPLETE: 2,
  5539. CLOSE: 3,
  5540. ENQUEUE: 4,
  5541. ERROR: 5,
  5542. PULL: 6,
  5543. PULL_COMPLETE: 7,
  5544. START_COMPLETE: 8
  5545. };
  5546. function onFn() {}
  5547. function wrapReason(ex) {
  5548. if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof MissingPDFException || ex instanceof PasswordException || ex instanceof UnexpectedResponseException || ex instanceof UnknownErrorException) {
  5549. return ex;
  5550. }
  5551. if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) {
  5552. unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  5553. }
  5554. switch (ex.name) {
  5555. case "AbortException":
  5556. return new AbortException(ex.message);
  5557. case "InvalidPDFException":
  5558. return new InvalidPDFException(ex.message);
  5559. case "MissingPDFException":
  5560. return new MissingPDFException(ex.message);
  5561. case "PasswordException":
  5562. return new PasswordException(ex.message, ex.code);
  5563. case "UnexpectedResponseException":
  5564. return new UnexpectedResponseException(ex.message, ex.status);
  5565. case "UnknownErrorException":
  5566. return new UnknownErrorException(ex.message, ex.details);
  5567. }
  5568. return new UnknownErrorException(ex.message, ex.toString());
  5569. }
  5570. class MessageHandler {
  5571. #messageAC = new AbortController();
  5572. constructor(sourceName, targetName, comObj) {
  5573. this.sourceName = sourceName;
  5574. this.targetName = targetName;
  5575. this.comObj = comObj;
  5576. this.callbackId = 1;
  5577. this.streamId = 1;
  5578. this.streamSinks = Object.create(null);
  5579. this.streamControllers = Object.create(null);
  5580. this.callbackCapabilities = Object.create(null);
  5581. this.actionHandler = Object.create(null);
  5582. comObj.addEventListener("message", this.#onMessage.bind(this), {
  5583. signal: this.#messageAC.signal
  5584. });
  5585. }
  5586. #onMessage({
  5587. data
  5588. }) {
  5589. if (data.targetName !== this.sourceName) {
  5590. return;
  5591. }
  5592. if (data.stream) {
  5593. this.#processStreamMessage(data);
  5594. return;
  5595. }
  5596. if (data.callback) {
  5597. const callbackId = data.callbackId;
  5598. const capability = this.callbackCapabilities[callbackId];
  5599. if (!capability) {
  5600. throw new Error(`Cannot resolve callback ${callbackId}`);
  5601. }
  5602. delete this.callbackCapabilities[callbackId];
  5603. if (data.callback === CallbackKind.DATA) {
  5604. capability.resolve(data.data);
  5605. } else if (data.callback === CallbackKind.ERROR) {
  5606. capability.reject(wrapReason(data.reason));
  5607. } else {
  5608. throw new Error("Unexpected callback case");
  5609. }
  5610. return;
  5611. }
  5612. const action = this.actionHandler[data.action];
  5613. if (!action) {
  5614. throw new Error(`Unknown action from worker: ${data.action}`);
  5615. }
  5616. if (data.callbackId) {
  5617. const sourceName = this.sourceName,
  5618. targetName = data.sourceName,
  5619. comObj = this.comObj;
  5620. Promise.try(action, data.data).then(function (result) {
  5621. comObj.postMessage({
  5622. sourceName,
  5623. targetName,
  5624. callback: CallbackKind.DATA,
  5625. callbackId: data.callbackId,
  5626. data: result
  5627. });
  5628. }, function (reason) {
  5629. comObj.postMessage({
  5630. sourceName,
  5631. targetName,
  5632. callback: CallbackKind.ERROR,
  5633. callbackId: data.callbackId,
  5634. reason: wrapReason(reason)
  5635. });
  5636. });
  5637. return;
  5638. }
  5639. if (data.streamId) {
  5640. this.#createStreamSink(data);
  5641. return;
  5642. }
  5643. action(data.data);
  5644. }
  5645. on(actionName, handler) {
  5646. const ah = this.actionHandler;
  5647. if (ah[actionName]) {
  5648. throw new Error(`There is already an actionName called "${actionName}"`);
  5649. }
  5650. ah[actionName] = handler;
  5651. }
  5652. send(actionName, data, transfers) {
  5653. this.comObj.postMessage({
  5654. sourceName: this.sourceName,
  5655. targetName: this.targetName,
  5656. action: actionName,
  5657. data
  5658. }, transfers);
  5659. }
  5660. sendWithPromise(actionName, data, transfers) {
  5661. const callbackId = this.callbackId++;
  5662. const capability = Promise.withResolvers();
  5663. this.callbackCapabilities[callbackId] = capability;
  5664. try {
  5665. this.comObj.postMessage({
  5666. sourceName: this.sourceName,
  5667. targetName: this.targetName,
  5668. action: actionName,
  5669. callbackId,
  5670. data
  5671. }, transfers);
  5672. } catch (ex) {
  5673. capability.reject(ex);
  5674. }
  5675. return capability.promise;
  5676. }
  5677. sendWithStream(actionName, data, queueingStrategy, transfers) {
  5678. const streamId = this.streamId++,
  5679. sourceName = this.sourceName,
  5680. targetName = this.targetName,
  5681. comObj = this.comObj;
  5682. return new ReadableStream({
  5683. start: controller => {
  5684. const startCapability = Promise.withResolvers();
  5685. this.streamControllers[streamId] = {
  5686. controller,
  5687. startCall: startCapability,
  5688. pullCall: null,
  5689. cancelCall: null,
  5690. isClosed: false
  5691. };
  5692. comObj.postMessage({
  5693. sourceName,
  5694. targetName,
  5695. action: actionName,
  5696. streamId,
  5697. data,
  5698. desiredSize: controller.desiredSize
  5699. }, transfers);
  5700. return startCapability.promise;
  5701. },
  5702. pull: controller => {
  5703. const pullCapability = Promise.withResolvers();
  5704. this.streamControllers[streamId].pullCall = pullCapability;
  5705. comObj.postMessage({
  5706. sourceName,
  5707. targetName,
  5708. stream: StreamKind.PULL,
  5709. streamId,
  5710. desiredSize: controller.desiredSize
  5711. });
  5712. return pullCapability.promise;
  5713. },
  5714. cancel: reason => {
  5715. assert(reason instanceof Error, "cancel must have a valid reason");
  5716. const cancelCapability = Promise.withResolvers();
  5717. this.streamControllers[streamId].cancelCall = cancelCapability;
  5718. this.streamControllers[streamId].isClosed = true;
  5719. comObj.postMessage({
  5720. sourceName,
  5721. targetName,
  5722. stream: StreamKind.CANCEL,
  5723. streamId,
  5724. reason: wrapReason(reason)
  5725. });
  5726. return cancelCapability.promise;
  5727. }
  5728. }, queueingStrategy);
  5729. }
  5730. #createStreamSink(data) {
  5731. const streamId = data.streamId,
  5732. sourceName = this.sourceName,
  5733. targetName = data.sourceName,
  5734. comObj = this.comObj;
  5735. const self = this,
  5736. action = this.actionHandler[data.action];
  5737. const streamSink = {
  5738. enqueue(chunk, size = 1, transfers) {
  5739. if (this.isCancelled) {
  5740. return;
  5741. }
  5742. const lastDesiredSize = this.desiredSize;
  5743. this.desiredSize -= size;
  5744. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  5745. this.sinkCapability = Promise.withResolvers();
  5746. this.ready = this.sinkCapability.promise;
  5747. }
  5748. comObj.postMessage({
  5749. sourceName,
  5750. targetName,
  5751. stream: StreamKind.ENQUEUE,
  5752. streamId,
  5753. chunk
  5754. }, transfers);
  5755. },
  5756. close() {
  5757. if (this.isCancelled) {
  5758. return;
  5759. }
  5760. this.isCancelled = true;
  5761. comObj.postMessage({
  5762. sourceName,
  5763. targetName,
  5764. stream: StreamKind.CLOSE,
  5765. streamId
  5766. });
  5767. delete self.streamSinks[streamId];
  5768. },
  5769. error(reason) {
  5770. assert(reason instanceof Error, "error must have a valid reason");
  5771. if (this.isCancelled) {
  5772. return;
  5773. }
  5774. this.isCancelled = true;
  5775. comObj.postMessage({
  5776. sourceName,
  5777. targetName,
  5778. stream: StreamKind.ERROR,
  5779. streamId,
  5780. reason: wrapReason(reason)
  5781. });
  5782. },
  5783. sinkCapability: Promise.withResolvers(),
  5784. onPull: null,
  5785. onCancel: null,
  5786. isCancelled: false,
  5787. desiredSize: data.desiredSize,
  5788. ready: null
  5789. };
  5790. streamSink.sinkCapability.resolve();
  5791. streamSink.ready = streamSink.sinkCapability.promise;
  5792. this.streamSinks[streamId] = streamSink;
  5793. Promise.try(action, data.data, streamSink).then(function () {
  5794. comObj.postMessage({
  5795. sourceName,
  5796. targetName,
  5797. stream: StreamKind.START_COMPLETE,
  5798. streamId,
  5799. success: true
  5800. });
  5801. }, function (reason) {
  5802. comObj.postMessage({
  5803. sourceName,
  5804. targetName,
  5805. stream: StreamKind.START_COMPLETE,
  5806. streamId,
  5807. reason: wrapReason(reason)
  5808. });
  5809. });
  5810. }
  5811. #processStreamMessage(data) {
  5812. const streamId = data.streamId,
  5813. sourceName = this.sourceName,
  5814. targetName = data.sourceName,
  5815. comObj = this.comObj;
  5816. const streamController = this.streamControllers[streamId],
  5817. streamSink = this.streamSinks[streamId];
  5818. switch (data.stream) {
  5819. case StreamKind.START_COMPLETE:
  5820. if (data.success) {
  5821. streamController.startCall.resolve();
  5822. } else {
  5823. streamController.startCall.reject(wrapReason(data.reason));
  5824. }
  5825. break;
  5826. case StreamKind.PULL_COMPLETE:
  5827. if (data.success) {
  5828. streamController.pullCall.resolve();
  5829. } else {
  5830. streamController.pullCall.reject(wrapReason(data.reason));
  5831. }
  5832. break;
  5833. case StreamKind.PULL:
  5834. if (!streamSink) {
  5835. comObj.postMessage({
  5836. sourceName,
  5837. targetName,
  5838. stream: StreamKind.PULL_COMPLETE,
  5839. streamId,
  5840. success: true
  5841. });
  5842. break;
  5843. }
  5844. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  5845. streamSink.sinkCapability.resolve();
  5846. }
  5847. streamSink.desiredSize = data.desiredSize;
  5848. Promise.try(streamSink.onPull || onFn).then(function () {
  5849. comObj.postMessage({
  5850. sourceName,
  5851. targetName,
  5852. stream: StreamKind.PULL_COMPLETE,
  5853. streamId,
  5854. success: true
  5855. });
  5856. }, function (reason) {
  5857. comObj.postMessage({
  5858. sourceName,
  5859. targetName,
  5860. stream: StreamKind.PULL_COMPLETE,
  5861. streamId,
  5862. reason: wrapReason(reason)
  5863. });
  5864. });
  5865. break;
  5866. case StreamKind.ENQUEUE:
  5867. assert(streamController, "enqueue should have stream controller");
  5868. if (streamController.isClosed) {
  5869. break;
  5870. }
  5871. streamController.controller.enqueue(data.chunk);
  5872. break;
  5873. case StreamKind.CLOSE:
  5874. assert(streamController, "close should have stream controller");
  5875. if (streamController.isClosed) {
  5876. break;
  5877. }
  5878. streamController.isClosed = true;
  5879. streamController.controller.close();
  5880. this.#deleteStreamController(streamController, streamId);
  5881. break;
  5882. case StreamKind.ERROR:
  5883. assert(streamController, "error should have stream controller");
  5884. streamController.controller.error(wrapReason(data.reason));
  5885. this.#deleteStreamController(streamController, streamId);
  5886. break;
  5887. case StreamKind.CANCEL_COMPLETE:
  5888. if (data.success) {
  5889. streamController.cancelCall.resolve();
  5890. } else {
  5891. streamController.cancelCall.reject(wrapReason(data.reason));
  5892. }
  5893. this.#deleteStreamController(streamController, streamId);
  5894. break;
  5895. case StreamKind.CANCEL:
  5896. if (!streamSink) {
  5897. break;
  5898. }
  5899. const dataReason = wrapReason(data.reason);
  5900. Promise.try(streamSink.onCancel || onFn, dataReason).then(function () {
  5901. comObj.postMessage({
  5902. sourceName,
  5903. targetName,
  5904. stream: StreamKind.CANCEL_COMPLETE,
  5905. streamId,
  5906. success: true
  5907. });
  5908. }, function (reason) {
  5909. comObj.postMessage({
  5910. sourceName,
  5911. targetName,
  5912. stream: StreamKind.CANCEL_COMPLETE,
  5913. streamId,
  5914. reason: wrapReason(reason)
  5915. });
  5916. });
  5917. streamSink.sinkCapability.reject(dataReason);
  5918. streamSink.isCancelled = true;
  5919. delete this.streamSinks[streamId];
  5920. break;
  5921. default:
  5922. throw new Error("Unexpected stream case");
  5923. }
  5924. }
  5925. async #deleteStreamController(streamController, streamId) {
  5926. await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
  5927. delete this.streamControllers[streamId];
  5928. }
  5929. destroy() {
  5930. this.#messageAC?.abort();
  5931. this.#messageAC = null;
  5932. }
  5933. }
  5934. ;// ./src/display/canvas_factory.js
  5935. class BaseCanvasFactory {
  5936. #enableHWA = false;
  5937. constructor({
  5938. enableHWA = false
  5939. }) {
  5940. this.#enableHWA = enableHWA;
  5941. }
  5942. create(width, height) {
  5943. if (width <= 0 || height <= 0) {
  5944. throw new Error("Invalid canvas size");
  5945. }
  5946. const canvas = this._createCanvas(width, height);
  5947. return {
  5948. canvas,
  5949. context: canvas.getContext("2d", {
  5950. willReadFrequently: !this.#enableHWA
  5951. })
  5952. };
  5953. }
  5954. reset(canvasAndContext, width, height) {
  5955. if (!canvasAndContext.canvas) {
  5956. throw new Error("Canvas is not specified");
  5957. }
  5958. if (width <= 0 || height <= 0) {
  5959. throw new Error("Invalid canvas size");
  5960. }
  5961. canvasAndContext.canvas.width = width;
  5962. canvasAndContext.canvas.height = height;
  5963. }
  5964. destroy(canvasAndContext) {
  5965. if (!canvasAndContext.canvas) {
  5966. throw new Error("Canvas is not specified");
  5967. }
  5968. canvasAndContext.canvas.width = 0;
  5969. canvasAndContext.canvas.height = 0;
  5970. canvasAndContext.canvas = null;
  5971. canvasAndContext.context = null;
  5972. }
  5973. _createCanvas(width, height) {
  5974. unreachable("Abstract method `_createCanvas` called.");
  5975. }
  5976. }
  5977. class DOMCanvasFactory extends BaseCanvasFactory {
  5978. constructor({
  5979. ownerDocument = globalThis.document,
  5980. enableHWA = false
  5981. }) {
  5982. super({
  5983. enableHWA
  5984. });
  5985. this._document = ownerDocument;
  5986. }
  5987. _createCanvas(width, height) {
  5988. const canvas = this._document.createElement("canvas");
  5989. canvas.width = width;
  5990. canvas.height = height;
  5991. return canvas;
  5992. }
  5993. }
  5994. ;// ./src/display/cmap_reader_factory.js
  5995. class BaseCMapReaderFactory {
  5996. constructor({
  5997. baseUrl = null,
  5998. isCompressed = true
  5999. }) {
  6000. this.baseUrl = baseUrl;
  6001. this.isCompressed = isCompressed;
  6002. }
  6003. async fetch({
  6004. name
  6005. }) {
  6006. if (!this.baseUrl) {
  6007. throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");
  6008. }
  6009. if (!name) {
  6010. throw new Error("CMap name must be specified.");
  6011. }
  6012. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  6013. return this._fetch(url).then(cMapData => ({
  6014. cMapData,
  6015. isCompressed: this.isCompressed
  6016. })).catch(reason => {
  6017. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  6018. });
  6019. }
  6020. async _fetch(url) {
  6021. unreachable("Abstract method `_fetch` called.");
  6022. }
  6023. }
  6024. class DOMCMapReaderFactory extends BaseCMapReaderFactory {
  6025. async _fetch(url) {
  6026. const data = await fetchData(url, this.isCompressed ? "arraybuffer" : "text");
  6027. return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data);
  6028. }
  6029. }
  6030. ;// ./src/display/filter_factory.js
  6031. class BaseFilterFactory {
  6032. addFilter(maps) {
  6033. return "none";
  6034. }
  6035. addHCMFilter(fgColor, bgColor) {
  6036. return "none";
  6037. }
  6038. addAlphaFilter(map) {
  6039. return "none";
  6040. }
  6041. addLuminosityFilter(map) {
  6042. return "none";
  6043. }
  6044. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  6045. return "none";
  6046. }
  6047. destroy(keepHCM = false) {}
  6048. }
  6049. class DOMFilterFactory extends BaseFilterFactory {
  6050. #baseUrl;
  6051. #_cache;
  6052. #_defs;
  6053. #docId;
  6054. #document;
  6055. #_hcmCache;
  6056. #id = 0;
  6057. constructor({
  6058. docId,
  6059. ownerDocument = globalThis.document
  6060. }) {
  6061. super();
  6062. this.#docId = docId;
  6063. this.#document = ownerDocument;
  6064. }
  6065. get #cache() {
  6066. return this.#_cache ||= new Map();
  6067. }
  6068. get #hcmCache() {
  6069. return this.#_hcmCache ||= new Map();
  6070. }
  6071. get #defs() {
  6072. if (!this.#_defs) {
  6073. const div = this.#document.createElement("div");
  6074. const {
  6075. style
  6076. } = div;
  6077. style.visibility = "hidden";
  6078. style.contain = "strict";
  6079. style.width = style.height = 0;
  6080. style.position = "absolute";
  6081. style.top = style.left = 0;
  6082. style.zIndex = -1;
  6083. const svg = this.#document.createElementNS(SVG_NS, "svg");
  6084. svg.setAttribute("width", 0);
  6085. svg.setAttribute("height", 0);
  6086. this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
  6087. div.append(svg);
  6088. svg.append(this.#_defs);
  6089. this.#document.body.append(div);
  6090. }
  6091. return this.#_defs;
  6092. }
  6093. #createTables(maps) {
  6094. if (maps.length === 1) {
  6095. const mapR = maps[0];
  6096. const buffer = new Array(256);
  6097. for (let i = 0; i < 256; i++) {
  6098. buffer[i] = mapR[i] / 255;
  6099. }
  6100. const table = buffer.join(",");
  6101. return [table, table, table];
  6102. }
  6103. const [mapR, mapG, mapB] = maps;
  6104. const bufferR = new Array(256);
  6105. const bufferG = new Array(256);
  6106. const bufferB = new Array(256);
  6107. for (let i = 0; i < 256; i++) {
  6108. bufferR[i] = mapR[i] / 255;
  6109. bufferG[i] = mapG[i] / 255;
  6110. bufferB[i] = mapB[i] / 255;
  6111. }
  6112. return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
  6113. }
  6114. #createUrl(id) {
  6115. if (this.#baseUrl === undefined) {
  6116. this.#baseUrl = "";
  6117. const url = this.#document.URL;
  6118. if (url !== this.#document.baseURI) {
  6119. if (isDataScheme(url)) {
  6120. warn('#createUrl: ignore "data:"-URL for performance reasons.');
  6121. } else {
  6122. this.#baseUrl = url.split("#", 1)[0];
  6123. }
  6124. }
  6125. }
  6126. return `url(${this.#baseUrl}#${id})`;
  6127. }
  6128. addFilter(maps) {
  6129. if (!maps) {
  6130. return "none";
  6131. }
  6132. let value = this.#cache.get(maps);
  6133. if (value) {
  6134. return value;
  6135. }
  6136. const [tableR, tableG, tableB] = this.#createTables(maps);
  6137. const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
  6138. value = this.#cache.get(key);
  6139. if (value) {
  6140. this.#cache.set(maps, value);
  6141. return value;
  6142. }
  6143. const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
  6144. const url = this.#createUrl(id);
  6145. this.#cache.set(maps, url);
  6146. this.#cache.set(key, url);
  6147. const filter = this.#createFilter(id);
  6148. this.#addTransferMapConversion(tableR, tableG, tableB, filter);
  6149. return url;
  6150. }
  6151. addHCMFilter(fgColor, bgColor) {
  6152. const key = `${fgColor}-${bgColor}`;
  6153. const filterName = "base";
  6154. let info = this.#hcmCache.get(filterName);
  6155. if (info?.key === key) {
  6156. return info.url;
  6157. }
  6158. if (info) {
  6159. info.filter?.remove();
  6160. info.key = key;
  6161. info.url = "none";
  6162. info.filter = null;
  6163. } else {
  6164. info = {
  6165. key,
  6166. url: "none",
  6167. filter: null
  6168. };
  6169. this.#hcmCache.set(filterName, info);
  6170. }
  6171. if (!fgColor || !bgColor) {
  6172. return info.url;
  6173. }
  6174. const fgRGB = this.#getRGB(fgColor);
  6175. fgColor = Util.makeHexColor(...fgRGB);
  6176. const bgRGB = this.#getRGB(bgColor);
  6177. bgColor = Util.makeHexColor(...bgRGB);
  6178. this.#defs.style.color = "";
  6179. if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
  6180. return info.url;
  6181. }
  6182. const map = new Array(256);
  6183. for (let i = 0; i <= 255; i++) {
  6184. const x = i / 255;
  6185. map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  6186. }
  6187. const table = map.join(",");
  6188. const id = `g_${this.#docId}_hcm_filter`;
  6189. const filter = info.filter = this.#createFilter(id);
  6190. this.#addTransferMapConversion(table, table, table, filter);
  6191. this.#addGrayConversion(filter);
  6192. const getSteps = (c, n) => {
  6193. const start = fgRGB[c] / 255;
  6194. const end = bgRGB[c] / 255;
  6195. const arr = new Array(n + 1);
  6196. for (let i = 0; i <= n; i++) {
  6197. arr[i] = start + i / n * (end - start);
  6198. }
  6199. return arr.join(",");
  6200. };
  6201. this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
  6202. info.url = this.#createUrl(id);
  6203. return info.url;
  6204. }
  6205. addAlphaFilter(map) {
  6206. let value = this.#cache.get(map);
  6207. if (value) {
  6208. return value;
  6209. }
  6210. const [tableA] = this.#createTables([map]);
  6211. const key = `alpha_${tableA}`;
  6212. value = this.#cache.get(key);
  6213. if (value) {
  6214. this.#cache.set(map, value);
  6215. return value;
  6216. }
  6217. const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
  6218. const url = this.#createUrl(id);
  6219. this.#cache.set(map, url);
  6220. this.#cache.set(key, url);
  6221. const filter = this.#createFilter(id);
  6222. this.#addTransferMapAlphaConversion(tableA, filter);
  6223. return url;
  6224. }
  6225. addLuminosityFilter(map) {
  6226. let value = this.#cache.get(map || "luminosity");
  6227. if (value) {
  6228. return value;
  6229. }
  6230. let tableA, key;
  6231. if (map) {
  6232. [tableA] = this.#createTables([map]);
  6233. key = `luminosity_${tableA}`;
  6234. } else {
  6235. key = "luminosity";
  6236. }
  6237. value = this.#cache.get(key);
  6238. if (value) {
  6239. this.#cache.set(map, value);
  6240. return value;
  6241. }
  6242. const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
  6243. const url = this.#createUrl(id);
  6244. this.#cache.set(map, url);
  6245. this.#cache.set(key, url);
  6246. const filter = this.#createFilter(id);
  6247. this.#addLuminosityConversion(filter);
  6248. if (map) {
  6249. this.#addTransferMapAlphaConversion(tableA, filter);
  6250. }
  6251. return url;
  6252. }
  6253. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  6254. const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
  6255. let info = this.#hcmCache.get(filterName);
  6256. if (info?.key === key) {
  6257. return info.url;
  6258. }
  6259. if (info) {
  6260. info.filter?.remove();
  6261. info.key = key;
  6262. info.url = "none";
  6263. info.filter = null;
  6264. } else {
  6265. info = {
  6266. key,
  6267. url: "none",
  6268. filter: null
  6269. };
  6270. this.#hcmCache.set(filterName, info);
  6271. }
  6272. if (!fgColor || !bgColor) {
  6273. return info.url;
  6274. }
  6275. const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
  6276. let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
  6277. let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
  6278. let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
  6279. if (bgGray < fgGray) {
  6280. [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
  6281. }
  6282. this.#defs.style.color = "";
  6283. const getSteps = (fg, bg, n) => {
  6284. const arr = new Array(256);
  6285. const step = (bgGray - fgGray) / n;
  6286. const newStart = fg / 255;
  6287. const newStep = (bg - fg) / (255 * n);
  6288. let prev = 0;
  6289. for (let i = 0; i <= n; i++) {
  6290. const k = Math.round(fgGray + i * step);
  6291. const value = newStart + i * newStep;
  6292. for (let j = prev; j <= k; j++) {
  6293. arr[j] = value;
  6294. }
  6295. prev = k + 1;
  6296. }
  6297. for (let i = prev; i < 256; i++) {
  6298. arr[i] = arr[prev - 1];
  6299. }
  6300. return arr.join(",");
  6301. };
  6302. const id = `g_${this.#docId}_hcm_${filterName}_filter`;
  6303. const filter = info.filter = this.#createFilter(id);
  6304. this.#addGrayConversion(filter);
  6305. this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
  6306. info.url = this.#createUrl(id);
  6307. return info.url;
  6308. }
  6309. destroy(keepHCM = false) {
  6310. if (keepHCM && this.#_hcmCache?.size) {
  6311. return;
  6312. }
  6313. this.#_defs?.parentNode.parentNode.remove();
  6314. this.#_defs = null;
  6315. this.#_cache?.clear();
  6316. this.#_cache = null;
  6317. this.#_hcmCache?.clear();
  6318. this.#_hcmCache = null;
  6319. this.#id = 0;
  6320. }
  6321. #addLuminosityConversion(filter) {
  6322. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  6323. feColorMatrix.setAttribute("type", "matrix");
  6324. 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");
  6325. filter.append(feColorMatrix);
  6326. }
  6327. #addGrayConversion(filter) {
  6328. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  6329. feColorMatrix.setAttribute("type", "matrix");
  6330. 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");
  6331. filter.append(feColorMatrix);
  6332. }
  6333. #createFilter(id) {
  6334. const filter = this.#document.createElementNS(SVG_NS, "filter");
  6335. filter.setAttribute("color-interpolation-filters", "sRGB");
  6336. filter.setAttribute("id", id);
  6337. this.#defs.append(filter);
  6338. return filter;
  6339. }
  6340. #appendFeFunc(feComponentTransfer, func, table) {
  6341. const feFunc = this.#document.createElementNS(SVG_NS, func);
  6342. feFunc.setAttribute("type", "discrete");
  6343. feFunc.setAttribute("tableValues", table);
  6344. feComponentTransfer.append(feFunc);
  6345. }
  6346. #addTransferMapConversion(rTable, gTable, bTable, filter) {
  6347. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  6348. filter.append(feComponentTransfer);
  6349. this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
  6350. this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
  6351. this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
  6352. }
  6353. #addTransferMapAlphaConversion(aTable, filter) {
  6354. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  6355. filter.append(feComponentTransfer);
  6356. this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
  6357. }
  6358. #getRGB(color) {
  6359. this.#defs.style.color = color;
  6360. return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
  6361. }
  6362. }
  6363. ;// ./src/display/standard_fontdata_factory.js
  6364. class BaseStandardFontDataFactory {
  6365. constructor({
  6366. baseUrl = null
  6367. }) {
  6368. this.baseUrl = baseUrl;
  6369. }
  6370. async fetch({
  6371. filename
  6372. }) {
  6373. if (!this.baseUrl) {
  6374. throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");
  6375. }
  6376. if (!filename) {
  6377. throw new Error("Font filename must be specified.");
  6378. }
  6379. const url = `${this.baseUrl}${filename}`;
  6380. return this._fetch(url).catch(reason => {
  6381. throw new Error(`Unable to load font data at: ${url}`);
  6382. });
  6383. }
  6384. async _fetch(url) {
  6385. unreachable("Abstract method `_fetch` called.");
  6386. }
  6387. }
  6388. class DOMStandardFontDataFactory extends BaseStandardFontDataFactory {
  6389. async _fetch(url) {
  6390. const data = await fetchData(url, "arraybuffer");
  6391. return new Uint8Array(data);
  6392. }
  6393. }
  6394. ;// ./src/display/node_utils.js
  6395. if (isNodeJS) {
  6396. warn("Please use the `legacy` build in Node.js environments.");
  6397. }
  6398. async function node_utils_fetchData(url) {
  6399. const fs = process.getBuiltinModule("fs");
  6400. const data = await fs.promises.readFile(url);
  6401. return new Uint8Array(data);
  6402. }
  6403. class NodeFilterFactory extends BaseFilterFactory {}
  6404. class NodeCanvasFactory extends BaseCanvasFactory {
  6405. _createCanvas(width, height) {
  6406. const require = process.getBuiltinModule("module").createRequire(import.meta.url);
  6407. const canvas = require("@napi-rs/canvas");
  6408. return canvas.createCanvas(width, height);
  6409. }
  6410. }
  6411. class NodeCMapReaderFactory extends BaseCMapReaderFactory {
  6412. async _fetch(url) {
  6413. return node_utils_fetchData(url);
  6414. }
  6415. }
  6416. class NodeStandardFontDataFactory extends BaseStandardFontDataFactory {
  6417. async _fetch(url) {
  6418. return node_utils_fetchData(url);
  6419. }
  6420. }
  6421. ;// ./src/display/pattern_helper.js
  6422. const PathType = {
  6423. FILL: "Fill",
  6424. STROKE: "Stroke",
  6425. SHADING: "Shading"
  6426. };
  6427. function applyBoundingBox(ctx, bbox) {
  6428. if (!bbox) {
  6429. return;
  6430. }
  6431. const width = bbox[2] - bbox[0];
  6432. const height = bbox[3] - bbox[1];
  6433. const region = new Path2D();
  6434. region.rect(bbox[0], bbox[1], width, height);
  6435. ctx.clip(region);
  6436. }
  6437. class BaseShadingPattern {
  6438. getPattern() {
  6439. unreachable("Abstract method `getPattern` called.");
  6440. }
  6441. }
  6442. class RadialAxialShadingPattern extends BaseShadingPattern {
  6443. constructor(IR) {
  6444. super();
  6445. this._type = IR[1];
  6446. this._bbox = IR[2];
  6447. this._colorStops = IR[3];
  6448. this._p0 = IR[4];
  6449. this._p1 = IR[5];
  6450. this._r0 = IR[6];
  6451. this._r1 = IR[7];
  6452. this.matrix = null;
  6453. }
  6454. _createGradient(ctx) {
  6455. let grad;
  6456. if (this._type === "axial") {
  6457. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  6458. } else if (this._type === "radial") {
  6459. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  6460. }
  6461. for (const colorStop of this._colorStops) {
  6462. grad.addColorStop(colorStop[0], colorStop[1]);
  6463. }
  6464. return grad;
  6465. }
  6466. getPattern(ctx, owner, inverse, pathType) {
  6467. let pattern;
  6468. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  6469. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
  6470. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  6471. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  6472. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);
  6473. const tmpCtx = tmpCanvas.context;
  6474. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  6475. tmpCtx.beginPath();
  6476. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  6477. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  6478. inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  6479. tmpCtx.transform(...owner.baseTransform);
  6480. if (this.matrix) {
  6481. tmpCtx.transform(...this.matrix);
  6482. }
  6483. applyBoundingBox(tmpCtx, this._bbox);
  6484. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  6485. tmpCtx.fill();
  6486. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  6487. const domMatrix = new DOMMatrix(inverse);
  6488. pattern.setTransform(domMatrix);
  6489. } else {
  6490. applyBoundingBox(ctx, this._bbox);
  6491. pattern = this._createGradient(ctx);
  6492. }
  6493. return pattern;
  6494. }
  6495. }
  6496. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  6497. const coords = context.coords,
  6498. colors = context.colors;
  6499. const bytes = data.data,
  6500. rowSize = data.width * 4;
  6501. let tmp;
  6502. if (coords[p1 + 1] > coords[p2 + 1]) {
  6503. tmp = p1;
  6504. p1 = p2;
  6505. p2 = tmp;
  6506. tmp = c1;
  6507. c1 = c2;
  6508. c2 = tmp;
  6509. }
  6510. if (coords[p2 + 1] > coords[p3 + 1]) {
  6511. tmp = p2;
  6512. p2 = p3;
  6513. p3 = tmp;
  6514. tmp = c2;
  6515. c2 = c3;
  6516. c3 = tmp;
  6517. }
  6518. if (coords[p1 + 1] > coords[p2 + 1]) {
  6519. tmp = p1;
  6520. p1 = p2;
  6521. p2 = tmp;
  6522. tmp = c1;
  6523. c1 = c2;
  6524. c2 = tmp;
  6525. }
  6526. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  6527. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  6528. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  6529. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  6530. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  6531. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  6532. if (y1 >= y3) {
  6533. return;
  6534. }
  6535. const c1r = colors[c1],
  6536. c1g = colors[c1 + 1],
  6537. c1b = colors[c1 + 2];
  6538. const c2r = colors[c2],
  6539. c2g = colors[c2 + 1],
  6540. c2b = colors[c2 + 2];
  6541. const c3r = colors[c3],
  6542. c3g = colors[c3 + 1],
  6543. c3b = colors[c3 + 2];
  6544. const minY = Math.round(y1),
  6545. maxY = Math.round(y3);
  6546. let xa, car, cag, cab;
  6547. let xb, cbr, cbg, cbb;
  6548. for (let y = minY; y <= maxY; y++) {
  6549. if (y < y2) {
  6550. const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);
  6551. xa = x1 - (x1 - x2) * k;
  6552. car = c1r - (c1r - c2r) * k;
  6553. cag = c1g - (c1g - c2g) * k;
  6554. cab = c1b - (c1b - c2b) * k;
  6555. } else {
  6556. let k;
  6557. if (y > y3) {
  6558. k = 1;
  6559. } else if (y2 === y3) {
  6560. k = 0;
  6561. } else {
  6562. k = (y2 - y) / (y2 - y3);
  6563. }
  6564. xa = x2 - (x2 - x3) * k;
  6565. car = c2r - (c2r - c3r) * k;
  6566. cag = c2g - (c2g - c3g) * k;
  6567. cab = c2b - (c2b - c3b) * k;
  6568. }
  6569. let k;
  6570. if (y < y1) {
  6571. k = 0;
  6572. } else if (y > y3) {
  6573. k = 1;
  6574. } else {
  6575. k = (y1 - y) / (y1 - y3);
  6576. }
  6577. xb = x1 - (x1 - x3) * k;
  6578. cbr = c1r - (c1r - c3r) * k;
  6579. cbg = c1g - (c1g - c3g) * k;
  6580. cbb = c1b - (c1b - c3b) * k;
  6581. const x1_ = Math.round(Math.min(xa, xb));
  6582. const x2_ = Math.round(Math.max(xa, xb));
  6583. let j = rowSize * y + x1_ * 4;
  6584. for (let x = x1_; x <= x2_; x++) {
  6585. k = (xa - x) / (xa - xb);
  6586. if (k < 0) {
  6587. k = 0;
  6588. } else if (k > 1) {
  6589. k = 1;
  6590. }
  6591. bytes[j++] = car - (car - cbr) * k | 0;
  6592. bytes[j++] = cag - (cag - cbg) * k | 0;
  6593. bytes[j++] = cab - (cab - cbb) * k | 0;
  6594. bytes[j++] = 255;
  6595. }
  6596. }
  6597. }
  6598. function drawFigure(data, figure, context) {
  6599. const ps = figure.coords;
  6600. const cs = figure.colors;
  6601. let i, ii;
  6602. switch (figure.type) {
  6603. case "lattice":
  6604. const verticesPerRow = figure.verticesPerRow;
  6605. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  6606. const cols = verticesPerRow - 1;
  6607. for (i = 0; i < rows; i++) {
  6608. let q = i * verticesPerRow;
  6609. for (let j = 0; j < cols; j++, q++) {
  6610. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  6611. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  6612. }
  6613. }
  6614. break;
  6615. case "triangles":
  6616. for (i = 0, ii = ps.length; i < ii; i += 3) {
  6617. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  6618. }
  6619. break;
  6620. default:
  6621. throw new Error("illegal figure");
  6622. }
  6623. }
  6624. class MeshShadingPattern extends BaseShadingPattern {
  6625. constructor(IR) {
  6626. super();
  6627. this._coords = IR[2];
  6628. this._colors = IR[3];
  6629. this._figures = IR[4];
  6630. this._bounds = IR[5];
  6631. this._bbox = IR[7];
  6632. this._background = IR[8];
  6633. this.matrix = null;
  6634. }
  6635. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  6636. const EXPECTED_SCALE = 1.1;
  6637. const MAX_PATTERN_SIZE = 3000;
  6638. const BORDER_SIZE = 2;
  6639. const offsetX = Math.floor(this._bounds[0]);
  6640. const offsetY = Math.floor(this._bounds[1]);
  6641. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  6642. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  6643. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6644. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6645. const scaleX = boundsWidth / width;
  6646. const scaleY = boundsHeight / height;
  6647. const context = {
  6648. coords: this._coords,
  6649. colors: this._colors,
  6650. offsetX: -offsetX,
  6651. offsetY: -offsetY,
  6652. scaleX: 1 / scaleX,
  6653. scaleY: 1 / scaleY
  6654. };
  6655. const paddedWidth = width + BORDER_SIZE * 2;
  6656. const paddedHeight = height + BORDER_SIZE * 2;
  6657. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);
  6658. const tmpCtx = tmpCanvas.context;
  6659. const data = tmpCtx.createImageData(width, height);
  6660. if (backgroundColor) {
  6661. const bytes = data.data;
  6662. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  6663. bytes[i] = backgroundColor[0];
  6664. bytes[i + 1] = backgroundColor[1];
  6665. bytes[i + 2] = backgroundColor[2];
  6666. bytes[i + 3] = 255;
  6667. }
  6668. }
  6669. for (const figure of this._figures) {
  6670. drawFigure(data, figure, context);
  6671. }
  6672. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6673. const canvas = tmpCanvas.canvas;
  6674. return {
  6675. canvas,
  6676. offsetX: offsetX - BORDER_SIZE * scaleX,
  6677. offsetY: offsetY - BORDER_SIZE * scaleY,
  6678. scaleX,
  6679. scaleY
  6680. };
  6681. }
  6682. getPattern(ctx, owner, inverse, pathType) {
  6683. applyBoundingBox(ctx, this._bbox);
  6684. let scale;
  6685. if (pathType === PathType.SHADING) {
  6686. scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx));
  6687. } else {
  6688. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  6689. if (this.matrix) {
  6690. const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6691. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  6692. }
  6693. }
  6694. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  6695. if (pathType !== PathType.SHADING) {
  6696. ctx.setTransform(...owner.baseTransform);
  6697. if (this.matrix) {
  6698. ctx.transform(...this.matrix);
  6699. }
  6700. }
  6701. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6702. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6703. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  6704. }
  6705. }
  6706. class DummyShadingPattern extends BaseShadingPattern {
  6707. getPattern() {
  6708. return "hotpink";
  6709. }
  6710. }
  6711. function getShadingPattern(IR) {
  6712. switch (IR[0]) {
  6713. case "RadialAxial":
  6714. return new RadialAxialShadingPattern(IR);
  6715. case "Mesh":
  6716. return new MeshShadingPattern(IR);
  6717. case "Dummy":
  6718. return new DummyShadingPattern();
  6719. }
  6720. throw new Error(`Unknown IR type: ${IR[0]}`);
  6721. }
  6722. const PaintType = {
  6723. COLORED: 1,
  6724. UNCOLORED: 2
  6725. };
  6726. class TilingPattern {
  6727. static MAX_PATTERN_SIZE = 3000;
  6728. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6729. this.operatorList = IR[2];
  6730. this.matrix = IR[3];
  6731. this.bbox = IR[4];
  6732. this.xstep = IR[5];
  6733. this.ystep = IR[6];
  6734. this.paintType = IR[7];
  6735. this.tilingType = IR[8];
  6736. this.color = color;
  6737. this.ctx = ctx;
  6738. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6739. this.baseTransform = baseTransform;
  6740. }
  6741. createPatternCanvas(owner) {
  6742. const {
  6743. bbox,
  6744. operatorList,
  6745. paintType,
  6746. tilingType,
  6747. color,
  6748. canvasGraphicsFactory
  6749. } = this;
  6750. let {
  6751. xstep,
  6752. ystep
  6753. } = this;
  6754. xstep = Math.abs(xstep);
  6755. ystep = Math.abs(ystep);
  6756. info("TilingType: " + tilingType);
  6757. const x0 = bbox[0],
  6758. y0 = bbox[1],
  6759. x1 = bbox[2],
  6760. y1 = bbox[3];
  6761. const width = x1 - x0;
  6762. const height = y1 - y0;
  6763. const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6764. const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  6765. const combinedScaleX = matrixScale[0] * curMatrixScale[0];
  6766. const combinedScaleY = matrixScale[1] * curMatrixScale[1];
  6767. let canvasWidth = width,
  6768. canvasHeight = height,
  6769. redrawHorizontally = false,
  6770. redrawVertically = false;
  6771. const xScaledStep = Math.ceil(xstep * combinedScaleX);
  6772. const yScaledStep = Math.ceil(ystep * combinedScaleY);
  6773. const xScaledWidth = Math.ceil(width * combinedScaleX);
  6774. const yScaledHeight = Math.ceil(height * combinedScaleY);
  6775. if (xScaledStep >= xScaledWidth) {
  6776. canvasWidth = xstep;
  6777. } else {
  6778. redrawHorizontally = true;
  6779. }
  6780. if (yScaledStep >= yScaledHeight) {
  6781. canvasHeight = ystep;
  6782. } else {
  6783. redrawVertically = true;
  6784. }
  6785. const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  6786. const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  6787. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);
  6788. const tmpCtx = tmpCanvas.context;
  6789. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6790. graphics.groupLevel = owner.groupLevel;
  6791. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  6792. tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);
  6793. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  6794. tmpCtx.save();
  6795. this.clipBbox(graphics, x0, y0, x1, y1);
  6796. graphics.baseTransform = getCurrentTransform(graphics.ctx);
  6797. graphics.executeOperatorList(operatorList);
  6798. graphics.endDrawing();
  6799. tmpCtx.restore();
  6800. if (redrawHorizontally || redrawVertically) {
  6801. const image = tmpCanvas.canvas;
  6802. if (redrawHorizontally) {
  6803. canvasWidth = xstep;
  6804. }
  6805. if (redrawVertically) {
  6806. canvasHeight = ystep;
  6807. }
  6808. const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  6809. const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  6810. const xSize = dimx2.size;
  6811. const ySize = dimy2.size;
  6812. const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);
  6813. const tmpCtx2 = tmpCanvas2.context;
  6814. const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;
  6815. const jj = redrawVertically ? Math.floor(height / ystep) : 0;
  6816. for (let i = 0; i <= ii; i++) {
  6817. for (let j = 0; j <= jj; j++) {
  6818. tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize);
  6819. }
  6820. }
  6821. return {
  6822. canvas: tmpCanvas2.canvas,
  6823. scaleX: dimx2.scale,
  6824. scaleY: dimy2.scale,
  6825. offsetX: x0,
  6826. offsetY: y0
  6827. };
  6828. }
  6829. return {
  6830. canvas: tmpCanvas.canvas,
  6831. scaleX: dimx.scale,
  6832. scaleY: dimy.scale,
  6833. offsetX: x0,
  6834. offsetY: y0
  6835. };
  6836. }
  6837. getSizeAndScale(step, realOutputSize, scale) {
  6838. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  6839. let size = Math.ceil(step * scale);
  6840. if (size >= maxSize) {
  6841. size = maxSize;
  6842. } else {
  6843. scale = size / step;
  6844. }
  6845. return {
  6846. scale,
  6847. size
  6848. };
  6849. }
  6850. clipBbox(graphics, x0, y0, x1, y1) {
  6851. const bboxWidth = x1 - x0;
  6852. const bboxHeight = y1 - y0;
  6853. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6854. graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]);
  6855. graphics.clip();
  6856. graphics.endPath();
  6857. }
  6858. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  6859. const context = graphics.ctx,
  6860. current = graphics.current;
  6861. switch (paintType) {
  6862. case PaintType.COLORED:
  6863. const ctx = this.ctx;
  6864. context.fillStyle = ctx.fillStyle;
  6865. context.strokeStyle = ctx.strokeStyle;
  6866. current.fillColor = ctx.fillStyle;
  6867. current.strokeColor = ctx.strokeStyle;
  6868. break;
  6869. case PaintType.UNCOLORED:
  6870. const cssColor = Util.makeHexColor(color[0], color[1], color[2]);
  6871. context.fillStyle = cssColor;
  6872. context.strokeStyle = cssColor;
  6873. current.fillColor = cssColor;
  6874. current.strokeColor = cssColor;
  6875. break;
  6876. default:
  6877. throw new FormatError(`Unsupported paint type: ${paintType}`);
  6878. }
  6879. }
  6880. getPattern(ctx, owner, inverse, pathType) {
  6881. let matrix = inverse;
  6882. if (pathType !== PathType.SHADING) {
  6883. matrix = Util.transform(matrix, owner.baseTransform);
  6884. if (this.matrix) {
  6885. matrix = Util.transform(matrix, this.matrix);
  6886. }
  6887. }
  6888. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  6889. let domMatrix = new DOMMatrix(matrix);
  6890. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6891. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  6892. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  6893. pattern.setTransform(domMatrix);
  6894. return pattern;
  6895. }
  6896. }
  6897. ;// ./src/shared/image_utils.js
  6898. function convertToRGBA(params) {
  6899. switch (params.kind) {
  6900. case ImageKind.GRAYSCALE_1BPP:
  6901. return convertBlackAndWhiteToRGBA(params);
  6902. case ImageKind.RGB_24BPP:
  6903. return convertRGBToRGBA(params);
  6904. }
  6905. return null;
  6906. }
  6907. function convertBlackAndWhiteToRGBA({
  6908. src,
  6909. srcPos = 0,
  6910. dest,
  6911. width,
  6912. height,
  6913. nonBlackColor = 0xffffffff,
  6914. inverseDecode = false
  6915. }) {
  6916. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  6917. const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
  6918. const widthInSource = width >> 3;
  6919. const widthRemainder = width & 7;
  6920. const srcLength = src.length;
  6921. dest = new Uint32Array(dest.buffer);
  6922. let destPos = 0;
  6923. for (let i = 0; i < height; i++) {
  6924. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  6925. const elem = srcPos < srcLength ? src[srcPos] : 255;
  6926. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  6927. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  6928. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  6929. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  6930. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  6931. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  6932. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  6933. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  6934. }
  6935. if (widthRemainder === 0) {
  6936. continue;
  6937. }
  6938. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  6939. for (let j = 0; j < widthRemainder; j++) {
  6940. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  6941. }
  6942. }
  6943. return {
  6944. srcPos,
  6945. destPos
  6946. };
  6947. }
  6948. function convertRGBToRGBA({
  6949. src,
  6950. srcPos = 0,
  6951. dest,
  6952. destPos = 0,
  6953. width,
  6954. height
  6955. }) {
  6956. let i = 0;
  6957. const len = width * height * 3;
  6958. const len32 = len >> 2;
  6959. const src32 = new Uint32Array(src.buffer, srcPos, len32);
  6960. if (FeatureTest.isLittleEndian) {
  6961. for (; i < len32 - 2; i += 3, destPos += 4) {
  6962. const s1 = src32[i];
  6963. const s2 = src32[i + 1];
  6964. const s3 = src32[i + 2];
  6965. dest[destPos] = s1 | 0xff000000;
  6966. dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
  6967. dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
  6968. dest[destPos + 3] = s3 >>> 8 | 0xff000000;
  6969. }
  6970. for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {
  6971. dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
  6972. }
  6973. } else {
  6974. for (; i < len32 - 2; i += 3, destPos += 4) {
  6975. const s1 = src32[i];
  6976. const s2 = src32[i + 1];
  6977. const s3 = src32[i + 2];
  6978. dest[destPos] = s1 | 0xff;
  6979. dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
  6980. dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
  6981. dest[destPos + 3] = s3 << 8 | 0xff;
  6982. }
  6983. for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {
  6984. dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
  6985. }
  6986. }
  6987. return {
  6988. srcPos: srcPos + len,
  6989. destPos
  6990. };
  6991. }
  6992. function grayToRGBA(src, dest) {
  6993. if (FeatureTest.isLittleEndian) {
  6994. for (let i = 0, ii = src.length; i < ii; i++) {
  6995. dest[i] = src[i] * 0x10101 | 0xff000000;
  6996. }
  6997. } else {
  6998. for (let i = 0, ii = src.length; i < ii; i++) {
  6999. dest[i] = src[i] * 0x1010100 | 0x000000ff;
  7000. }
  7001. }
  7002. }
  7003. ;// ./src/display/canvas.js
  7004. const MIN_FONT_SIZE = 16;
  7005. const MAX_FONT_SIZE = 100;
  7006. const EXECUTION_TIME = 15;
  7007. const EXECUTION_STEPS = 10;
  7008. const MAX_SIZE_TO_COMPILE = 1000;
  7009. const FULL_CHUNK_HEIGHT = 16;
  7010. function mirrorContextOperations(ctx, destCtx) {
  7011. if (ctx._removeMirroring) {
  7012. throw new Error("Context is already forwarding operations.");
  7013. }
  7014. ctx.__originalSave = ctx.save;
  7015. ctx.__originalRestore = ctx.restore;
  7016. ctx.__originalRotate = ctx.rotate;
  7017. ctx.__originalScale = ctx.scale;
  7018. ctx.__originalTranslate = ctx.translate;
  7019. ctx.__originalTransform = ctx.transform;
  7020. ctx.__originalSetTransform = ctx.setTransform;
  7021. ctx.__originalResetTransform = ctx.resetTransform;
  7022. ctx.__originalClip = ctx.clip;
  7023. ctx.__originalMoveTo = ctx.moveTo;
  7024. ctx.__originalLineTo = ctx.lineTo;
  7025. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  7026. ctx.__originalRect = ctx.rect;
  7027. ctx.__originalClosePath = ctx.closePath;
  7028. ctx.__originalBeginPath = ctx.beginPath;
  7029. ctx._removeMirroring = () => {
  7030. ctx.save = ctx.__originalSave;
  7031. ctx.restore = ctx.__originalRestore;
  7032. ctx.rotate = ctx.__originalRotate;
  7033. ctx.scale = ctx.__originalScale;
  7034. ctx.translate = ctx.__originalTranslate;
  7035. ctx.transform = ctx.__originalTransform;
  7036. ctx.setTransform = ctx.__originalSetTransform;
  7037. ctx.resetTransform = ctx.__originalResetTransform;
  7038. ctx.clip = ctx.__originalClip;
  7039. ctx.moveTo = ctx.__originalMoveTo;
  7040. ctx.lineTo = ctx.__originalLineTo;
  7041. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  7042. ctx.rect = ctx.__originalRect;
  7043. ctx.closePath = ctx.__originalClosePath;
  7044. ctx.beginPath = ctx.__originalBeginPath;
  7045. delete ctx._removeMirroring;
  7046. };
  7047. ctx.save = function ctxSave() {
  7048. destCtx.save();
  7049. this.__originalSave();
  7050. };
  7051. ctx.restore = function ctxRestore() {
  7052. destCtx.restore();
  7053. this.__originalRestore();
  7054. };
  7055. ctx.translate = function ctxTranslate(x, y) {
  7056. destCtx.translate(x, y);
  7057. this.__originalTranslate(x, y);
  7058. };
  7059. ctx.scale = function ctxScale(x, y) {
  7060. destCtx.scale(x, y);
  7061. this.__originalScale(x, y);
  7062. };
  7063. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  7064. destCtx.transform(a, b, c, d, e, f);
  7065. this.__originalTransform(a, b, c, d, e, f);
  7066. };
  7067. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  7068. destCtx.setTransform(a, b, c, d, e, f);
  7069. this.__originalSetTransform(a, b, c, d, e, f);
  7070. };
  7071. ctx.resetTransform = function ctxResetTransform() {
  7072. destCtx.resetTransform();
  7073. this.__originalResetTransform();
  7074. };
  7075. ctx.rotate = function ctxRotate(angle) {
  7076. destCtx.rotate(angle);
  7077. this.__originalRotate(angle);
  7078. };
  7079. ctx.clip = function ctxRotate(rule) {
  7080. destCtx.clip(rule);
  7081. this.__originalClip(rule);
  7082. };
  7083. ctx.moveTo = function (x, y) {
  7084. destCtx.moveTo(x, y);
  7085. this.__originalMoveTo(x, y);
  7086. };
  7087. ctx.lineTo = function (x, y) {
  7088. destCtx.lineTo(x, y);
  7089. this.__originalLineTo(x, y);
  7090. };
  7091. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  7092. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  7093. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  7094. };
  7095. ctx.rect = function (x, y, width, height) {
  7096. destCtx.rect(x, y, width, height);
  7097. this.__originalRect(x, y, width, height);
  7098. };
  7099. ctx.closePath = function () {
  7100. destCtx.closePath();
  7101. this.__originalClosePath();
  7102. };
  7103. ctx.beginPath = function () {
  7104. destCtx.beginPath();
  7105. this.__originalBeginPath();
  7106. };
  7107. }
  7108. class CachedCanvases {
  7109. constructor(canvasFactory) {
  7110. this.canvasFactory = canvasFactory;
  7111. this.cache = Object.create(null);
  7112. }
  7113. getCanvas(id, width, height) {
  7114. let canvasEntry;
  7115. if (this.cache[id] !== undefined) {
  7116. canvasEntry = this.cache[id];
  7117. this.canvasFactory.reset(canvasEntry, width, height);
  7118. } else {
  7119. canvasEntry = this.canvasFactory.create(width, height);
  7120. this.cache[id] = canvasEntry;
  7121. }
  7122. return canvasEntry;
  7123. }
  7124. delete(id) {
  7125. delete this.cache[id];
  7126. }
  7127. clear() {
  7128. for (const id in this.cache) {
  7129. const canvasEntry = this.cache[id];
  7130. this.canvasFactory.destroy(canvasEntry);
  7131. delete this.cache[id];
  7132. }
  7133. }
  7134. }
  7135. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  7136. const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);
  7137. if (b === 0 && c === 0) {
  7138. const tlX = destX * a + tx;
  7139. const rTlX = Math.round(tlX);
  7140. const tlY = destY * d + ty;
  7141. const rTlY = Math.round(tlY);
  7142. const brX = (destX + destW) * a + tx;
  7143. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  7144. const brY = (destY + destH) * d + ty;
  7145. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  7146. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  7147. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  7148. ctx.setTransform(a, b, c, d, tx, ty);
  7149. return [rWidth, rHeight];
  7150. }
  7151. if (a === 0 && d === 0) {
  7152. const tlX = destY * c + tx;
  7153. const rTlX = Math.round(tlX);
  7154. const tlY = destX * b + ty;
  7155. const rTlY = Math.round(tlY);
  7156. const brX = (destY + destH) * c + tx;
  7157. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  7158. const brY = (destX + destW) * b + ty;
  7159. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  7160. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  7161. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  7162. ctx.setTransform(a, b, c, d, tx, ty);
  7163. return [rHeight, rWidth];
  7164. }
  7165. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  7166. const scaleX = Math.hypot(a, b);
  7167. const scaleY = Math.hypot(c, d);
  7168. return [scaleX * destW, scaleY * destH];
  7169. }
  7170. function compileType3Glyph(imgData) {
  7171. const {
  7172. width,
  7173. height
  7174. } = imgData;
  7175. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  7176. return null;
  7177. }
  7178. const POINT_TO_PROCESS_LIMIT = 1000;
  7179. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  7180. const width1 = width + 1;
  7181. let points = new Uint8Array(width1 * (height + 1));
  7182. let i, j, j0;
  7183. const lineSize = width + 7 & ~7;
  7184. let data = new Uint8Array(lineSize * height),
  7185. pos = 0;
  7186. for (const elem of imgData.data) {
  7187. let mask = 128;
  7188. while (mask > 0) {
  7189. data[pos++] = elem & mask ? 0 : 255;
  7190. mask >>= 1;
  7191. }
  7192. }
  7193. let count = 0;
  7194. pos = 0;
  7195. if (data[pos] !== 0) {
  7196. points[0] = 1;
  7197. ++count;
  7198. }
  7199. for (j = 1; j < width; j++) {
  7200. if (data[pos] !== data[pos + 1]) {
  7201. points[j] = data[pos] ? 2 : 1;
  7202. ++count;
  7203. }
  7204. pos++;
  7205. }
  7206. if (data[pos] !== 0) {
  7207. points[j] = 2;
  7208. ++count;
  7209. }
  7210. for (i = 1; i < height; i++) {
  7211. pos = i * lineSize;
  7212. j0 = i * width1;
  7213. if (data[pos - lineSize] !== data[pos]) {
  7214. points[j0] = data[pos] ? 1 : 8;
  7215. ++count;
  7216. }
  7217. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  7218. for (j = 1; j < width; j++) {
  7219. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  7220. if (POINT_TYPES[sum]) {
  7221. points[j0 + j] = POINT_TYPES[sum];
  7222. ++count;
  7223. }
  7224. pos++;
  7225. }
  7226. if (data[pos - lineSize] !== data[pos]) {
  7227. points[j0 + j] = data[pos] ? 2 : 4;
  7228. ++count;
  7229. }
  7230. if (count > POINT_TO_PROCESS_LIMIT) {
  7231. return null;
  7232. }
  7233. }
  7234. pos = lineSize * (height - 1);
  7235. j0 = i * width1;
  7236. if (data[pos] !== 0) {
  7237. points[j0] = 8;
  7238. ++count;
  7239. }
  7240. for (j = 1; j < width; j++) {
  7241. if (data[pos] !== data[pos + 1]) {
  7242. points[j0 + j] = data[pos] ? 4 : 8;
  7243. ++count;
  7244. }
  7245. pos++;
  7246. }
  7247. if (data[pos] !== 0) {
  7248. points[j0 + j] = 4;
  7249. ++count;
  7250. }
  7251. if (count > POINT_TO_PROCESS_LIMIT) {
  7252. return null;
  7253. }
  7254. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  7255. const path = new Path2D();
  7256. for (i = 0; count && i <= height; i++) {
  7257. let p = i * width1;
  7258. const end = p + width;
  7259. while (p < end && !points[p]) {
  7260. p++;
  7261. }
  7262. if (p === end) {
  7263. continue;
  7264. }
  7265. path.moveTo(p % width1, i);
  7266. const p0 = p;
  7267. let type = points[p];
  7268. do {
  7269. const step = steps[type];
  7270. do {
  7271. p += step;
  7272. } while (!points[p]);
  7273. const pp = points[p];
  7274. if (pp !== 5 && pp !== 10) {
  7275. type = pp;
  7276. points[p] = 0;
  7277. } else {
  7278. type = pp & 0x33 * type >> 4;
  7279. points[p] &= type >> 2 | type << 2;
  7280. }
  7281. path.lineTo(p % width1, p / width1 | 0);
  7282. if (!points[p]) {
  7283. --count;
  7284. }
  7285. } while (p0 !== p);
  7286. --i;
  7287. }
  7288. data = null;
  7289. points = null;
  7290. const drawOutline = function (c) {
  7291. c.save();
  7292. c.scale(1 / width, -1 / height);
  7293. c.translate(0, -height);
  7294. c.fill(path);
  7295. c.beginPath();
  7296. c.restore();
  7297. };
  7298. return drawOutline;
  7299. }
  7300. class CanvasExtraState {
  7301. constructor(width, height) {
  7302. this.alphaIsShape = false;
  7303. this.fontSize = 0;
  7304. this.fontSizeScale = 1;
  7305. this.textMatrix = IDENTITY_MATRIX;
  7306. this.textMatrixScale = 1;
  7307. this.fontMatrix = FONT_IDENTITY_MATRIX;
  7308. this.leading = 0;
  7309. this.x = 0;
  7310. this.y = 0;
  7311. this.lineX = 0;
  7312. this.lineY = 0;
  7313. this.charSpacing = 0;
  7314. this.wordSpacing = 0;
  7315. this.textHScale = 1;
  7316. this.textRenderingMode = TextRenderingMode.FILL;
  7317. this.textRise = 0;
  7318. this.fillColor = "#000000";
  7319. this.strokeColor = "#000000";
  7320. this.patternFill = false;
  7321. this.patternStroke = false;
  7322. this.fillAlpha = 1;
  7323. this.strokeAlpha = 1;
  7324. this.lineWidth = 1;
  7325. this.activeSMask = null;
  7326. this.transferMaps = "none";
  7327. this.startNewPathAndClipBox([0, 0, width, height]);
  7328. }
  7329. clone() {
  7330. const clone = Object.create(this);
  7331. clone.clipBox = this.clipBox.slice();
  7332. return clone;
  7333. }
  7334. setCurrentPoint(x, y) {
  7335. this.x = x;
  7336. this.y = y;
  7337. }
  7338. updatePathMinMax(transform, x, y) {
  7339. [x, y] = Util.applyTransform([x, y], transform);
  7340. this.minX = Math.min(this.minX, x);
  7341. this.minY = Math.min(this.minY, y);
  7342. this.maxX = Math.max(this.maxX, x);
  7343. this.maxY = Math.max(this.maxY, y);
  7344. }
  7345. updateRectMinMax(transform, rect) {
  7346. const p1 = Util.applyTransform(rect, transform);
  7347. const p2 = Util.applyTransform(rect.slice(2), transform);
  7348. const p3 = Util.applyTransform([rect[0], rect[3]], transform);
  7349. const p4 = Util.applyTransform([rect[2], rect[1]], transform);
  7350. this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]);
  7351. this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]);
  7352. this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]);
  7353. this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]);
  7354. }
  7355. updateScalingPathMinMax(transform, minMax) {
  7356. Util.scaleMinMax(transform, minMax);
  7357. this.minX = Math.min(this.minX, minMax[0]);
  7358. this.minY = Math.min(this.minY, minMax[1]);
  7359. this.maxX = Math.max(this.maxX, minMax[2]);
  7360. this.maxY = Math.max(this.maxY, minMax[3]);
  7361. }
  7362. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  7363. const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax);
  7364. if (minMax) {
  7365. return;
  7366. }
  7367. this.updateRectMinMax(transform, box);
  7368. }
  7369. getPathBoundingBox(pathType = PathType.FILL, transform = null) {
  7370. const box = [this.minX, this.minY, this.maxX, this.maxY];
  7371. if (pathType === PathType.STROKE) {
  7372. if (!transform) {
  7373. unreachable("Stroke bounding box must include transform.");
  7374. }
  7375. const scale = Util.singularValueDecompose2dScale(transform);
  7376. const xStrokePad = scale[0] * this.lineWidth / 2;
  7377. const yStrokePad = scale[1] * this.lineWidth / 2;
  7378. box[0] -= xStrokePad;
  7379. box[1] -= yStrokePad;
  7380. box[2] += xStrokePad;
  7381. box[3] += yStrokePad;
  7382. }
  7383. return box;
  7384. }
  7385. updateClipFromPath() {
  7386. const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
  7387. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  7388. }
  7389. isEmptyClip() {
  7390. return this.minX === Infinity;
  7391. }
  7392. startNewPathAndClipBox(box) {
  7393. this.clipBox = box;
  7394. this.minX = Infinity;
  7395. this.minY = Infinity;
  7396. this.maxX = 0;
  7397. this.maxY = 0;
  7398. }
  7399. getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
  7400. return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  7401. }
  7402. }
  7403. function putBinaryImageData(ctx, imgData) {
  7404. if (imgData instanceof ImageData) {
  7405. ctx.putImageData(imgData, 0, 0);
  7406. return;
  7407. }
  7408. const height = imgData.height,
  7409. width = imgData.width;
  7410. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  7411. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  7412. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  7413. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  7414. let srcPos = 0,
  7415. destPos;
  7416. const src = imgData.data;
  7417. const dest = chunkImgData.data;
  7418. let i, j, thisChunkHeight, elemsInThisChunk;
  7419. if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
  7420. const srcLength = src.byteLength;
  7421. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  7422. const dest32DataLength = dest32.length;
  7423. const fullSrcDiff = width + 7 >> 3;
  7424. const white = 0xffffffff;
  7425. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  7426. for (i = 0; i < totalChunks; i++) {
  7427. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  7428. destPos = 0;
  7429. for (j = 0; j < thisChunkHeight; j++) {
  7430. const srcDiff = srcLength - srcPos;
  7431. let k = 0;
  7432. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  7433. const kEndUnrolled = kEnd & ~7;
  7434. let mask = 0;
  7435. let srcByte = 0;
  7436. for (; k < kEndUnrolled; k += 8) {
  7437. srcByte = src[srcPos++];
  7438. dest32[destPos++] = srcByte & 128 ? white : black;
  7439. dest32[destPos++] = srcByte & 64 ? white : black;
  7440. dest32[destPos++] = srcByte & 32 ? white : black;
  7441. dest32[destPos++] = srcByte & 16 ? white : black;
  7442. dest32[destPos++] = srcByte & 8 ? white : black;
  7443. dest32[destPos++] = srcByte & 4 ? white : black;
  7444. dest32[destPos++] = srcByte & 2 ? white : black;
  7445. dest32[destPos++] = srcByte & 1 ? white : black;
  7446. }
  7447. for (; k < kEnd; k++) {
  7448. if (mask === 0) {
  7449. srcByte = src[srcPos++];
  7450. mask = 128;
  7451. }
  7452. dest32[destPos++] = srcByte & mask ? white : black;
  7453. mask >>= 1;
  7454. }
  7455. }
  7456. while (destPos < dest32DataLength) {
  7457. dest32[destPos++] = 0;
  7458. }
  7459. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  7460. }
  7461. } else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
  7462. j = 0;
  7463. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  7464. for (i = 0; i < fullChunks; i++) {
  7465. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  7466. srcPos += elemsInThisChunk;
  7467. ctx.putImageData(chunkImgData, 0, j);
  7468. j += FULL_CHUNK_HEIGHT;
  7469. }
  7470. if (i < totalChunks) {
  7471. elemsInThisChunk = width * partialChunkHeight * 4;
  7472. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  7473. ctx.putImageData(chunkImgData, 0, j);
  7474. }
  7475. } else if (imgData.kind === util_ImageKind.RGB_24BPP) {
  7476. thisChunkHeight = FULL_CHUNK_HEIGHT;
  7477. elemsInThisChunk = width * thisChunkHeight;
  7478. for (i = 0; i < totalChunks; i++) {
  7479. if (i >= fullChunks) {
  7480. thisChunkHeight = partialChunkHeight;
  7481. elemsInThisChunk = width * thisChunkHeight;
  7482. }
  7483. destPos = 0;
  7484. for (j = elemsInThisChunk; j--;) {
  7485. dest[destPos++] = src[srcPos++];
  7486. dest[destPos++] = src[srcPos++];
  7487. dest[destPos++] = src[srcPos++];
  7488. dest[destPos++] = 255;
  7489. }
  7490. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  7491. }
  7492. } else {
  7493. throw new Error(`bad image kind: ${imgData.kind}`);
  7494. }
  7495. }
  7496. function putBinaryImageMask(ctx, imgData) {
  7497. if (imgData.bitmap) {
  7498. ctx.drawImage(imgData.bitmap, 0, 0);
  7499. return;
  7500. }
  7501. const height = imgData.height,
  7502. width = imgData.width;
  7503. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  7504. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  7505. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  7506. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  7507. let srcPos = 0;
  7508. const src = imgData.data;
  7509. const dest = chunkImgData.data;
  7510. for (let i = 0; i < totalChunks; i++) {
  7511. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  7512. ({
  7513. srcPos
  7514. } = convertBlackAndWhiteToRGBA({
  7515. src,
  7516. srcPos,
  7517. dest,
  7518. width,
  7519. height: thisChunkHeight,
  7520. nonBlackColor: 0
  7521. }));
  7522. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  7523. }
  7524. }
  7525. function copyCtxState(sourceCtx, destCtx) {
  7526. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
  7527. for (const property of properties) {
  7528. if (sourceCtx[property] !== undefined) {
  7529. destCtx[property] = sourceCtx[property];
  7530. }
  7531. }
  7532. if (sourceCtx.setLineDash !== undefined) {
  7533. destCtx.setLineDash(sourceCtx.getLineDash());
  7534. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  7535. }
  7536. }
  7537. function resetCtxToDefault(ctx) {
  7538. ctx.strokeStyle = ctx.fillStyle = "#000000";
  7539. ctx.fillRule = "nonzero";
  7540. ctx.globalAlpha = 1;
  7541. ctx.lineWidth = 1;
  7542. ctx.lineCap = "butt";
  7543. ctx.lineJoin = "miter";
  7544. ctx.miterLimit = 10;
  7545. ctx.globalCompositeOperation = "source-over";
  7546. ctx.font = "10px sans-serif";
  7547. if (ctx.setLineDash !== undefined) {
  7548. ctx.setLineDash([]);
  7549. ctx.lineDashOffset = 0;
  7550. }
  7551. if (!isNodeJS) {
  7552. const {
  7553. filter
  7554. } = ctx;
  7555. if (filter !== "none" && filter !== "") {
  7556. ctx.filter = "none";
  7557. }
  7558. }
  7559. }
  7560. function getImageSmoothingEnabled(transform, interpolate) {
  7561. if (interpolate) {
  7562. return true;
  7563. }
  7564. const scale = Util.singularValueDecompose2dScale(transform);
  7565. scale[0] = Math.fround(scale[0]);
  7566. scale[1] = Math.fround(scale[1]);
  7567. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS);
  7568. return scale[0] <= actualScale && scale[1] <= actualScale;
  7569. }
  7570. const LINE_CAP_STYLES = ["butt", "round", "square"];
  7571. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  7572. const NORMAL_CLIP = {};
  7573. const EO_CLIP = {};
  7574. class CanvasGraphics {
  7575. constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
  7576. optionalContentConfig,
  7577. markedContentStack = null
  7578. }, annotationCanvasMap, pageColors) {
  7579. this.ctx = canvasCtx;
  7580. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  7581. this.stateStack = [];
  7582. this.pendingClip = null;
  7583. this.pendingEOFill = false;
  7584. this.res = null;
  7585. this.xobjs = null;
  7586. this.commonObjs = commonObjs;
  7587. this.objs = objs;
  7588. this.canvasFactory = canvasFactory;
  7589. this.filterFactory = filterFactory;
  7590. this.groupStack = [];
  7591. this.processingType3 = null;
  7592. this.baseTransform = null;
  7593. this.baseTransformStack = [];
  7594. this.groupLevel = 0;
  7595. this.smaskStack = [];
  7596. this.smaskCounter = 0;
  7597. this.tempSMask = null;
  7598. this.suspendedCtx = null;
  7599. this.contentVisible = true;
  7600. this.markedContentStack = markedContentStack || [];
  7601. this.optionalContentConfig = optionalContentConfig;
  7602. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  7603. this.cachedPatterns = new Map();
  7604. this.annotationCanvasMap = annotationCanvasMap;
  7605. this.viewportScale = 1;
  7606. this.outputScaleX = 1;
  7607. this.outputScaleY = 1;
  7608. this.pageColors = pageColors;
  7609. this._cachedScaleForStroking = [-1, 0];
  7610. this._cachedGetSinglePixelWidth = null;
  7611. this._cachedBitmapsMap = new Map();
  7612. }
  7613. getObject(data, fallback = null) {
  7614. if (typeof data === "string") {
  7615. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  7616. }
  7617. return fallback;
  7618. }
  7619. beginDrawing({
  7620. transform,
  7621. viewport,
  7622. transparency = false,
  7623. background = null
  7624. }) {
  7625. const width = this.ctx.canvas.width;
  7626. const height = this.ctx.canvas.height;
  7627. const savedFillStyle = this.ctx.fillStyle;
  7628. this.ctx.fillStyle = background || "#ffffff";
  7629. this.ctx.fillRect(0, 0, width, height);
  7630. this.ctx.fillStyle = savedFillStyle;
  7631. if (transparency) {
  7632. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  7633. this.compositeCtx = this.ctx;
  7634. this.transparentCanvas = transparentCanvas.canvas;
  7635. this.ctx = transparentCanvas.context;
  7636. this.ctx.save();
  7637. this.ctx.transform(...getCurrentTransform(this.compositeCtx));
  7638. }
  7639. this.ctx.save();
  7640. resetCtxToDefault(this.ctx);
  7641. if (transform) {
  7642. this.ctx.transform(...transform);
  7643. this.outputScaleX = transform[0];
  7644. this.outputScaleY = transform[0];
  7645. }
  7646. this.ctx.transform(...viewport.transform);
  7647. this.viewportScale = viewport.scale;
  7648. this.baseTransform = getCurrentTransform(this.ctx);
  7649. }
  7650. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  7651. const argsArray = operatorList.argsArray;
  7652. const fnArray = operatorList.fnArray;
  7653. let i = executionStartIdx || 0;
  7654. const argsArrayLen = argsArray.length;
  7655. if (argsArrayLen === i) {
  7656. return i;
  7657. }
  7658. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  7659. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  7660. let steps = 0;
  7661. const commonObjs = this.commonObjs;
  7662. const objs = this.objs;
  7663. let fnId;
  7664. while (true) {
  7665. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  7666. stepper.breakIt(i, continueCallback);
  7667. return i;
  7668. }
  7669. fnId = fnArray[i];
  7670. if (fnId !== OPS.dependency) {
  7671. this[fnId].apply(this, argsArray[i]);
  7672. } else {
  7673. for (const depObjId of argsArray[i]) {
  7674. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  7675. if (!objsPool.has(depObjId)) {
  7676. objsPool.get(depObjId, continueCallback);
  7677. return i;
  7678. }
  7679. }
  7680. }
  7681. i++;
  7682. if (i === argsArrayLen) {
  7683. return i;
  7684. }
  7685. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  7686. if (Date.now() > endTime) {
  7687. continueCallback();
  7688. return i;
  7689. }
  7690. steps = 0;
  7691. }
  7692. }
  7693. }
  7694. #restoreInitialState() {
  7695. while (this.stateStack.length || this.inSMaskMode) {
  7696. this.restore();
  7697. }
  7698. this.current.activeSMask = null;
  7699. this.ctx.restore();
  7700. if (this.transparentCanvas) {
  7701. this.ctx = this.compositeCtx;
  7702. this.ctx.save();
  7703. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7704. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  7705. this.ctx.restore();
  7706. this.transparentCanvas = null;
  7707. }
  7708. }
  7709. endDrawing() {
  7710. this.#restoreInitialState();
  7711. this.cachedCanvases.clear();
  7712. this.cachedPatterns.clear();
  7713. for (const cache of this._cachedBitmapsMap.values()) {
  7714. for (const canvas of cache.values()) {
  7715. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  7716. canvas.width = canvas.height = 0;
  7717. }
  7718. }
  7719. cache.clear();
  7720. }
  7721. this._cachedBitmapsMap.clear();
  7722. this.#drawFilter();
  7723. }
  7724. #drawFilter() {
  7725. if (this.pageColors) {
  7726. const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
  7727. if (hcmFilterId !== "none") {
  7728. const savedFilter = this.ctx.filter;
  7729. this.ctx.filter = hcmFilterId;
  7730. this.ctx.drawImage(this.ctx.canvas, 0, 0);
  7731. this.ctx.filter = savedFilter;
  7732. }
  7733. }
  7734. }
  7735. _scaleImage(img, inverseTransform) {
  7736. const width = img.width ?? img.displayWidth;
  7737. const height = img.height ?? img.displayHeight;
  7738. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  7739. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  7740. let paintWidth = width,
  7741. paintHeight = height;
  7742. let tmpCanvasId = "prescale1";
  7743. let tmpCanvas, tmpCtx;
  7744. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  7745. let newWidth = paintWidth,
  7746. newHeight = paintHeight;
  7747. if (widthScale > 2 && paintWidth > 1) {
  7748. newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
  7749. widthScale /= paintWidth / newWidth;
  7750. }
  7751. if (heightScale > 2 && paintHeight > 1) {
  7752. newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
  7753. heightScale /= paintHeight / newHeight;
  7754. }
  7755. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  7756. tmpCtx = tmpCanvas.context;
  7757. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7758. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  7759. img = tmpCanvas.canvas;
  7760. paintWidth = newWidth;
  7761. paintHeight = newHeight;
  7762. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  7763. }
  7764. return {
  7765. img,
  7766. paintWidth,
  7767. paintHeight
  7768. };
  7769. }
  7770. _createMaskCanvas(img) {
  7771. const ctx = this.ctx;
  7772. const {
  7773. width,
  7774. height
  7775. } = img;
  7776. const fillColor = this.current.fillColor;
  7777. const isPatternFill = this.current.patternFill;
  7778. const currentTransform = getCurrentTransform(ctx);
  7779. let cache, cacheKey, scaled, maskCanvas;
  7780. if ((img.bitmap || img.data) && img.count > 1) {
  7781. const mainKey = img.bitmap || img.data.buffer;
  7782. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  7783. cache = this._cachedBitmapsMap.get(mainKey);
  7784. if (!cache) {
  7785. cache = new Map();
  7786. this._cachedBitmapsMap.set(mainKey, cache);
  7787. }
  7788. const cachedImage = cache.get(cacheKey);
  7789. if (cachedImage && !isPatternFill) {
  7790. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  7791. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  7792. return {
  7793. canvas: cachedImage,
  7794. offsetX,
  7795. offsetY
  7796. };
  7797. }
  7798. scaled = cachedImage;
  7799. }
  7800. if (!scaled) {
  7801. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  7802. putBinaryImageMask(maskCanvas.context, img);
  7803. }
  7804. let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  7805. maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  7806. const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox([0, 0, width, height], maskToCanvas);
  7807. const drawnWidth = Math.round(maxX - minX) || 1;
  7808. const drawnHeight = Math.round(maxY - minY) || 1;
  7809. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  7810. const fillCtx = fillCanvas.context;
  7811. const offsetX = minX;
  7812. const offsetY = minY;
  7813. fillCtx.translate(-offsetX, -offsetY);
  7814. fillCtx.transform(...maskToCanvas);
  7815. if (!scaled) {
  7816. scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
  7817. scaled = scaled.img;
  7818. if (cache && isPatternFill) {
  7819. cache.set(cacheKey, scaled);
  7820. }
  7821. }
  7822. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
  7823. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  7824. fillCtx.globalCompositeOperation = "source-in";
  7825. const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  7826. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor;
  7827. fillCtx.fillRect(0, 0, width, height);
  7828. if (cache && !isPatternFill) {
  7829. this.cachedCanvases.delete("fillCanvas");
  7830. cache.set(cacheKey, fillCanvas.canvas);
  7831. }
  7832. return {
  7833. canvas: fillCanvas.canvas,
  7834. offsetX: Math.round(offsetX),
  7835. offsetY: Math.round(offsetY)
  7836. };
  7837. }
  7838. setLineWidth(width) {
  7839. if (width !== this.current.lineWidth) {
  7840. this._cachedScaleForStroking[0] = -1;
  7841. }
  7842. this.current.lineWidth = width;
  7843. this.ctx.lineWidth = width;
  7844. }
  7845. setLineCap(style) {
  7846. this.ctx.lineCap = LINE_CAP_STYLES[style];
  7847. }
  7848. setLineJoin(style) {
  7849. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  7850. }
  7851. setMiterLimit(limit) {
  7852. this.ctx.miterLimit = limit;
  7853. }
  7854. setDash(dashArray, dashPhase) {
  7855. const ctx = this.ctx;
  7856. if (ctx.setLineDash !== undefined) {
  7857. ctx.setLineDash(dashArray);
  7858. ctx.lineDashOffset = dashPhase;
  7859. }
  7860. }
  7861. setRenderingIntent(intent) {}
  7862. setFlatness(flatness) {}
  7863. setGState(states) {
  7864. for (const [key, value] of states) {
  7865. switch (key) {
  7866. case "LW":
  7867. this.setLineWidth(value);
  7868. break;
  7869. case "LC":
  7870. this.setLineCap(value);
  7871. break;
  7872. case "LJ":
  7873. this.setLineJoin(value);
  7874. break;
  7875. case "ML":
  7876. this.setMiterLimit(value);
  7877. break;
  7878. case "D":
  7879. this.setDash(value[0], value[1]);
  7880. break;
  7881. case "RI":
  7882. this.setRenderingIntent(value);
  7883. break;
  7884. case "FL":
  7885. this.setFlatness(value);
  7886. break;
  7887. case "Font":
  7888. this.setFont(value[0], value[1]);
  7889. break;
  7890. case "CA":
  7891. this.current.strokeAlpha = value;
  7892. break;
  7893. case "ca":
  7894. this.current.fillAlpha = value;
  7895. this.ctx.globalAlpha = value;
  7896. break;
  7897. case "BM":
  7898. this.ctx.globalCompositeOperation = value;
  7899. break;
  7900. case "SMask":
  7901. this.current.activeSMask = value ? this.tempSMask : null;
  7902. this.tempSMask = null;
  7903. this.checkSMaskState();
  7904. break;
  7905. case "TR":
  7906. this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
  7907. break;
  7908. }
  7909. }
  7910. }
  7911. get inSMaskMode() {
  7912. return !!this.suspendedCtx;
  7913. }
  7914. checkSMaskState() {
  7915. const inSMaskMode = this.inSMaskMode;
  7916. if (this.current.activeSMask && !inSMaskMode) {
  7917. this.beginSMaskMode();
  7918. } else if (!this.current.activeSMask && inSMaskMode) {
  7919. this.endSMaskMode();
  7920. }
  7921. }
  7922. beginSMaskMode() {
  7923. if (this.inSMaskMode) {
  7924. throw new Error("beginSMaskMode called while already in smask mode");
  7925. }
  7926. const drawnWidth = this.ctx.canvas.width;
  7927. const drawnHeight = this.ctx.canvas.height;
  7928. const cacheId = "smaskGroupAt" + this.groupLevel;
  7929. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  7930. this.suspendedCtx = this.ctx;
  7931. this.ctx = scratchCanvas.context;
  7932. const ctx = this.ctx;
  7933. ctx.setTransform(...getCurrentTransform(this.suspendedCtx));
  7934. copyCtxState(this.suspendedCtx, ctx);
  7935. mirrorContextOperations(ctx, this.suspendedCtx);
  7936. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  7937. }
  7938. endSMaskMode() {
  7939. if (!this.inSMaskMode) {
  7940. throw new Error("endSMaskMode called while not in smask mode");
  7941. }
  7942. this.ctx._removeMirroring();
  7943. copyCtxState(this.ctx, this.suspendedCtx);
  7944. this.ctx = this.suspendedCtx;
  7945. this.suspendedCtx = null;
  7946. }
  7947. compose(dirtyBox) {
  7948. if (!this.current.activeSMask) {
  7949. return;
  7950. }
  7951. if (!dirtyBox) {
  7952. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  7953. } else {
  7954. dirtyBox[0] = Math.floor(dirtyBox[0]);
  7955. dirtyBox[1] = Math.floor(dirtyBox[1]);
  7956. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  7957. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  7958. }
  7959. const smask = this.current.activeSMask;
  7960. const suspendedCtx = this.suspendedCtx;
  7961. this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  7962. this.ctx.save();
  7963. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7964. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  7965. this.ctx.restore();
  7966. }
  7967. composeSMask(ctx, smask, layerCtx, layerBox) {
  7968. const layerOffsetX = layerBox[0];
  7969. const layerOffsetY = layerBox[1];
  7970. const layerWidth = layerBox[2] - layerOffsetX;
  7971. const layerHeight = layerBox[3] - layerOffsetY;
  7972. if (layerWidth === 0 || layerHeight === 0) {
  7973. return;
  7974. }
  7975. this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  7976. ctx.save();
  7977. ctx.globalAlpha = 1;
  7978. ctx.globalCompositeOperation = "source-over";
  7979. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7980. ctx.drawImage(layerCtx.canvas, 0, 0);
  7981. ctx.restore();
  7982. }
  7983. genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  7984. let maskCanvas = maskCtx.canvas;
  7985. let maskX = layerOffsetX - maskOffsetX;
  7986. let maskY = layerOffsetY - maskOffsetY;
  7987. if (backdrop) {
  7988. const backdropRGB = Util.makeHexColor(...backdrop);
  7989. if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
  7990. const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
  7991. const ctx = canvas.context;
  7992. ctx.drawImage(maskCanvas, -maskX, -maskY);
  7993. ctx.globalCompositeOperation = "destination-atop";
  7994. ctx.fillStyle = backdropRGB;
  7995. ctx.fillRect(0, 0, width, height);
  7996. ctx.globalCompositeOperation = "source-over";
  7997. maskCanvas = canvas.canvas;
  7998. maskX = maskY = 0;
  7999. } else {
  8000. maskCtx.save();
  8001. maskCtx.globalAlpha = 1;
  8002. maskCtx.setTransform(1, 0, 0, 1, 0, 0);
  8003. const clip = new Path2D();
  8004. clip.rect(maskX, maskY, width, height);
  8005. maskCtx.clip(clip);
  8006. maskCtx.globalCompositeOperation = "destination-atop";
  8007. maskCtx.fillStyle = backdropRGB;
  8008. maskCtx.fillRect(maskX, maskY, width, height);
  8009. maskCtx.restore();
  8010. }
  8011. }
  8012. layerCtx.save();
  8013. layerCtx.globalAlpha = 1;
  8014. layerCtx.setTransform(1, 0, 0, 1, 0, 0);
  8015. if (subtype === "Alpha" && transferMap) {
  8016. layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
  8017. } else if (subtype === "Luminosity") {
  8018. layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
  8019. }
  8020. const clip = new Path2D();
  8021. clip.rect(layerOffsetX, layerOffsetY, width, height);
  8022. layerCtx.clip(clip);
  8023. layerCtx.globalCompositeOperation = "destination-in";
  8024. layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
  8025. layerCtx.restore();
  8026. }
  8027. save() {
  8028. if (this.inSMaskMode) {
  8029. copyCtxState(this.ctx, this.suspendedCtx);
  8030. this.suspendedCtx.save();
  8031. } else {
  8032. this.ctx.save();
  8033. }
  8034. const old = this.current;
  8035. this.stateStack.push(old);
  8036. this.current = old.clone();
  8037. }
  8038. restore() {
  8039. if (this.stateStack.length === 0 && this.inSMaskMode) {
  8040. this.endSMaskMode();
  8041. }
  8042. if (this.stateStack.length !== 0) {
  8043. this.current = this.stateStack.pop();
  8044. if (this.inSMaskMode) {
  8045. this.suspendedCtx.restore();
  8046. copyCtxState(this.suspendedCtx, this.ctx);
  8047. } else {
  8048. this.ctx.restore();
  8049. }
  8050. this.checkSMaskState();
  8051. this.pendingClip = null;
  8052. this._cachedScaleForStroking[0] = -1;
  8053. this._cachedGetSinglePixelWidth = null;
  8054. }
  8055. }
  8056. transform(a, b, c, d, e, f) {
  8057. this.ctx.transform(a, b, c, d, e, f);
  8058. this._cachedScaleForStroking[0] = -1;
  8059. this._cachedGetSinglePixelWidth = null;
  8060. }
  8061. constructPath(ops, args, minMax) {
  8062. const ctx = this.ctx;
  8063. const current = this.current;
  8064. let x = current.x,
  8065. y = current.y;
  8066. let startX, startY;
  8067. const currentTransform = getCurrentTransform(ctx);
  8068. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  8069. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  8070. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  8071. switch (ops[i] | 0) {
  8072. case OPS.rectangle:
  8073. x = args[j++];
  8074. y = args[j++];
  8075. const width = args[j++];
  8076. const height = args[j++];
  8077. const xw = x + width;
  8078. const yh = y + height;
  8079. ctx.moveTo(x, y);
  8080. if (width === 0 || height === 0) {
  8081. ctx.lineTo(xw, yh);
  8082. } else {
  8083. ctx.lineTo(xw, y);
  8084. ctx.lineTo(xw, yh);
  8085. ctx.lineTo(x, yh);
  8086. }
  8087. if (!isScalingMatrix) {
  8088. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  8089. }
  8090. ctx.closePath();
  8091. break;
  8092. case OPS.moveTo:
  8093. x = args[j++];
  8094. y = args[j++];
  8095. ctx.moveTo(x, y);
  8096. if (!isScalingMatrix) {
  8097. current.updatePathMinMax(currentTransform, x, y);
  8098. }
  8099. break;
  8100. case OPS.lineTo:
  8101. x = args[j++];
  8102. y = args[j++];
  8103. ctx.lineTo(x, y);
  8104. if (!isScalingMatrix) {
  8105. current.updatePathMinMax(currentTransform, x, y);
  8106. }
  8107. break;
  8108. case OPS.curveTo:
  8109. startX = x;
  8110. startY = y;
  8111. x = args[j + 4];
  8112. y = args[j + 5];
  8113. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  8114. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  8115. j += 6;
  8116. break;
  8117. case OPS.curveTo2:
  8118. startX = x;
  8119. startY = y;
  8120. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  8121. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  8122. x = args[j + 2];
  8123. y = args[j + 3];
  8124. j += 4;
  8125. break;
  8126. case OPS.curveTo3:
  8127. startX = x;
  8128. startY = y;
  8129. x = args[j + 2];
  8130. y = args[j + 3];
  8131. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  8132. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  8133. j += 4;
  8134. break;
  8135. case OPS.closePath:
  8136. ctx.closePath();
  8137. break;
  8138. }
  8139. }
  8140. if (isScalingMatrix) {
  8141. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  8142. }
  8143. current.setCurrentPoint(x, y);
  8144. }
  8145. closePath() {
  8146. this.ctx.closePath();
  8147. }
  8148. stroke(consumePath = true) {
  8149. const ctx = this.ctx;
  8150. const strokeColor = this.current.strokeColor;
  8151. ctx.globalAlpha = this.current.strokeAlpha;
  8152. if (this.contentVisible) {
  8153. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  8154. ctx.save();
  8155. ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
  8156. this.rescaleAndStroke(false);
  8157. ctx.restore();
  8158. } else {
  8159. this.rescaleAndStroke(true);
  8160. }
  8161. }
  8162. if (consumePath) {
  8163. this.consumePath(this.current.getClippedPathBoundingBox());
  8164. }
  8165. ctx.globalAlpha = this.current.fillAlpha;
  8166. }
  8167. closeStroke() {
  8168. this.closePath();
  8169. this.stroke();
  8170. }
  8171. fill(consumePath = true) {
  8172. const ctx = this.ctx;
  8173. const fillColor = this.current.fillColor;
  8174. const isPatternFill = this.current.patternFill;
  8175. let needRestore = false;
  8176. if (isPatternFill) {
  8177. ctx.save();
  8178. ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  8179. needRestore = true;
  8180. }
  8181. const intersect = this.current.getClippedPathBoundingBox();
  8182. if (this.contentVisible && intersect !== null) {
  8183. if (this.pendingEOFill) {
  8184. ctx.fill("evenodd");
  8185. this.pendingEOFill = false;
  8186. } else {
  8187. ctx.fill();
  8188. }
  8189. }
  8190. if (needRestore) {
  8191. ctx.restore();
  8192. }
  8193. if (consumePath) {
  8194. this.consumePath(intersect);
  8195. }
  8196. }
  8197. eoFill() {
  8198. this.pendingEOFill = true;
  8199. this.fill();
  8200. }
  8201. fillStroke() {
  8202. this.fill(false);
  8203. this.stroke(false);
  8204. this.consumePath();
  8205. }
  8206. eoFillStroke() {
  8207. this.pendingEOFill = true;
  8208. this.fillStroke();
  8209. }
  8210. closeFillStroke() {
  8211. this.closePath();
  8212. this.fillStroke();
  8213. }
  8214. closeEOFillStroke() {
  8215. this.pendingEOFill = true;
  8216. this.closePath();
  8217. this.fillStroke();
  8218. }
  8219. endPath() {
  8220. this.consumePath();
  8221. }
  8222. clip() {
  8223. this.pendingClip = NORMAL_CLIP;
  8224. }
  8225. eoClip() {
  8226. this.pendingClip = EO_CLIP;
  8227. }
  8228. beginText() {
  8229. this.current.textMatrix = IDENTITY_MATRIX;
  8230. this.current.textMatrixScale = 1;
  8231. this.current.x = this.current.lineX = 0;
  8232. this.current.y = this.current.lineY = 0;
  8233. }
  8234. endText() {
  8235. const paths = this.pendingTextPaths;
  8236. const ctx = this.ctx;
  8237. if (paths === undefined) {
  8238. ctx.beginPath();
  8239. return;
  8240. }
  8241. const newPath = new Path2D();
  8242. const invTransf = ctx.getTransform().invertSelf();
  8243. for (const {
  8244. transform,
  8245. x,
  8246. y,
  8247. fontSize,
  8248. path
  8249. } of paths) {
  8250. newPath.addPath(path, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x, y).scale(fontSize, -fontSize));
  8251. }
  8252. ctx.clip(newPath);
  8253. ctx.beginPath();
  8254. delete this.pendingTextPaths;
  8255. }
  8256. setCharSpacing(spacing) {
  8257. this.current.charSpacing = spacing;
  8258. }
  8259. setWordSpacing(spacing) {
  8260. this.current.wordSpacing = spacing;
  8261. }
  8262. setHScale(scale) {
  8263. this.current.textHScale = scale / 100;
  8264. }
  8265. setLeading(leading) {
  8266. this.current.leading = -leading;
  8267. }
  8268. setFont(fontRefName, size) {
  8269. const fontObj = this.commonObjs.get(fontRefName);
  8270. const current = this.current;
  8271. if (!fontObj) {
  8272. throw new Error(`Can't find font for ${fontRefName}`);
  8273. }
  8274. current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
  8275. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  8276. warn("Invalid font matrix for font " + fontRefName);
  8277. }
  8278. if (size < 0) {
  8279. size = -size;
  8280. current.fontDirection = -1;
  8281. } else {
  8282. current.fontDirection = 1;
  8283. }
  8284. this.current.font = fontObj;
  8285. this.current.fontSize = size;
  8286. if (fontObj.isType3Font) {
  8287. return;
  8288. }
  8289. const name = fontObj.loadedName || "sans-serif";
  8290. const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
  8291. let bold = "normal";
  8292. if (fontObj.black) {
  8293. bold = "900";
  8294. } else if (fontObj.bold) {
  8295. bold = "bold";
  8296. }
  8297. const italic = fontObj.italic ? "italic" : "normal";
  8298. let browserFontSize = size;
  8299. if (size < MIN_FONT_SIZE) {
  8300. browserFontSize = MIN_FONT_SIZE;
  8301. } else if (size > MAX_FONT_SIZE) {
  8302. browserFontSize = MAX_FONT_SIZE;
  8303. }
  8304. this.current.fontSizeScale = size / browserFontSize;
  8305. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  8306. }
  8307. setTextRenderingMode(mode) {
  8308. this.current.textRenderingMode = mode;
  8309. }
  8310. setTextRise(rise) {
  8311. this.current.textRise = rise;
  8312. }
  8313. moveText(x, y) {
  8314. this.current.x = this.current.lineX += x;
  8315. this.current.y = this.current.lineY += y;
  8316. }
  8317. setLeadingMoveText(x, y) {
  8318. this.setLeading(-y);
  8319. this.moveText(x, y);
  8320. }
  8321. setTextMatrix(a, b, c, d, e, f) {
  8322. this.current.textMatrix = [a, b, c, d, e, f];
  8323. this.current.textMatrixScale = Math.hypot(a, b);
  8324. this.current.x = this.current.lineX = 0;
  8325. this.current.y = this.current.lineY = 0;
  8326. }
  8327. nextLine() {
  8328. this.moveText(0, this.current.leading);
  8329. }
  8330. #getScaledPath(path, currentTransform, transform) {
  8331. const newPath = new Path2D();
  8332. newPath.addPath(path, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform));
  8333. return newPath;
  8334. }
  8335. paintChar(character, x, y, patternFillTransform, patternStrokeTransform) {
  8336. const ctx = this.ctx;
  8337. const current = this.current;
  8338. const font = current.font;
  8339. const textRenderingMode = current.textRenderingMode;
  8340. const fontSize = current.fontSize / current.fontSizeScale;
  8341. const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  8342. const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  8343. const patternFill = current.patternFill && !font.missingFile;
  8344. const patternStroke = current.patternStroke && !font.missingFile;
  8345. let path;
  8346. if (font.disableFontFace || isAddToPathSet || patternFill || patternStroke) {
  8347. path = font.getPathGenerator(this.commonObjs, character);
  8348. }
  8349. if (font.disableFontFace || patternFill || patternStroke) {
  8350. ctx.save();
  8351. ctx.translate(x, y);
  8352. ctx.scale(fontSize, -fontSize);
  8353. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  8354. if (patternFillTransform) {
  8355. const currentTransform = ctx.getTransform();
  8356. ctx.setTransform(...patternFillTransform);
  8357. ctx.fill(this.#getScaledPath(path, currentTransform, patternFillTransform));
  8358. } else {
  8359. ctx.fill(path);
  8360. }
  8361. }
  8362. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  8363. if (patternStrokeTransform) {
  8364. const currentTransform = ctx.getTransform();
  8365. ctx.setTransform(...patternStrokeTransform);
  8366. ctx.stroke(this.#getScaledPath(path, currentTransform, patternStrokeTransform));
  8367. } else {
  8368. ctx.lineWidth /= fontSize;
  8369. ctx.stroke(path);
  8370. }
  8371. }
  8372. ctx.restore();
  8373. } else {
  8374. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  8375. ctx.fillText(character, x, y);
  8376. }
  8377. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  8378. ctx.strokeText(character, x, y);
  8379. }
  8380. }
  8381. if (isAddToPathSet) {
  8382. const paths = this.pendingTextPaths ||= [];
  8383. paths.push({
  8384. transform: getCurrentTransform(ctx),
  8385. x,
  8386. y,
  8387. fontSize,
  8388. path
  8389. });
  8390. }
  8391. }
  8392. get isFontSubpixelAAEnabled() {
  8393. const {
  8394. context: ctx
  8395. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  8396. ctx.scale(1.5, 1);
  8397. ctx.fillText("I", 0, 10);
  8398. const data = ctx.getImageData(0, 0, 10, 10).data;
  8399. let enabled = false;
  8400. for (let i = 3; i < data.length; i += 4) {
  8401. if (data[i] > 0 && data[i] < 255) {
  8402. enabled = true;
  8403. break;
  8404. }
  8405. }
  8406. return shadow(this, "isFontSubpixelAAEnabled", enabled);
  8407. }
  8408. showText(glyphs) {
  8409. const current = this.current;
  8410. const font = current.font;
  8411. if (font.isType3Font) {
  8412. return this.showType3Text(glyphs);
  8413. }
  8414. const fontSize = current.fontSize;
  8415. if (fontSize === 0) {
  8416. return undefined;
  8417. }
  8418. const ctx = this.ctx;
  8419. const fontSizeScale = current.fontSizeScale;
  8420. const charSpacing = current.charSpacing;
  8421. const wordSpacing = current.wordSpacing;
  8422. const fontDirection = current.fontDirection;
  8423. const textHScale = current.textHScale * fontDirection;
  8424. const glyphsLength = glyphs.length;
  8425. const vertical = font.vertical;
  8426. const spacingDir = vertical ? 1 : -1;
  8427. const defaultVMetrics = font.defaultVMetrics;
  8428. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  8429. const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  8430. ctx.save();
  8431. ctx.transform(...current.textMatrix);
  8432. ctx.translate(current.x, current.y + current.textRise);
  8433. if (fontDirection > 0) {
  8434. ctx.scale(textHScale, -1);
  8435. } else {
  8436. ctx.scale(textHScale, 1);
  8437. }
  8438. let patternFillTransform, patternStrokeTransform;
  8439. if (current.patternFill) {
  8440. ctx.save();
  8441. const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  8442. patternFillTransform = getCurrentTransform(ctx);
  8443. ctx.restore();
  8444. ctx.fillStyle = pattern;
  8445. }
  8446. if (current.patternStroke) {
  8447. ctx.save();
  8448. const pattern = current.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
  8449. patternStrokeTransform = getCurrentTransform(ctx);
  8450. ctx.restore();
  8451. ctx.strokeStyle = pattern;
  8452. }
  8453. let lineWidth = current.lineWidth;
  8454. const scale = current.textMatrixScale;
  8455. if (scale === 0 || lineWidth === 0) {
  8456. const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  8457. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  8458. lineWidth = this.getSinglePixelWidth();
  8459. }
  8460. } else {
  8461. lineWidth /= scale;
  8462. }
  8463. if (fontSizeScale !== 1.0) {
  8464. ctx.scale(fontSizeScale, fontSizeScale);
  8465. lineWidth /= fontSizeScale;
  8466. }
  8467. ctx.lineWidth = lineWidth;
  8468. if (font.isInvalidPDFjsFont) {
  8469. const chars = [];
  8470. let width = 0;
  8471. for (const glyph of glyphs) {
  8472. chars.push(glyph.unicode);
  8473. width += glyph.width;
  8474. }
  8475. ctx.fillText(chars.join(""), 0, 0);
  8476. current.x += width * widthAdvanceScale * textHScale;
  8477. ctx.restore();
  8478. this.compose();
  8479. return undefined;
  8480. }
  8481. let x = 0,
  8482. i;
  8483. for (i = 0; i < glyphsLength; ++i) {
  8484. const glyph = glyphs[i];
  8485. if (typeof glyph === "number") {
  8486. x += spacingDir * glyph * fontSize / 1000;
  8487. continue;
  8488. }
  8489. let restoreNeeded = false;
  8490. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  8491. const character = glyph.fontChar;
  8492. const accent = glyph.accent;
  8493. let scaledX, scaledY;
  8494. let width = glyph.width;
  8495. if (vertical) {
  8496. const vmetric = glyph.vmetric || defaultVMetrics;
  8497. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  8498. const vy = vmetric[2] * widthAdvanceScale;
  8499. width = vmetric ? -vmetric[0] : width;
  8500. scaledX = vx / fontSizeScale;
  8501. scaledY = (x + vy) / fontSizeScale;
  8502. } else {
  8503. scaledX = x / fontSizeScale;
  8504. scaledY = 0;
  8505. }
  8506. if (font.remeasure && width > 0) {
  8507. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  8508. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  8509. const characterScaleX = width / measuredWidth;
  8510. restoreNeeded = true;
  8511. ctx.save();
  8512. ctx.scale(characterScaleX, 1);
  8513. scaledX /= characterScaleX;
  8514. } else if (width !== measuredWidth) {
  8515. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  8516. }
  8517. }
  8518. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  8519. if (simpleFillText && !accent) {
  8520. ctx.fillText(character, scaledX, scaledY);
  8521. } else {
  8522. this.paintChar(character, scaledX, scaledY, patternFillTransform, patternStrokeTransform);
  8523. if (accent) {
  8524. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  8525. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  8526. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform);
  8527. }
  8528. }
  8529. }
  8530. const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
  8531. x += charWidth;
  8532. if (restoreNeeded) {
  8533. ctx.restore();
  8534. }
  8535. }
  8536. if (vertical) {
  8537. current.y -= x;
  8538. } else {
  8539. current.x += x * textHScale;
  8540. }
  8541. ctx.restore();
  8542. this.compose();
  8543. return undefined;
  8544. }
  8545. showType3Text(glyphs) {
  8546. const ctx = this.ctx;
  8547. const current = this.current;
  8548. const font = current.font;
  8549. const fontSize = current.fontSize;
  8550. const fontDirection = current.fontDirection;
  8551. const spacingDir = font.vertical ? 1 : -1;
  8552. const charSpacing = current.charSpacing;
  8553. const wordSpacing = current.wordSpacing;
  8554. const textHScale = current.textHScale * fontDirection;
  8555. const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  8556. const glyphsLength = glyphs.length;
  8557. const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  8558. let i, glyph, width, spacingLength;
  8559. if (isTextInvisible || fontSize === 0) {
  8560. return;
  8561. }
  8562. this._cachedScaleForStroking[0] = -1;
  8563. this._cachedGetSinglePixelWidth = null;
  8564. ctx.save();
  8565. ctx.transform(...current.textMatrix);
  8566. ctx.translate(current.x, current.y);
  8567. ctx.scale(textHScale, fontDirection);
  8568. for (i = 0; i < glyphsLength; ++i) {
  8569. glyph = glyphs[i];
  8570. if (typeof glyph === "number") {
  8571. spacingLength = spacingDir * glyph * fontSize / 1000;
  8572. this.ctx.translate(spacingLength, 0);
  8573. current.x += spacingLength * textHScale;
  8574. continue;
  8575. }
  8576. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  8577. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  8578. if (!operatorList) {
  8579. warn(`Type3 character "${glyph.operatorListId}" is not available.`);
  8580. continue;
  8581. }
  8582. if (this.contentVisible) {
  8583. this.processingType3 = glyph;
  8584. this.save();
  8585. ctx.scale(fontSize, fontSize);
  8586. ctx.transform(...fontMatrix);
  8587. this.executeOperatorList(operatorList);
  8588. this.restore();
  8589. }
  8590. const transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  8591. width = transformed[0] * fontSize + spacing;
  8592. ctx.translate(width, 0);
  8593. current.x += width * textHScale;
  8594. }
  8595. ctx.restore();
  8596. this.processingType3 = null;
  8597. }
  8598. setCharWidth(xWidth, yWidth) {}
  8599. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  8600. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  8601. this.ctx.clip();
  8602. this.endPath();
  8603. }
  8604. getColorN_Pattern(IR) {
  8605. let pattern;
  8606. if (IR[0] === "TilingPattern") {
  8607. const color = IR[1];
  8608. const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
  8609. const canvasGraphicsFactory = {
  8610. createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  8611. optionalContentConfig: this.optionalContentConfig,
  8612. markedContentStack: this.markedContentStack
  8613. })
  8614. };
  8615. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  8616. } else {
  8617. pattern = this._getPattern(IR[1], IR[2]);
  8618. }
  8619. return pattern;
  8620. }
  8621. setStrokeColorN() {
  8622. this.current.strokeColor = this.getColorN_Pattern(arguments);
  8623. this.current.patternStroke = true;
  8624. }
  8625. setFillColorN() {
  8626. this.current.fillColor = this.getColorN_Pattern(arguments);
  8627. this.current.patternFill = true;
  8628. }
  8629. setStrokeRGBColor(r, g, b) {
  8630. this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(r, g, b);
  8631. this.current.patternStroke = false;
  8632. }
  8633. setStrokeTransparent() {
  8634. this.ctx.strokeStyle = this.current.strokeColor = "transparent";
  8635. this.current.patternStroke = false;
  8636. }
  8637. setFillRGBColor(r, g, b) {
  8638. this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b);
  8639. this.current.patternFill = false;
  8640. }
  8641. setFillTransparent() {
  8642. this.ctx.fillStyle = this.current.fillColor = "transparent";
  8643. this.current.patternFill = false;
  8644. }
  8645. _getPattern(objId, matrix = null) {
  8646. let pattern;
  8647. if (this.cachedPatterns.has(objId)) {
  8648. pattern = this.cachedPatterns.get(objId);
  8649. } else {
  8650. pattern = getShadingPattern(this.getObject(objId));
  8651. this.cachedPatterns.set(objId, pattern);
  8652. }
  8653. if (matrix) {
  8654. pattern.matrix = matrix;
  8655. }
  8656. return pattern;
  8657. }
  8658. shadingFill(objId) {
  8659. if (!this.contentVisible) {
  8660. return;
  8661. }
  8662. const ctx = this.ctx;
  8663. this.save();
  8664. const pattern = this._getPattern(objId);
  8665. ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING);
  8666. const inv = getCurrentTransformInverse(ctx);
  8667. if (inv) {
  8668. const {
  8669. width,
  8670. height
  8671. } = ctx.canvas;
  8672. const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox([0, 0, width, height], inv);
  8673. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  8674. } else {
  8675. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  8676. }
  8677. this.compose(this.current.getClippedPathBoundingBox());
  8678. this.restore();
  8679. }
  8680. beginInlineImage() {
  8681. unreachable("Should not call beginInlineImage");
  8682. }
  8683. beginImageData() {
  8684. unreachable("Should not call beginImageData");
  8685. }
  8686. paintFormXObjectBegin(matrix, bbox) {
  8687. if (!this.contentVisible) {
  8688. return;
  8689. }
  8690. this.save();
  8691. this.baseTransformStack.push(this.baseTransform);
  8692. if (matrix) {
  8693. this.transform(...matrix);
  8694. }
  8695. this.baseTransform = getCurrentTransform(this.ctx);
  8696. if (bbox) {
  8697. const width = bbox[2] - bbox[0];
  8698. const height = bbox[3] - bbox[1];
  8699. this.ctx.rect(bbox[0], bbox[1], width, height);
  8700. this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox);
  8701. this.clip();
  8702. this.endPath();
  8703. }
  8704. }
  8705. paintFormXObjectEnd() {
  8706. if (!this.contentVisible) {
  8707. return;
  8708. }
  8709. this.restore();
  8710. this.baseTransform = this.baseTransformStack.pop();
  8711. }
  8712. beginGroup(group) {
  8713. if (!this.contentVisible) {
  8714. return;
  8715. }
  8716. this.save();
  8717. if (this.inSMaskMode) {
  8718. this.endSMaskMode();
  8719. this.current.activeSMask = null;
  8720. }
  8721. const currentCtx = this.ctx;
  8722. if (!group.isolated) {
  8723. info("TODO: Support non-isolated groups.");
  8724. }
  8725. if (group.knockout) {
  8726. warn("Knockout groups not supported.");
  8727. }
  8728. const currentTransform = getCurrentTransform(currentCtx);
  8729. if (group.matrix) {
  8730. currentCtx.transform(...group.matrix);
  8731. }
  8732. if (!group.bbox) {
  8733. throw new Error("Bounding box is required.");
  8734. }
  8735. let bounds = Util.getAxialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx));
  8736. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  8737. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  8738. const offsetX = Math.floor(bounds[0]);
  8739. const offsetY = Math.floor(bounds[1]);
  8740. const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  8741. const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  8742. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  8743. let cacheId = "groupAt" + this.groupLevel;
  8744. if (group.smask) {
  8745. cacheId += "_smask_" + this.smaskCounter++ % 2;
  8746. }
  8747. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  8748. const groupCtx = scratchCanvas.context;
  8749. groupCtx.translate(-offsetX, -offsetY);
  8750. groupCtx.transform(...currentTransform);
  8751. if (group.smask) {
  8752. this.smaskStack.push({
  8753. canvas: scratchCanvas.canvas,
  8754. context: groupCtx,
  8755. offsetX,
  8756. offsetY,
  8757. subtype: group.smask.subtype,
  8758. backdrop: group.smask.backdrop,
  8759. transferMap: group.smask.transferMap || null,
  8760. startTransformInverse: null
  8761. });
  8762. } else {
  8763. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  8764. currentCtx.translate(offsetX, offsetY);
  8765. currentCtx.save();
  8766. }
  8767. copyCtxState(currentCtx, groupCtx);
  8768. this.ctx = groupCtx;
  8769. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  8770. this.groupStack.push(currentCtx);
  8771. this.groupLevel++;
  8772. }
  8773. endGroup(group) {
  8774. if (!this.contentVisible) {
  8775. return;
  8776. }
  8777. this.groupLevel--;
  8778. const groupCtx = this.ctx;
  8779. const ctx = this.groupStack.pop();
  8780. this.ctx = ctx;
  8781. this.ctx.imageSmoothingEnabled = false;
  8782. if (group.smask) {
  8783. this.tempSMask = this.smaskStack.pop();
  8784. this.restore();
  8785. } else {
  8786. this.ctx.restore();
  8787. const currentMtx = getCurrentTransform(this.ctx);
  8788. this.restore();
  8789. this.ctx.save();
  8790. this.ctx.setTransform(...currentMtx);
  8791. const dirtyBox = Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  8792. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  8793. this.ctx.restore();
  8794. this.compose(dirtyBox);
  8795. }
  8796. }
  8797. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  8798. this.#restoreInitialState();
  8799. resetCtxToDefault(this.ctx);
  8800. this.ctx.save();
  8801. this.save();
  8802. if (this.baseTransform) {
  8803. this.ctx.setTransform(...this.baseTransform);
  8804. }
  8805. if (rect) {
  8806. const width = rect[2] - rect[0];
  8807. const height = rect[3] - rect[1];
  8808. if (hasOwnCanvas && this.annotationCanvasMap) {
  8809. transform = transform.slice();
  8810. transform[4] -= rect[0];
  8811. transform[5] -= rect[1];
  8812. rect = rect.slice();
  8813. rect[0] = rect[1] = 0;
  8814. rect[2] = width;
  8815. rect[3] = height;
  8816. const [scaleX, scaleY] = Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx));
  8817. const {
  8818. viewportScale
  8819. } = this;
  8820. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  8821. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  8822. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  8823. const {
  8824. canvas,
  8825. context
  8826. } = this.annotationCanvas;
  8827. this.annotationCanvasMap.set(id, canvas);
  8828. this.annotationCanvas.savedCtx = this.ctx;
  8829. this.ctx = context;
  8830. this.ctx.save();
  8831. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  8832. resetCtxToDefault(this.ctx);
  8833. } else {
  8834. resetCtxToDefault(this.ctx);
  8835. this.endPath();
  8836. this.ctx.rect(rect[0], rect[1], width, height);
  8837. this.ctx.clip();
  8838. this.ctx.beginPath();
  8839. }
  8840. }
  8841. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  8842. this.transform(...transform);
  8843. this.transform(...matrix);
  8844. }
  8845. endAnnotation() {
  8846. if (this.annotationCanvas) {
  8847. this.ctx.restore();
  8848. this.#drawFilter();
  8849. this.ctx = this.annotationCanvas.savedCtx;
  8850. delete this.annotationCanvas.savedCtx;
  8851. delete this.annotationCanvas;
  8852. }
  8853. }
  8854. paintImageMaskXObject(img) {
  8855. if (!this.contentVisible) {
  8856. return;
  8857. }
  8858. const count = img.count;
  8859. img = this.getObject(img.data, img);
  8860. img.count = count;
  8861. const ctx = this.ctx;
  8862. const glyph = this.processingType3;
  8863. if (glyph) {
  8864. if (glyph.compiled === undefined) {
  8865. glyph.compiled = compileType3Glyph(img);
  8866. }
  8867. if (glyph.compiled) {
  8868. glyph.compiled(ctx);
  8869. return;
  8870. }
  8871. }
  8872. const mask = this._createMaskCanvas(img);
  8873. const maskCanvas = mask.canvas;
  8874. ctx.save();
  8875. ctx.setTransform(1, 0, 0, 1, 0, 0);
  8876. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  8877. ctx.restore();
  8878. this.compose();
  8879. }
  8880. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  8881. if (!this.contentVisible) {
  8882. return;
  8883. }
  8884. img = this.getObject(img.data, img);
  8885. const ctx = this.ctx;
  8886. ctx.save();
  8887. const currentTransform = getCurrentTransform(ctx);
  8888. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  8889. const mask = this._createMaskCanvas(img);
  8890. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  8891. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  8892. const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  8893. const [x, y] = Util.applyTransform([0, 0], trans);
  8894. ctx.drawImage(mask.canvas, x, y);
  8895. }
  8896. ctx.restore();
  8897. this.compose();
  8898. }
  8899. paintImageMaskXObjectGroup(images) {
  8900. if (!this.contentVisible) {
  8901. return;
  8902. }
  8903. const ctx = this.ctx;
  8904. const fillColor = this.current.fillColor;
  8905. const isPatternFill = this.current.patternFill;
  8906. for (const image of images) {
  8907. const {
  8908. data,
  8909. width,
  8910. height,
  8911. transform
  8912. } = image;
  8913. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  8914. const maskCtx = maskCanvas.context;
  8915. maskCtx.save();
  8916. const img = this.getObject(data, image);
  8917. putBinaryImageMask(maskCtx, img);
  8918. maskCtx.globalCompositeOperation = "source-in";
  8919. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor;
  8920. maskCtx.fillRect(0, 0, width, height);
  8921. maskCtx.restore();
  8922. ctx.save();
  8923. ctx.transform(...transform);
  8924. ctx.scale(1, -1);
  8925. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8926. ctx.restore();
  8927. }
  8928. this.compose();
  8929. }
  8930. paintImageXObject(objId) {
  8931. if (!this.contentVisible) {
  8932. return;
  8933. }
  8934. const imgData = this.getObject(objId);
  8935. if (!imgData) {
  8936. warn("Dependent image isn't ready yet");
  8937. return;
  8938. }
  8939. this.paintInlineImageXObject(imgData);
  8940. }
  8941. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  8942. if (!this.contentVisible) {
  8943. return;
  8944. }
  8945. const imgData = this.getObject(objId);
  8946. if (!imgData) {
  8947. warn("Dependent image isn't ready yet");
  8948. return;
  8949. }
  8950. const width = imgData.width;
  8951. const height = imgData.height;
  8952. const map = [];
  8953. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  8954. map.push({
  8955. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  8956. x: 0,
  8957. y: 0,
  8958. w: width,
  8959. h: height
  8960. });
  8961. }
  8962. this.paintInlineImageXObjectGroup(imgData, map);
  8963. }
  8964. applyTransferMapsToCanvas(ctx) {
  8965. if (this.current.transferMaps !== "none") {
  8966. ctx.filter = this.current.transferMaps;
  8967. ctx.drawImage(ctx.canvas, 0, 0);
  8968. ctx.filter = "none";
  8969. }
  8970. return ctx.canvas;
  8971. }
  8972. applyTransferMapsToBitmap(imgData) {
  8973. if (this.current.transferMaps === "none") {
  8974. return imgData.bitmap;
  8975. }
  8976. const {
  8977. bitmap,
  8978. width,
  8979. height
  8980. } = imgData;
  8981. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  8982. const tmpCtx = tmpCanvas.context;
  8983. tmpCtx.filter = this.current.transferMaps;
  8984. tmpCtx.drawImage(bitmap, 0, 0);
  8985. tmpCtx.filter = "none";
  8986. return tmpCanvas.canvas;
  8987. }
  8988. paintInlineImageXObject(imgData) {
  8989. if (!this.contentVisible) {
  8990. return;
  8991. }
  8992. const width = imgData.width;
  8993. const height = imgData.height;
  8994. const ctx = this.ctx;
  8995. this.save();
  8996. if (!isNodeJS) {
  8997. const {
  8998. filter
  8999. } = ctx;
  9000. if (filter !== "none" && filter !== "") {
  9001. ctx.filter = "none";
  9002. }
  9003. }
  9004. ctx.scale(1 / width, -1 / height);
  9005. let imgToPaint;
  9006. if (imgData.bitmap) {
  9007. imgToPaint = this.applyTransferMapsToBitmap(imgData);
  9008. } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  9009. imgToPaint = imgData;
  9010. } else {
  9011. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  9012. const tmpCtx = tmpCanvas.context;
  9013. putBinaryImageData(tmpCtx, imgData);
  9014. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  9015. }
  9016. const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
  9017. ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
  9018. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  9019. this.compose();
  9020. this.restore();
  9021. }
  9022. paintInlineImageXObjectGroup(imgData, map) {
  9023. if (!this.contentVisible) {
  9024. return;
  9025. }
  9026. const ctx = this.ctx;
  9027. let imgToPaint;
  9028. if (imgData.bitmap) {
  9029. imgToPaint = imgData.bitmap;
  9030. } else {
  9031. const w = imgData.width;
  9032. const h = imgData.height;
  9033. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  9034. const tmpCtx = tmpCanvas.context;
  9035. putBinaryImageData(tmpCtx, imgData);
  9036. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  9037. }
  9038. for (const entry of map) {
  9039. ctx.save();
  9040. ctx.transform(...entry.transform);
  9041. ctx.scale(1, -1);
  9042. drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  9043. ctx.restore();
  9044. }
  9045. this.compose();
  9046. }
  9047. paintSolidColorImageMask() {
  9048. if (!this.contentVisible) {
  9049. return;
  9050. }
  9051. this.ctx.fillRect(0, 0, 1, 1);
  9052. this.compose();
  9053. }
  9054. markPoint(tag) {}
  9055. markPointProps(tag, properties) {}
  9056. beginMarkedContent(tag) {
  9057. this.markedContentStack.push({
  9058. visible: true
  9059. });
  9060. }
  9061. beginMarkedContentProps(tag, properties) {
  9062. if (tag === "OC") {
  9063. this.markedContentStack.push({
  9064. visible: this.optionalContentConfig.isVisible(properties)
  9065. });
  9066. } else {
  9067. this.markedContentStack.push({
  9068. visible: true
  9069. });
  9070. }
  9071. this.contentVisible = this.isContentVisible();
  9072. }
  9073. endMarkedContent() {
  9074. this.markedContentStack.pop();
  9075. this.contentVisible = this.isContentVisible();
  9076. }
  9077. beginCompat() {}
  9078. endCompat() {}
  9079. consumePath(clipBox) {
  9080. const isEmpty = this.current.isEmptyClip();
  9081. if (this.pendingClip) {
  9082. this.current.updateClipFromPath();
  9083. }
  9084. if (!this.pendingClip) {
  9085. this.compose(clipBox);
  9086. }
  9087. const ctx = this.ctx;
  9088. if (this.pendingClip) {
  9089. if (!isEmpty) {
  9090. if (this.pendingClip === EO_CLIP) {
  9091. ctx.clip("evenodd");
  9092. } else {
  9093. ctx.clip();
  9094. }
  9095. }
  9096. this.pendingClip = null;
  9097. }
  9098. this.current.startNewPathAndClipBox(this.current.clipBox);
  9099. ctx.beginPath();
  9100. }
  9101. getSinglePixelWidth() {
  9102. if (!this._cachedGetSinglePixelWidth) {
  9103. const m = getCurrentTransform(this.ctx);
  9104. if (m[1] === 0 && m[2] === 0) {
  9105. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  9106. } else {
  9107. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  9108. const normX = Math.hypot(m[0], m[2]);
  9109. const normY = Math.hypot(m[1], m[3]);
  9110. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  9111. }
  9112. }
  9113. return this._cachedGetSinglePixelWidth;
  9114. }
  9115. getScaleForStroking() {
  9116. if (this._cachedScaleForStroking[0] === -1) {
  9117. const {
  9118. lineWidth
  9119. } = this.current;
  9120. const {
  9121. a,
  9122. b,
  9123. c,
  9124. d
  9125. } = this.ctx.getTransform();
  9126. let scaleX, scaleY;
  9127. if (b === 0 && c === 0) {
  9128. const normX = Math.abs(a);
  9129. const normY = Math.abs(d);
  9130. if (normX === normY) {
  9131. if (lineWidth === 0) {
  9132. scaleX = scaleY = 1 / normX;
  9133. } else {
  9134. const scaledLineWidth = normX * lineWidth;
  9135. scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
  9136. }
  9137. } else if (lineWidth === 0) {
  9138. scaleX = 1 / normX;
  9139. scaleY = 1 / normY;
  9140. } else {
  9141. const scaledXLineWidth = normX * lineWidth;
  9142. const scaledYLineWidth = normY * lineWidth;
  9143. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  9144. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  9145. }
  9146. } else {
  9147. const absDet = Math.abs(a * d - b * c);
  9148. const normX = Math.hypot(a, b);
  9149. const normY = Math.hypot(c, d);
  9150. if (lineWidth === 0) {
  9151. scaleX = normY / absDet;
  9152. scaleY = normX / absDet;
  9153. } else {
  9154. const baseArea = lineWidth * absDet;
  9155. scaleX = normY > baseArea ? normY / baseArea : 1;
  9156. scaleY = normX > baseArea ? normX / baseArea : 1;
  9157. }
  9158. }
  9159. this._cachedScaleForStroking[0] = scaleX;
  9160. this._cachedScaleForStroking[1] = scaleY;
  9161. }
  9162. return this._cachedScaleForStroking;
  9163. }
  9164. rescaleAndStroke(saveRestore) {
  9165. const {
  9166. ctx
  9167. } = this;
  9168. const {
  9169. lineWidth
  9170. } = this.current;
  9171. const [scaleX, scaleY] = this.getScaleForStroking();
  9172. ctx.lineWidth = lineWidth || 1;
  9173. if (scaleX === 1 && scaleY === 1) {
  9174. ctx.stroke();
  9175. return;
  9176. }
  9177. const dashes = ctx.getLineDash();
  9178. if (saveRestore) {
  9179. ctx.save();
  9180. }
  9181. ctx.scale(scaleX, scaleY);
  9182. if (dashes.length > 0) {
  9183. const scale = Math.max(scaleX, scaleY);
  9184. ctx.setLineDash(dashes.map(x => x / scale));
  9185. ctx.lineDashOffset /= scale;
  9186. }
  9187. ctx.stroke();
  9188. if (saveRestore) {
  9189. ctx.restore();
  9190. }
  9191. }
  9192. isContentVisible() {
  9193. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  9194. if (!this.markedContentStack[i].visible) {
  9195. return false;
  9196. }
  9197. }
  9198. return true;
  9199. }
  9200. }
  9201. for (const op in OPS) {
  9202. if (CanvasGraphics.prototype[op] !== undefined) {
  9203. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  9204. }
  9205. }
  9206. ;// ./src/display/worker_options.js
  9207. class GlobalWorkerOptions {
  9208. static #port = null;
  9209. static #src = "";
  9210. static get workerPort() {
  9211. return this.#port;
  9212. }
  9213. static set workerPort(val) {
  9214. if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) {
  9215. throw new Error("Invalid `workerPort` type.");
  9216. }
  9217. this.#port = val;
  9218. }
  9219. static get workerSrc() {
  9220. return this.#src;
  9221. }
  9222. static set workerSrc(val) {
  9223. if (typeof val !== "string") {
  9224. throw new Error("Invalid `workerSrc` type.");
  9225. }
  9226. this.#src = val;
  9227. }
  9228. }
  9229. ;// ./src/display/metadata.js
  9230. class Metadata {
  9231. #metadataMap;
  9232. #data;
  9233. constructor({
  9234. parsedData,
  9235. rawData
  9236. }) {
  9237. this.#metadataMap = parsedData;
  9238. this.#data = rawData;
  9239. }
  9240. getRaw() {
  9241. return this.#data;
  9242. }
  9243. get(name) {
  9244. return this.#metadataMap.get(name) ?? null;
  9245. }
  9246. getAll() {
  9247. return objectFromMap(this.#metadataMap);
  9248. }
  9249. has(name) {
  9250. return this.#metadataMap.has(name);
  9251. }
  9252. }
  9253. ;// ./src/display/optional_content_config.js
  9254. const INTERNAL = Symbol("INTERNAL");
  9255. class OptionalContentGroup {
  9256. #isDisplay = false;
  9257. #isPrint = false;
  9258. #userSet = false;
  9259. #visible = true;
  9260. constructor(renderingIntent, {
  9261. name,
  9262. intent,
  9263. usage,
  9264. rbGroups
  9265. }) {
  9266. this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
  9267. this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  9268. this.name = name;
  9269. this.intent = intent;
  9270. this.usage = usage;
  9271. this.rbGroups = rbGroups;
  9272. }
  9273. get visible() {
  9274. if (this.#userSet) {
  9275. return this.#visible;
  9276. }
  9277. if (!this.#visible) {
  9278. return false;
  9279. }
  9280. const {
  9281. print,
  9282. view
  9283. } = this.usage;
  9284. if (this.#isDisplay) {
  9285. return view?.viewState !== "OFF";
  9286. } else if (this.#isPrint) {
  9287. return print?.printState !== "OFF";
  9288. }
  9289. return true;
  9290. }
  9291. _setVisible(internal, visible, userSet = false) {
  9292. if (internal !== INTERNAL) {
  9293. unreachable("Internal method `_setVisible` called.");
  9294. }
  9295. this.#userSet = userSet;
  9296. this.#visible = visible;
  9297. }
  9298. }
  9299. class OptionalContentConfig {
  9300. #cachedGetHash = null;
  9301. #groups = new Map();
  9302. #initialHash = null;
  9303. #order = null;
  9304. constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
  9305. this.renderingIntent = renderingIntent;
  9306. this.name = null;
  9307. this.creator = null;
  9308. if (data === null) {
  9309. return;
  9310. }
  9311. this.name = data.name;
  9312. this.creator = data.creator;
  9313. this.#order = data.order;
  9314. for (const group of data.groups) {
  9315. this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
  9316. }
  9317. if (data.baseState === "OFF") {
  9318. for (const group of this.#groups.values()) {
  9319. group._setVisible(INTERNAL, false);
  9320. }
  9321. }
  9322. for (const on of data.on) {
  9323. this.#groups.get(on)._setVisible(INTERNAL, true);
  9324. }
  9325. for (const off of data.off) {
  9326. this.#groups.get(off)._setVisible(INTERNAL, false);
  9327. }
  9328. this.#initialHash = this.getHash();
  9329. }
  9330. #evaluateVisibilityExpression(array) {
  9331. const length = array.length;
  9332. if (length < 2) {
  9333. return true;
  9334. }
  9335. const operator = array[0];
  9336. for (let i = 1; i < length; i++) {
  9337. const element = array[i];
  9338. let state;
  9339. if (Array.isArray(element)) {
  9340. state = this.#evaluateVisibilityExpression(element);
  9341. } else if (this.#groups.has(element)) {
  9342. state = this.#groups.get(element).visible;
  9343. } else {
  9344. warn(`Optional content group not found: ${element}`);
  9345. return true;
  9346. }
  9347. switch (operator) {
  9348. case "And":
  9349. if (!state) {
  9350. return false;
  9351. }
  9352. break;
  9353. case "Or":
  9354. if (state) {
  9355. return true;
  9356. }
  9357. break;
  9358. case "Not":
  9359. return !state;
  9360. default:
  9361. return true;
  9362. }
  9363. }
  9364. return operator === "And";
  9365. }
  9366. isVisible(group) {
  9367. if (this.#groups.size === 0) {
  9368. return true;
  9369. }
  9370. if (!group) {
  9371. info("Optional content group not defined.");
  9372. return true;
  9373. }
  9374. if (group.type === "OCG") {
  9375. if (!this.#groups.has(group.id)) {
  9376. warn(`Optional content group not found: ${group.id}`);
  9377. return true;
  9378. }
  9379. return this.#groups.get(group.id).visible;
  9380. } else if (group.type === "OCMD") {
  9381. if (group.expression) {
  9382. return this.#evaluateVisibilityExpression(group.expression);
  9383. }
  9384. if (!group.policy || group.policy === "AnyOn") {
  9385. for (const id of group.ids) {
  9386. if (!this.#groups.has(id)) {
  9387. warn(`Optional content group not found: ${id}`);
  9388. return true;
  9389. }
  9390. if (this.#groups.get(id).visible) {
  9391. return true;
  9392. }
  9393. }
  9394. return false;
  9395. } else if (group.policy === "AllOn") {
  9396. for (const id of group.ids) {
  9397. if (!this.#groups.has(id)) {
  9398. warn(`Optional content group not found: ${id}`);
  9399. return true;
  9400. }
  9401. if (!this.#groups.get(id).visible) {
  9402. return false;
  9403. }
  9404. }
  9405. return true;
  9406. } else if (group.policy === "AnyOff") {
  9407. for (const id of group.ids) {
  9408. if (!this.#groups.has(id)) {
  9409. warn(`Optional content group not found: ${id}`);
  9410. return true;
  9411. }
  9412. if (!this.#groups.get(id).visible) {
  9413. return true;
  9414. }
  9415. }
  9416. return false;
  9417. } else if (group.policy === "AllOff") {
  9418. for (const id of group.ids) {
  9419. if (!this.#groups.has(id)) {
  9420. warn(`Optional content group not found: ${id}`);
  9421. return true;
  9422. }
  9423. if (this.#groups.get(id).visible) {
  9424. return false;
  9425. }
  9426. }
  9427. return true;
  9428. }
  9429. warn(`Unknown optional content policy ${group.policy}.`);
  9430. return true;
  9431. }
  9432. warn(`Unknown group type ${group.type}.`);
  9433. return true;
  9434. }
  9435. setVisibility(id, visible = true, preserveRB = true) {
  9436. const group = this.#groups.get(id);
  9437. if (!group) {
  9438. warn(`Optional content group not found: ${id}`);
  9439. return;
  9440. }
  9441. if (preserveRB && visible && group.rbGroups.length) {
  9442. for (const rbGroup of group.rbGroups) {
  9443. for (const otherId of rbGroup) {
  9444. if (otherId !== id) {
  9445. this.#groups.get(otherId)?._setVisible(INTERNAL, false, true);
  9446. }
  9447. }
  9448. }
  9449. }
  9450. group._setVisible(INTERNAL, !!visible, true);
  9451. this.#cachedGetHash = null;
  9452. }
  9453. setOCGState({
  9454. state,
  9455. preserveRB
  9456. }) {
  9457. let operator;
  9458. for (const elem of state) {
  9459. switch (elem) {
  9460. case "ON":
  9461. case "OFF":
  9462. case "Toggle":
  9463. operator = elem;
  9464. continue;
  9465. }
  9466. const group = this.#groups.get(elem);
  9467. if (!group) {
  9468. continue;
  9469. }
  9470. switch (operator) {
  9471. case "ON":
  9472. this.setVisibility(elem, true, preserveRB);
  9473. break;
  9474. case "OFF":
  9475. this.setVisibility(elem, false, preserveRB);
  9476. break;
  9477. case "Toggle":
  9478. this.setVisibility(elem, !group.visible, preserveRB);
  9479. break;
  9480. }
  9481. }
  9482. this.#cachedGetHash = null;
  9483. }
  9484. get hasInitialVisibility() {
  9485. return this.#initialHash === null || this.getHash() === this.#initialHash;
  9486. }
  9487. getOrder() {
  9488. if (!this.#groups.size) {
  9489. return null;
  9490. }
  9491. if (this.#order) {
  9492. return this.#order.slice();
  9493. }
  9494. return [...this.#groups.keys()];
  9495. }
  9496. getGroups() {
  9497. return this.#groups.size > 0 ? objectFromMap(this.#groups) : null;
  9498. }
  9499. getGroup(id) {
  9500. return this.#groups.get(id) || null;
  9501. }
  9502. getHash() {
  9503. if (this.#cachedGetHash !== null) {
  9504. return this.#cachedGetHash;
  9505. }
  9506. const hash = new MurmurHash3_64();
  9507. for (const [id, group] of this.#groups) {
  9508. hash.update(`${id}:${group.visible}`);
  9509. }
  9510. return this.#cachedGetHash = hash.hexdigest();
  9511. }
  9512. }
  9513. ;// ./src/display/transport_stream.js
  9514. class PDFDataTransportStream {
  9515. constructor(pdfDataRangeTransport, {
  9516. disableRange = false,
  9517. disableStream = false
  9518. }) {
  9519. assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  9520. const {
  9521. length,
  9522. initialData,
  9523. progressiveDone,
  9524. contentDispositionFilename
  9525. } = pdfDataRangeTransport;
  9526. this._queuedChunks = [];
  9527. this._progressiveDone = progressiveDone;
  9528. this._contentDispositionFilename = contentDispositionFilename;
  9529. if (initialData?.length > 0) {
  9530. const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
  9531. this._queuedChunks.push(buffer);
  9532. }
  9533. this._pdfDataRangeTransport = pdfDataRangeTransport;
  9534. this._isStreamingSupported = !disableStream;
  9535. this._isRangeSupported = !disableRange;
  9536. this._contentLength = length;
  9537. this._fullRequestReader = null;
  9538. this._rangeReaders = [];
  9539. pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  9540. this._onReceiveData({
  9541. begin,
  9542. chunk
  9543. });
  9544. });
  9545. pdfDataRangeTransport.addProgressListener((loaded, total) => {
  9546. this._onProgress({
  9547. loaded,
  9548. total
  9549. });
  9550. });
  9551. pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  9552. this._onReceiveData({
  9553. chunk
  9554. });
  9555. });
  9556. pdfDataRangeTransport.addProgressiveDoneListener(() => {
  9557. this._onProgressiveDone();
  9558. });
  9559. pdfDataRangeTransport.transportReady();
  9560. }
  9561. _onReceiveData({
  9562. begin,
  9563. chunk
  9564. }) {
  9565. const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
  9566. if (begin === undefined) {
  9567. if (this._fullRequestReader) {
  9568. this._fullRequestReader._enqueue(buffer);
  9569. } else {
  9570. this._queuedChunks.push(buffer);
  9571. }
  9572. } else {
  9573. const found = this._rangeReaders.some(function (rangeReader) {
  9574. if (rangeReader._begin !== begin) {
  9575. return false;
  9576. }
  9577. rangeReader._enqueue(buffer);
  9578. return true;
  9579. });
  9580. assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  9581. }
  9582. }
  9583. get _progressiveDataLength() {
  9584. return this._fullRequestReader?._loaded ?? 0;
  9585. }
  9586. _onProgress(evt) {
  9587. if (evt.total === undefined) {
  9588. this._rangeReaders[0]?.onProgress?.({
  9589. loaded: evt.loaded
  9590. });
  9591. } else {
  9592. this._fullRequestReader?.onProgress?.({
  9593. loaded: evt.loaded,
  9594. total: evt.total
  9595. });
  9596. }
  9597. }
  9598. _onProgressiveDone() {
  9599. this._fullRequestReader?.progressiveDone();
  9600. this._progressiveDone = true;
  9601. }
  9602. _removeRangeReader(reader) {
  9603. const i = this._rangeReaders.indexOf(reader);
  9604. if (i >= 0) {
  9605. this._rangeReaders.splice(i, 1);
  9606. }
  9607. }
  9608. getFullReader() {
  9609. assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  9610. const queuedChunks = this._queuedChunks;
  9611. this._queuedChunks = null;
  9612. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  9613. }
  9614. getRangeReader(begin, end) {
  9615. if (end <= this._progressiveDataLength) {
  9616. return null;
  9617. }
  9618. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  9619. this._pdfDataRangeTransport.requestDataRange(begin, end);
  9620. this._rangeReaders.push(reader);
  9621. return reader;
  9622. }
  9623. cancelAllRequests(reason) {
  9624. this._fullRequestReader?.cancel(reason);
  9625. for (const reader of this._rangeReaders.slice(0)) {
  9626. reader.cancel(reason);
  9627. }
  9628. this._pdfDataRangeTransport.abort();
  9629. }
  9630. }
  9631. class PDFDataTransportStreamReader {
  9632. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  9633. this._stream = stream;
  9634. this._done = progressiveDone || false;
  9635. this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
  9636. this._queuedChunks = queuedChunks || [];
  9637. this._loaded = 0;
  9638. for (const chunk of this._queuedChunks) {
  9639. this._loaded += chunk.byteLength;
  9640. }
  9641. this._requests = [];
  9642. this._headersReady = Promise.resolve();
  9643. stream._fullRequestReader = this;
  9644. this.onProgress = null;
  9645. }
  9646. _enqueue(chunk) {
  9647. if (this._done) {
  9648. return;
  9649. }
  9650. if (this._requests.length > 0) {
  9651. const requestCapability = this._requests.shift();
  9652. requestCapability.resolve({
  9653. value: chunk,
  9654. done: false
  9655. });
  9656. } else {
  9657. this._queuedChunks.push(chunk);
  9658. }
  9659. this._loaded += chunk.byteLength;
  9660. }
  9661. get headersReady() {
  9662. return this._headersReady;
  9663. }
  9664. get filename() {
  9665. return this._filename;
  9666. }
  9667. get isRangeSupported() {
  9668. return this._stream._isRangeSupported;
  9669. }
  9670. get isStreamingSupported() {
  9671. return this._stream._isStreamingSupported;
  9672. }
  9673. get contentLength() {
  9674. return this._stream._contentLength;
  9675. }
  9676. async read() {
  9677. if (this._queuedChunks.length > 0) {
  9678. const chunk = this._queuedChunks.shift();
  9679. return {
  9680. value: chunk,
  9681. done: false
  9682. };
  9683. }
  9684. if (this._done) {
  9685. return {
  9686. value: undefined,
  9687. done: true
  9688. };
  9689. }
  9690. const requestCapability = Promise.withResolvers();
  9691. this._requests.push(requestCapability);
  9692. return requestCapability.promise;
  9693. }
  9694. cancel(reason) {
  9695. this._done = true;
  9696. for (const requestCapability of this._requests) {
  9697. requestCapability.resolve({
  9698. value: undefined,
  9699. done: true
  9700. });
  9701. }
  9702. this._requests.length = 0;
  9703. }
  9704. progressiveDone() {
  9705. if (this._done) {
  9706. return;
  9707. }
  9708. this._done = true;
  9709. }
  9710. }
  9711. class PDFDataTransportStreamRangeReader {
  9712. constructor(stream, begin, end) {
  9713. this._stream = stream;
  9714. this._begin = begin;
  9715. this._end = end;
  9716. this._queuedChunk = null;
  9717. this._requests = [];
  9718. this._done = false;
  9719. this.onProgress = null;
  9720. }
  9721. _enqueue(chunk) {
  9722. if (this._done) {
  9723. return;
  9724. }
  9725. if (this._requests.length === 0) {
  9726. this._queuedChunk = chunk;
  9727. } else {
  9728. const requestsCapability = this._requests.shift();
  9729. requestsCapability.resolve({
  9730. value: chunk,
  9731. done: false
  9732. });
  9733. for (const requestCapability of this._requests) {
  9734. requestCapability.resolve({
  9735. value: undefined,
  9736. done: true
  9737. });
  9738. }
  9739. this._requests.length = 0;
  9740. }
  9741. this._done = true;
  9742. this._stream._removeRangeReader(this);
  9743. }
  9744. get isStreamingSupported() {
  9745. return false;
  9746. }
  9747. async read() {
  9748. if (this._queuedChunk) {
  9749. const chunk = this._queuedChunk;
  9750. this._queuedChunk = null;
  9751. return {
  9752. value: chunk,
  9753. done: false
  9754. };
  9755. }
  9756. if (this._done) {
  9757. return {
  9758. value: undefined,
  9759. done: true
  9760. };
  9761. }
  9762. const requestCapability = Promise.withResolvers();
  9763. this._requests.push(requestCapability);
  9764. return requestCapability.promise;
  9765. }
  9766. cancel(reason) {
  9767. this._done = true;
  9768. for (const requestCapability of this._requests) {
  9769. requestCapability.resolve({
  9770. value: undefined,
  9771. done: true
  9772. });
  9773. }
  9774. this._requests.length = 0;
  9775. this._stream._removeRangeReader(this);
  9776. }
  9777. }
  9778. ;// ./src/display/content_disposition.js
  9779. function getFilenameFromContentDispositionHeader(contentDisposition) {
  9780. let needsEncodingFixup = true;
  9781. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  9782. if (tmp) {
  9783. tmp = tmp[1];
  9784. let filename = rfc2616unquote(tmp);
  9785. filename = unescape(filename);
  9786. filename = rfc5987decode(filename);
  9787. filename = rfc2047decode(filename);
  9788. return fixupEncoding(filename);
  9789. }
  9790. tmp = rfc2231getparam(contentDisposition);
  9791. if (tmp) {
  9792. const filename = rfc2047decode(tmp);
  9793. return fixupEncoding(filename);
  9794. }
  9795. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  9796. if (tmp) {
  9797. tmp = tmp[1];
  9798. let filename = rfc2616unquote(tmp);
  9799. filename = rfc2047decode(filename);
  9800. return fixupEncoding(filename);
  9801. }
  9802. function toParamRegExp(attributePattern, flags) {
  9803. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  9804. }
  9805. function textdecode(encoding, value) {
  9806. if (encoding) {
  9807. if (!/^[\x00-\xFF]+$/.test(value)) {
  9808. return value;
  9809. }
  9810. try {
  9811. const decoder = new TextDecoder(encoding, {
  9812. fatal: true
  9813. });
  9814. const buffer = stringToBytes(value);
  9815. value = decoder.decode(buffer);
  9816. needsEncodingFixup = false;
  9817. } catch {}
  9818. }
  9819. return value;
  9820. }
  9821. function fixupEncoding(value) {
  9822. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  9823. value = textdecode("utf-8", value);
  9824. if (needsEncodingFixup) {
  9825. value = textdecode("iso-8859-1", value);
  9826. }
  9827. }
  9828. return value;
  9829. }
  9830. function rfc2231getparam(contentDispositionStr) {
  9831. const matches = [];
  9832. let match;
  9833. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  9834. while ((match = iter.exec(contentDispositionStr)) !== null) {
  9835. let [, n, quot, part] = match;
  9836. n = parseInt(n, 10);
  9837. if (n in matches) {
  9838. if (n === 0) {
  9839. break;
  9840. }
  9841. continue;
  9842. }
  9843. matches[n] = [quot, part];
  9844. }
  9845. const parts = [];
  9846. for (let n = 0; n < matches.length; ++n) {
  9847. if (!(n in matches)) {
  9848. break;
  9849. }
  9850. let [quot, part] = matches[n];
  9851. part = rfc2616unquote(part);
  9852. if (quot) {
  9853. part = unescape(part);
  9854. if (n === 0) {
  9855. part = rfc5987decode(part);
  9856. }
  9857. }
  9858. parts.push(part);
  9859. }
  9860. return parts.join("");
  9861. }
  9862. function rfc2616unquote(value) {
  9863. if (value.startsWith('"')) {
  9864. const parts = value.slice(1).split('\\"');
  9865. for (let i = 0; i < parts.length; ++i) {
  9866. const quotindex = parts[i].indexOf('"');
  9867. if (quotindex !== -1) {
  9868. parts[i] = parts[i].slice(0, quotindex);
  9869. parts.length = i + 1;
  9870. }
  9871. parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
  9872. }
  9873. value = parts.join('"');
  9874. }
  9875. return value;
  9876. }
  9877. function rfc5987decode(extvalue) {
  9878. const encodingend = extvalue.indexOf("'");
  9879. if (encodingend === -1) {
  9880. return extvalue;
  9881. }
  9882. const encoding = extvalue.slice(0, encodingend);
  9883. const langvalue = extvalue.slice(encodingend + 1);
  9884. const value = langvalue.replace(/^[^']*'/, "");
  9885. return textdecode(encoding, value);
  9886. }
  9887. function rfc2047decode(value) {
  9888. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  9889. return value;
  9890. }
  9891. return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  9892. if (encoding === "q" || encoding === "Q") {
  9893. text = text.replaceAll("_", " ");
  9894. text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  9895. return String.fromCharCode(parseInt(hex, 16));
  9896. });
  9897. return textdecode(charset, text);
  9898. }
  9899. try {
  9900. text = atob(text);
  9901. } catch {}
  9902. return textdecode(charset, text);
  9903. });
  9904. }
  9905. return "";
  9906. }
  9907. ;// ./src/display/network_utils.js
  9908. function createHeaders(isHttp, httpHeaders) {
  9909. const headers = new Headers();
  9910. if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {
  9911. return headers;
  9912. }
  9913. for (const key in httpHeaders) {
  9914. const val = httpHeaders[key];
  9915. if (val !== undefined) {
  9916. headers.append(key, val);
  9917. }
  9918. }
  9919. return headers;
  9920. }
  9921. function getResponseOrigin(url) {
  9922. try {
  9923. return new URL(url).origin;
  9924. } catch {}
  9925. return null;
  9926. }
  9927. function validateRangeRequestCapabilities({
  9928. responseHeaders,
  9929. isHttp,
  9930. rangeChunkSize,
  9931. disableRange
  9932. }) {
  9933. const returnValues = {
  9934. allowRangeRequests: false,
  9935. suggestedLength: undefined
  9936. };
  9937. const length = parseInt(responseHeaders.get("Content-Length"), 10);
  9938. if (!Number.isInteger(length)) {
  9939. return returnValues;
  9940. }
  9941. returnValues.suggestedLength = length;
  9942. if (length <= 2 * rangeChunkSize) {
  9943. return returnValues;
  9944. }
  9945. if (disableRange || !isHttp) {
  9946. return returnValues;
  9947. }
  9948. if (responseHeaders.get("Accept-Ranges") !== "bytes") {
  9949. return returnValues;
  9950. }
  9951. const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";
  9952. if (contentEncoding !== "identity") {
  9953. return returnValues;
  9954. }
  9955. returnValues.allowRangeRequests = true;
  9956. return returnValues;
  9957. }
  9958. function extractFilenameFromHeader(responseHeaders) {
  9959. const contentDisposition = responseHeaders.get("Content-Disposition");
  9960. if (contentDisposition) {
  9961. let filename = getFilenameFromContentDispositionHeader(contentDisposition);
  9962. if (filename.includes("%")) {
  9963. try {
  9964. filename = decodeURIComponent(filename);
  9965. } catch {}
  9966. }
  9967. if (isPdfFile(filename)) {
  9968. return filename;
  9969. }
  9970. }
  9971. return null;
  9972. }
  9973. function createResponseStatusError(status, url) {
  9974. if (status === 404 || status === 0 && url.startsWith("file:")) {
  9975. return new MissingPDFException('Missing PDF "' + url + '".');
  9976. }
  9977. return new UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  9978. }
  9979. function validateResponseStatus(status) {
  9980. return status === 200 || status === 206;
  9981. }
  9982. ;// ./src/display/fetch_stream.js
  9983. function createFetchOptions(headers, withCredentials, abortController) {
  9984. return {
  9985. method: "GET",
  9986. headers,
  9987. signal: abortController.signal,
  9988. mode: "cors",
  9989. credentials: withCredentials ? "include" : "same-origin",
  9990. redirect: "follow"
  9991. };
  9992. }
  9993. function getArrayBuffer(val) {
  9994. if (val instanceof Uint8Array) {
  9995. return val.buffer;
  9996. }
  9997. if (val instanceof ArrayBuffer) {
  9998. return val;
  9999. }
  10000. warn(`getArrayBuffer - unexpected data format: ${val}`);
  10001. return new Uint8Array(val).buffer;
  10002. }
  10003. class PDFFetchStream {
  10004. _responseOrigin = null;
  10005. constructor(source) {
  10006. this.source = source;
  10007. this.isHttp = /^https?:/i.test(source.url);
  10008. this.headers = createHeaders(this.isHttp, source.httpHeaders);
  10009. this._fullRequestReader = null;
  10010. this._rangeRequestReaders = [];
  10011. }
  10012. get _progressiveDataLength() {
  10013. return this._fullRequestReader?._loaded ?? 0;
  10014. }
  10015. getFullReader() {
  10016. assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  10017. this._fullRequestReader = new PDFFetchStreamReader(this);
  10018. return this._fullRequestReader;
  10019. }
  10020. getRangeReader(begin, end) {
  10021. if (end <= this._progressiveDataLength) {
  10022. return null;
  10023. }
  10024. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  10025. this._rangeRequestReaders.push(reader);
  10026. return reader;
  10027. }
  10028. cancelAllRequests(reason) {
  10029. this._fullRequestReader?.cancel(reason);
  10030. for (const reader of this._rangeRequestReaders.slice(0)) {
  10031. reader.cancel(reason);
  10032. }
  10033. }
  10034. }
  10035. class PDFFetchStreamReader {
  10036. constructor(stream) {
  10037. this._stream = stream;
  10038. this._reader = null;
  10039. this._loaded = 0;
  10040. this._filename = null;
  10041. const source = stream.source;
  10042. this._withCredentials = source.withCredentials || false;
  10043. this._contentLength = source.length;
  10044. this._headersCapability = Promise.withResolvers();
  10045. this._disableRange = source.disableRange || false;
  10046. this._rangeChunkSize = source.rangeChunkSize;
  10047. if (!this._rangeChunkSize && !this._disableRange) {
  10048. this._disableRange = true;
  10049. }
  10050. this._abortController = new AbortController();
  10051. this._isStreamingSupported = !source.disableStream;
  10052. this._isRangeSupported = !source.disableRange;
  10053. const headers = new Headers(stream.headers);
  10054. const url = source.url;
  10055. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  10056. stream._responseOrigin = getResponseOrigin(response.url);
  10057. if (!validateResponseStatus(response.status)) {
  10058. throw createResponseStatusError(response.status, url);
  10059. }
  10060. this._reader = response.body.getReader();
  10061. this._headersCapability.resolve();
  10062. const responseHeaders = response.headers;
  10063. const {
  10064. allowRangeRequests,
  10065. suggestedLength
  10066. } = validateRangeRequestCapabilities({
  10067. responseHeaders,
  10068. isHttp: stream.isHttp,
  10069. rangeChunkSize: this._rangeChunkSize,
  10070. disableRange: this._disableRange
  10071. });
  10072. this._isRangeSupported = allowRangeRequests;
  10073. this._contentLength = suggestedLength || this._contentLength;
  10074. this._filename = extractFilenameFromHeader(responseHeaders);
  10075. if (!this._isStreamingSupported && this._isRangeSupported) {
  10076. this.cancel(new AbortException("Streaming is disabled."));
  10077. }
  10078. }).catch(this._headersCapability.reject);
  10079. this.onProgress = null;
  10080. }
  10081. get headersReady() {
  10082. return this._headersCapability.promise;
  10083. }
  10084. get filename() {
  10085. return this._filename;
  10086. }
  10087. get contentLength() {
  10088. return this._contentLength;
  10089. }
  10090. get isRangeSupported() {
  10091. return this._isRangeSupported;
  10092. }
  10093. get isStreamingSupported() {
  10094. return this._isStreamingSupported;
  10095. }
  10096. async read() {
  10097. await this._headersCapability.promise;
  10098. const {
  10099. value,
  10100. done
  10101. } = await this._reader.read();
  10102. if (done) {
  10103. return {
  10104. value,
  10105. done
  10106. };
  10107. }
  10108. this._loaded += value.byteLength;
  10109. this.onProgress?.({
  10110. loaded: this._loaded,
  10111. total: this._contentLength
  10112. });
  10113. return {
  10114. value: getArrayBuffer(value),
  10115. done: false
  10116. };
  10117. }
  10118. cancel(reason) {
  10119. this._reader?.cancel(reason);
  10120. this._abortController.abort();
  10121. }
  10122. }
  10123. class PDFFetchStreamRangeReader {
  10124. constructor(stream, begin, end) {
  10125. this._stream = stream;
  10126. this._reader = null;
  10127. this._loaded = 0;
  10128. const source = stream.source;
  10129. this._withCredentials = source.withCredentials || false;
  10130. this._readCapability = Promise.withResolvers();
  10131. this._isStreamingSupported = !source.disableStream;
  10132. this._abortController = new AbortController();
  10133. const headers = new Headers(stream.headers);
  10134. headers.append("Range", `bytes=${begin}-${end - 1}`);
  10135. const url = source.url;
  10136. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  10137. const responseOrigin = getResponseOrigin(response.url);
  10138. if (responseOrigin !== stream._responseOrigin) {
  10139. throw new Error(`Expected range response-origin "${responseOrigin}" to match "${stream._responseOrigin}".`);
  10140. }
  10141. if (!validateResponseStatus(response.status)) {
  10142. throw createResponseStatusError(response.status, url);
  10143. }
  10144. this._readCapability.resolve();
  10145. this._reader = response.body.getReader();
  10146. }).catch(this._readCapability.reject);
  10147. this.onProgress = null;
  10148. }
  10149. get isStreamingSupported() {
  10150. return this._isStreamingSupported;
  10151. }
  10152. async read() {
  10153. await this._readCapability.promise;
  10154. const {
  10155. value,
  10156. done
  10157. } = await this._reader.read();
  10158. if (done) {
  10159. return {
  10160. value,
  10161. done
  10162. };
  10163. }
  10164. this._loaded += value.byteLength;
  10165. this.onProgress?.({
  10166. loaded: this._loaded
  10167. });
  10168. return {
  10169. value: getArrayBuffer(value),
  10170. done: false
  10171. };
  10172. }
  10173. cancel(reason) {
  10174. this._reader?.cancel(reason);
  10175. this._abortController.abort();
  10176. }
  10177. }
  10178. ;// ./src/display/network.js
  10179. const OK_RESPONSE = 200;
  10180. const PARTIAL_CONTENT_RESPONSE = 206;
  10181. function network_getArrayBuffer(xhr) {
  10182. const data = xhr.response;
  10183. if (typeof data !== "string") {
  10184. return data;
  10185. }
  10186. return stringToBytes(data).buffer;
  10187. }
  10188. class NetworkManager {
  10189. _responseOrigin = null;
  10190. constructor({
  10191. url,
  10192. httpHeaders,
  10193. withCredentials
  10194. }) {
  10195. this.url = url;
  10196. this.isHttp = /^https?:/i.test(url);
  10197. this.headers = createHeaders(this.isHttp, httpHeaders);
  10198. this.withCredentials = withCredentials || false;
  10199. this.currXhrId = 0;
  10200. this.pendingRequests = Object.create(null);
  10201. }
  10202. request(args) {
  10203. const xhr = new XMLHttpRequest();
  10204. const xhrId = this.currXhrId++;
  10205. const pendingRequest = this.pendingRequests[xhrId] = {
  10206. xhr
  10207. };
  10208. xhr.open("GET", this.url);
  10209. xhr.withCredentials = this.withCredentials;
  10210. for (const [key, val] of this.headers) {
  10211. xhr.setRequestHeader(key, val);
  10212. }
  10213. if (this.isHttp && "begin" in args && "end" in args) {
  10214. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  10215. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  10216. } else {
  10217. pendingRequest.expectedStatus = OK_RESPONSE;
  10218. }
  10219. xhr.responseType = "arraybuffer";
  10220. assert(args.onError, "Expected `onError` callback to be provided.");
  10221. xhr.onerror = () => {
  10222. args.onError(xhr.status);
  10223. };
  10224. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  10225. xhr.onprogress = this.onProgress.bind(this, xhrId);
  10226. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  10227. pendingRequest.onDone = args.onDone;
  10228. pendingRequest.onError = args.onError;
  10229. pendingRequest.onProgress = args.onProgress;
  10230. xhr.send(null);
  10231. return xhrId;
  10232. }
  10233. onProgress(xhrId, evt) {
  10234. const pendingRequest = this.pendingRequests[xhrId];
  10235. if (!pendingRequest) {
  10236. return;
  10237. }
  10238. pendingRequest.onProgress?.(evt);
  10239. }
  10240. onStateChange(xhrId, evt) {
  10241. const pendingRequest = this.pendingRequests[xhrId];
  10242. if (!pendingRequest) {
  10243. return;
  10244. }
  10245. const xhr = pendingRequest.xhr;
  10246. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  10247. pendingRequest.onHeadersReceived();
  10248. delete pendingRequest.onHeadersReceived;
  10249. }
  10250. if (xhr.readyState !== 4) {
  10251. return;
  10252. }
  10253. if (!(xhrId in this.pendingRequests)) {
  10254. return;
  10255. }
  10256. delete this.pendingRequests[xhrId];
  10257. if (xhr.status === 0 && this.isHttp) {
  10258. pendingRequest.onError(xhr.status);
  10259. return;
  10260. }
  10261. const xhrStatus = xhr.status || OK_RESPONSE;
  10262. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  10263. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  10264. pendingRequest.onError(xhr.status);
  10265. return;
  10266. }
  10267. const chunk = network_getArrayBuffer(xhr);
  10268. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  10269. const rangeHeader = xhr.getResponseHeader("Content-Range");
  10270. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  10271. if (matches) {
  10272. pendingRequest.onDone({
  10273. begin: parseInt(matches[1], 10),
  10274. chunk
  10275. });
  10276. } else {
  10277. warn(`Missing or invalid "Content-Range" header.`);
  10278. pendingRequest.onError(0);
  10279. }
  10280. } else if (chunk) {
  10281. pendingRequest.onDone({
  10282. begin: 0,
  10283. chunk
  10284. });
  10285. } else {
  10286. pendingRequest.onError(xhr.status);
  10287. }
  10288. }
  10289. getRequestXhr(xhrId) {
  10290. return this.pendingRequests[xhrId].xhr;
  10291. }
  10292. isPendingRequest(xhrId) {
  10293. return xhrId in this.pendingRequests;
  10294. }
  10295. abortRequest(xhrId) {
  10296. const xhr = this.pendingRequests[xhrId].xhr;
  10297. delete this.pendingRequests[xhrId];
  10298. xhr.abort();
  10299. }
  10300. }
  10301. class PDFNetworkStream {
  10302. constructor(source) {
  10303. this._source = source;
  10304. this._manager = new NetworkManager(source);
  10305. this._rangeChunkSize = source.rangeChunkSize;
  10306. this._fullRequestReader = null;
  10307. this._rangeRequestReaders = [];
  10308. }
  10309. _onRangeRequestReaderClosed(reader) {
  10310. const i = this._rangeRequestReaders.indexOf(reader);
  10311. if (i >= 0) {
  10312. this._rangeRequestReaders.splice(i, 1);
  10313. }
  10314. }
  10315. getFullReader() {
  10316. assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  10317. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  10318. return this._fullRequestReader;
  10319. }
  10320. getRangeReader(begin, end) {
  10321. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  10322. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  10323. this._rangeRequestReaders.push(reader);
  10324. return reader;
  10325. }
  10326. cancelAllRequests(reason) {
  10327. this._fullRequestReader?.cancel(reason);
  10328. for (const reader of this._rangeRequestReaders.slice(0)) {
  10329. reader.cancel(reason);
  10330. }
  10331. }
  10332. }
  10333. class PDFNetworkStreamFullRequestReader {
  10334. constructor(manager, source) {
  10335. this._manager = manager;
  10336. this._url = source.url;
  10337. this._fullRequestId = manager.request({
  10338. onHeadersReceived: this._onHeadersReceived.bind(this),
  10339. onDone: this._onDone.bind(this),
  10340. onError: this._onError.bind(this),
  10341. onProgress: this._onProgress.bind(this)
  10342. });
  10343. this._headersCapability = Promise.withResolvers();
  10344. this._disableRange = source.disableRange || false;
  10345. this._contentLength = source.length;
  10346. this._rangeChunkSize = source.rangeChunkSize;
  10347. if (!this._rangeChunkSize && !this._disableRange) {
  10348. this._disableRange = true;
  10349. }
  10350. this._isStreamingSupported = false;
  10351. this._isRangeSupported = false;
  10352. this._cachedChunks = [];
  10353. this._requests = [];
  10354. this._done = false;
  10355. this._storedError = undefined;
  10356. this._filename = null;
  10357. this.onProgress = null;
  10358. }
  10359. _onHeadersReceived() {
  10360. const fullRequestXhrId = this._fullRequestId;
  10361. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  10362. this._manager._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL);
  10363. const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders();
  10364. const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\S ]+$/, "").split(/[\r\n]+/).map(x => {
  10365. const [key, ...val] = x.split(": ");
  10366. return [key, val.join(": ")];
  10367. }) : []);
  10368. const {
  10369. allowRangeRequests,
  10370. suggestedLength
  10371. } = validateRangeRequestCapabilities({
  10372. responseHeaders,
  10373. isHttp: this._manager.isHttp,
  10374. rangeChunkSize: this._rangeChunkSize,
  10375. disableRange: this._disableRange
  10376. });
  10377. if (allowRangeRequests) {
  10378. this._isRangeSupported = true;
  10379. }
  10380. this._contentLength = suggestedLength || this._contentLength;
  10381. this._filename = extractFilenameFromHeader(responseHeaders);
  10382. if (this._isRangeSupported) {
  10383. this._manager.abortRequest(fullRequestXhrId);
  10384. }
  10385. this._headersCapability.resolve();
  10386. }
  10387. _onDone(data) {
  10388. if (data) {
  10389. if (this._requests.length > 0) {
  10390. const requestCapability = this._requests.shift();
  10391. requestCapability.resolve({
  10392. value: data.chunk,
  10393. done: false
  10394. });
  10395. } else {
  10396. this._cachedChunks.push(data.chunk);
  10397. }
  10398. }
  10399. this._done = true;
  10400. if (this._cachedChunks.length > 0) {
  10401. return;
  10402. }
  10403. for (const requestCapability of this._requests) {
  10404. requestCapability.resolve({
  10405. value: undefined,
  10406. done: true
  10407. });
  10408. }
  10409. this._requests.length = 0;
  10410. }
  10411. _onError(status) {
  10412. this._storedError = createResponseStatusError(status, this._url);
  10413. this._headersCapability.reject(this._storedError);
  10414. for (const requestCapability of this._requests) {
  10415. requestCapability.reject(this._storedError);
  10416. }
  10417. this._requests.length = 0;
  10418. this._cachedChunks.length = 0;
  10419. }
  10420. _onProgress(evt) {
  10421. this.onProgress?.({
  10422. loaded: evt.loaded,
  10423. total: evt.lengthComputable ? evt.total : this._contentLength
  10424. });
  10425. }
  10426. get filename() {
  10427. return this._filename;
  10428. }
  10429. get isRangeSupported() {
  10430. return this._isRangeSupported;
  10431. }
  10432. get isStreamingSupported() {
  10433. return this._isStreamingSupported;
  10434. }
  10435. get contentLength() {
  10436. return this._contentLength;
  10437. }
  10438. get headersReady() {
  10439. return this._headersCapability.promise;
  10440. }
  10441. async read() {
  10442. await this._headersCapability.promise;
  10443. if (this._storedError) {
  10444. throw this._storedError;
  10445. }
  10446. if (this._cachedChunks.length > 0) {
  10447. const chunk = this._cachedChunks.shift();
  10448. return {
  10449. value: chunk,
  10450. done: false
  10451. };
  10452. }
  10453. if (this._done) {
  10454. return {
  10455. value: undefined,
  10456. done: true
  10457. };
  10458. }
  10459. const requestCapability = Promise.withResolvers();
  10460. this._requests.push(requestCapability);
  10461. return requestCapability.promise;
  10462. }
  10463. cancel(reason) {
  10464. this._done = true;
  10465. this._headersCapability.reject(reason);
  10466. for (const requestCapability of this._requests) {
  10467. requestCapability.resolve({
  10468. value: undefined,
  10469. done: true
  10470. });
  10471. }
  10472. this._requests.length = 0;
  10473. if (this._manager.isPendingRequest(this._fullRequestId)) {
  10474. this._manager.abortRequest(this._fullRequestId);
  10475. }
  10476. this._fullRequestReader = null;
  10477. }
  10478. }
  10479. class PDFNetworkStreamRangeRequestReader {
  10480. constructor(manager, begin, end) {
  10481. this._manager = manager;
  10482. this._url = manager.url;
  10483. this._requestId = manager.request({
  10484. begin,
  10485. end,
  10486. onHeadersReceived: this._onHeadersReceived.bind(this),
  10487. onDone: this._onDone.bind(this),
  10488. onError: this._onError.bind(this),
  10489. onProgress: this._onProgress.bind(this)
  10490. });
  10491. this._requests = [];
  10492. this._queuedChunk = null;
  10493. this._done = false;
  10494. this._storedError = undefined;
  10495. this.onProgress = null;
  10496. this.onClosed = null;
  10497. }
  10498. _onHeadersReceived() {
  10499. const responseOrigin = getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);
  10500. if (responseOrigin !== this._manager._responseOrigin) {
  10501. this._storedError = new Error(`Expected range response-origin "${responseOrigin}" to match "${this._manager._responseOrigin}".`);
  10502. this._onError(0);
  10503. }
  10504. }
  10505. _close() {
  10506. this.onClosed?.(this);
  10507. }
  10508. _onDone(data) {
  10509. const chunk = data.chunk;
  10510. if (this._requests.length > 0) {
  10511. const requestCapability = this._requests.shift();
  10512. requestCapability.resolve({
  10513. value: chunk,
  10514. done: false
  10515. });
  10516. } else {
  10517. this._queuedChunk = chunk;
  10518. }
  10519. this._done = true;
  10520. for (const requestCapability of this._requests) {
  10521. requestCapability.resolve({
  10522. value: undefined,
  10523. done: true
  10524. });
  10525. }
  10526. this._requests.length = 0;
  10527. this._close();
  10528. }
  10529. _onError(status) {
  10530. this._storedError ??= createResponseStatusError(status, this._url);
  10531. for (const requestCapability of this._requests) {
  10532. requestCapability.reject(this._storedError);
  10533. }
  10534. this._requests.length = 0;
  10535. this._queuedChunk = null;
  10536. }
  10537. _onProgress(evt) {
  10538. if (!this.isStreamingSupported) {
  10539. this.onProgress?.({
  10540. loaded: evt.loaded
  10541. });
  10542. }
  10543. }
  10544. get isStreamingSupported() {
  10545. return false;
  10546. }
  10547. async read() {
  10548. if (this._storedError) {
  10549. throw this._storedError;
  10550. }
  10551. if (this._queuedChunk !== null) {
  10552. const chunk = this._queuedChunk;
  10553. this._queuedChunk = null;
  10554. return {
  10555. value: chunk,
  10556. done: false
  10557. };
  10558. }
  10559. if (this._done) {
  10560. return {
  10561. value: undefined,
  10562. done: true
  10563. };
  10564. }
  10565. const requestCapability = Promise.withResolvers();
  10566. this._requests.push(requestCapability);
  10567. return requestCapability.promise;
  10568. }
  10569. cancel(reason) {
  10570. this._done = true;
  10571. for (const requestCapability of this._requests) {
  10572. requestCapability.resolve({
  10573. value: undefined,
  10574. done: true
  10575. });
  10576. }
  10577. this._requests.length = 0;
  10578. if (this._manager.isPendingRequest(this._requestId)) {
  10579. this._manager.abortRequest(this._requestId);
  10580. }
  10581. this._close();
  10582. }
  10583. }
  10584. ;// ./src/display/node_stream.js
  10585. const urlRegex = /^[a-z][a-z0-9\-+.]+:/i;
  10586. function parseUrlOrPath(sourceUrl) {
  10587. if (urlRegex.test(sourceUrl)) {
  10588. return new URL(sourceUrl);
  10589. }
  10590. const url = process.getBuiltinModule("url");
  10591. return new URL(url.pathToFileURL(sourceUrl));
  10592. }
  10593. class PDFNodeStream {
  10594. constructor(source) {
  10595. this.source = source;
  10596. this.url = parseUrlOrPath(source.url);
  10597. assert(this.url.protocol === "file:", "PDFNodeStream only supports file:// URLs.");
  10598. this._fullRequestReader = null;
  10599. this._rangeRequestReaders = [];
  10600. }
  10601. get _progressiveDataLength() {
  10602. return this._fullRequestReader?._loaded ?? 0;
  10603. }
  10604. getFullReader() {
  10605. assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  10606. this._fullRequestReader = new PDFNodeStreamFsFullReader(this);
  10607. return this._fullRequestReader;
  10608. }
  10609. getRangeReader(start, end) {
  10610. if (end <= this._progressiveDataLength) {
  10611. return null;
  10612. }
  10613. const rangeReader = new PDFNodeStreamFsRangeReader(this, start, end);
  10614. this._rangeRequestReaders.push(rangeReader);
  10615. return rangeReader;
  10616. }
  10617. cancelAllRequests(reason) {
  10618. this._fullRequestReader?.cancel(reason);
  10619. for (const reader of this._rangeRequestReaders.slice(0)) {
  10620. reader.cancel(reason);
  10621. }
  10622. }
  10623. }
  10624. class PDFNodeStreamFsFullReader {
  10625. constructor(stream) {
  10626. this._url = stream.url;
  10627. this._done = false;
  10628. this._storedError = null;
  10629. this.onProgress = null;
  10630. const source = stream.source;
  10631. this._contentLength = source.length;
  10632. this._loaded = 0;
  10633. this._filename = null;
  10634. this._disableRange = source.disableRange || false;
  10635. this._rangeChunkSize = source.rangeChunkSize;
  10636. if (!this._rangeChunkSize && !this._disableRange) {
  10637. this._disableRange = true;
  10638. }
  10639. this._isStreamingSupported = !source.disableStream;
  10640. this._isRangeSupported = !source.disableRange;
  10641. this._readableStream = null;
  10642. this._readCapability = Promise.withResolvers();
  10643. this._headersCapability = Promise.withResolvers();
  10644. const fs = process.getBuiltinModule("fs");
  10645. fs.promises.lstat(this._url).then(stat => {
  10646. this._contentLength = stat.size;
  10647. this._setReadableStream(fs.createReadStream(this._url));
  10648. this._headersCapability.resolve();
  10649. }, error => {
  10650. if (error.code === "ENOENT") {
  10651. error = new MissingPDFException(`Missing PDF "${this._url}".`);
  10652. }
  10653. this._storedError = error;
  10654. this._headersCapability.reject(error);
  10655. });
  10656. }
  10657. get headersReady() {
  10658. return this._headersCapability.promise;
  10659. }
  10660. get filename() {
  10661. return this._filename;
  10662. }
  10663. get contentLength() {
  10664. return this._contentLength;
  10665. }
  10666. get isRangeSupported() {
  10667. return this._isRangeSupported;
  10668. }
  10669. get isStreamingSupported() {
  10670. return this._isStreamingSupported;
  10671. }
  10672. async read() {
  10673. await this._readCapability.promise;
  10674. if (this._done) {
  10675. return {
  10676. value: undefined,
  10677. done: true
  10678. };
  10679. }
  10680. if (this._storedError) {
  10681. throw this._storedError;
  10682. }
  10683. const chunk = this._readableStream.read();
  10684. if (chunk === null) {
  10685. this._readCapability = Promise.withResolvers();
  10686. return this.read();
  10687. }
  10688. this._loaded += chunk.length;
  10689. this.onProgress?.({
  10690. loaded: this._loaded,
  10691. total: this._contentLength
  10692. });
  10693. const buffer = new Uint8Array(chunk).buffer;
  10694. return {
  10695. value: buffer,
  10696. done: false
  10697. };
  10698. }
  10699. cancel(reason) {
  10700. if (!this._readableStream) {
  10701. this._error(reason);
  10702. return;
  10703. }
  10704. this._readableStream.destroy(reason);
  10705. }
  10706. _error(reason) {
  10707. this._storedError = reason;
  10708. this._readCapability.resolve();
  10709. }
  10710. _setReadableStream(readableStream) {
  10711. this._readableStream = readableStream;
  10712. readableStream.on("readable", () => {
  10713. this._readCapability.resolve();
  10714. });
  10715. readableStream.on("end", () => {
  10716. readableStream.destroy();
  10717. this._done = true;
  10718. this._readCapability.resolve();
  10719. });
  10720. readableStream.on("error", reason => {
  10721. this._error(reason);
  10722. });
  10723. if (!this._isStreamingSupported && this._isRangeSupported) {
  10724. this._error(new AbortException("streaming is disabled"));
  10725. }
  10726. if (this._storedError) {
  10727. this._readableStream.destroy(this._storedError);
  10728. }
  10729. }
  10730. }
  10731. class PDFNodeStreamFsRangeReader {
  10732. constructor(stream, start, end) {
  10733. this._url = stream.url;
  10734. this._done = false;
  10735. this._storedError = null;
  10736. this.onProgress = null;
  10737. this._loaded = 0;
  10738. this._readableStream = null;
  10739. this._readCapability = Promise.withResolvers();
  10740. const source = stream.source;
  10741. this._isStreamingSupported = !source.disableStream;
  10742. const fs = process.getBuiltinModule("fs");
  10743. this._setReadableStream(fs.createReadStream(this._url, {
  10744. start,
  10745. end: end - 1
  10746. }));
  10747. }
  10748. get isStreamingSupported() {
  10749. return this._isStreamingSupported;
  10750. }
  10751. async read() {
  10752. await this._readCapability.promise;
  10753. if (this._done) {
  10754. return {
  10755. value: undefined,
  10756. done: true
  10757. };
  10758. }
  10759. if (this._storedError) {
  10760. throw this._storedError;
  10761. }
  10762. const chunk = this._readableStream.read();
  10763. if (chunk === null) {
  10764. this._readCapability = Promise.withResolvers();
  10765. return this.read();
  10766. }
  10767. this._loaded += chunk.length;
  10768. this.onProgress?.({
  10769. loaded: this._loaded
  10770. });
  10771. const buffer = new Uint8Array(chunk).buffer;
  10772. return {
  10773. value: buffer,
  10774. done: false
  10775. };
  10776. }
  10777. cancel(reason) {
  10778. if (!this._readableStream) {
  10779. this._error(reason);
  10780. return;
  10781. }
  10782. this._readableStream.destroy(reason);
  10783. }
  10784. _error(reason) {
  10785. this._storedError = reason;
  10786. this._readCapability.resolve();
  10787. }
  10788. _setReadableStream(readableStream) {
  10789. this._readableStream = readableStream;
  10790. readableStream.on("readable", () => {
  10791. this._readCapability.resolve();
  10792. });
  10793. readableStream.on("end", () => {
  10794. readableStream.destroy();
  10795. this._done = true;
  10796. this._readCapability.resolve();
  10797. });
  10798. readableStream.on("error", reason => {
  10799. this._error(reason);
  10800. });
  10801. if (this._storedError) {
  10802. this._readableStream.destroy(this._storedError);
  10803. }
  10804. }
  10805. }
  10806. ;// ./src/display/text_layer.js
  10807. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  10808. const DEFAULT_FONT_SIZE = 30;
  10809. const DEFAULT_FONT_ASCENT = 0.8;
  10810. class TextLayer {
  10811. #capability = Promise.withResolvers();
  10812. #container = null;
  10813. #disableProcessItems = false;
  10814. #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  10815. #lang = null;
  10816. #layoutTextParams = null;
  10817. #pageHeight = 0;
  10818. #pageWidth = 0;
  10819. #reader = null;
  10820. #rootContainer = null;
  10821. #rotation = 0;
  10822. #scale = 0;
  10823. #styleCache = Object.create(null);
  10824. #textContentItemsStr = [];
  10825. #textContentSource = null;
  10826. #textDivs = [];
  10827. #textDivProperties = new WeakMap();
  10828. #transform = null;
  10829. static #ascentCache = new Map();
  10830. static #canvasContexts = new Map();
  10831. static #canvasCtxFonts = new WeakMap();
  10832. static #minFontSize = null;
  10833. static #pendingTextLayers = new Set();
  10834. constructor({
  10835. textContentSource,
  10836. container,
  10837. viewport
  10838. }) {
  10839. if (textContentSource instanceof ReadableStream) {
  10840. this.#textContentSource = textContentSource;
  10841. } else if (typeof textContentSource === "object") {
  10842. this.#textContentSource = new ReadableStream({
  10843. start(controller) {
  10844. controller.enqueue(textContentSource);
  10845. controller.close();
  10846. }
  10847. });
  10848. } else {
  10849. throw new Error('No "textContentSource" parameter specified.');
  10850. }
  10851. this.#container = this.#rootContainer = container;
  10852. this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  10853. this.#rotation = viewport.rotation;
  10854. this.#layoutTextParams = {
  10855. div: null,
  10856. properties: null,
  10857. ctx: null
  10858. };
  10859. const {
  10860. pageWidth,
  10861. pageHeight,
  10862. pageX,
  10863. pageY
  10864. } = viewport.rawDims;
  10865. this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
  10866. this.#pageWidth = pageWidth;
  10867. this.#pageHeight = pageHeight;
  10868. TextLayer.#ensureMinFontSizeComputed();
  10869. setLayerDimensions(container, viewport);
  10870. this.#capability.promise.finally(() => {
  10871. TextLayer.#pendingTextLayers.delete(this);
  10872. this.#layoutTextParams = null;
  10873. this.#styleCache = null;
  10874. }).catch(() => {});
  10875. }
  10876. static get fontFamilyMap() {
  10877. const {
  10878. isWindows,
  10879. isFirefox
  10880. } = util_FeatureTest.platform;
  10881. return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));
  10882. }
  10883. render() {
  10884. const pump = () => {
  10885. this.#reader.read().then(({
  10886. value,
  10887. done
  10888. }) => {
  10889. if (done) {
  10890. this.#capability.resolve();
  10891. return;
  10892. }
  10893. this.#lang ??= value.lang;
  10894. Object.assign(this.#styleCache, value.styles);
  10895. this.#processItems(value.items);
  10896. pump();
  10897. }, this.#capability.reject);
  10898. };
  10899. this.#reader = this.#textContentSource.getReader();
  10900. TextLayer.#pendingTextLayers.add(this);
  10901. pump();
  10902. return this.#capability.promise;
  10903. }
  10904. update({
  10905. viewport,
  10906. onBefore = null
  10907. }) {
  10908. const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  10909. const rotation = viewport.rotation;
  10910. if (rotation !== this.#rotation) {
  10911. onBefore?.();
  10912. this.#rotation = rotation;
  10913. setLayerDimensions(this.#rootContainer, {
  10914. rotation
  10915. });
  10916. }
  10917. if (scale !== this.#scale) {
  10918. onBefore?.();
  10919. this.#scale = scale;
  10920. const params = {
  10921. div: null,
  10922. properties: null,
  10923. ctx: TextLayer.#getCtx(this.#lang)
  10924. };
  10925. for (const div of this.#textDivs) {
  10926. params.properties = this.#textDivProperties.get(div);
  10927. params.div = div;
  10928. this.#layout(params);
  10929. }
  10930. }
  10931. }
  10932. cancel() {
  10933. const abortEx = new AbortException("TextLayer task cancelled.");
  10934. this.#reader?.cancel(abortEx).catch(() => {});
  10935. this.#reader = null;
  10936. this.#capability.reject(abortEx);
  10937. }
  10938. get textDivs() {
  10939. return this.#textDivs;
  10940. }
  10941. get textContentItemsStr() {
  10942. return this.#textContentItemsStr;
  10943. }
  10944. #processItems(items) {
  10945. if (this.#disableProcessItems) {
  10946. return;
  10947. }
  10948. this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);
  10949. const textDivs = this.#textDivs,
  10950. textContentItemsStr = this.#textContentItemsStr;
  10951. for (const item of items) {
  10952. if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
  10953. warn("Ignoring additional textDivs for performance reasons.");
  10954. this.#disableProcessItems = true;
  10955. return;
  10956. }
  10957. if (item.str === undefined) {
  10958. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  10959. const parent = this.#container;
  10960. this.#container = document.createElement("span");
  10961. this.#container.classList.add("markedContent");
  10962. if (item.id !== null) {
  10963. this.#container.setAttribute("id", `${item.id}`);
  10964. }
  10965. parent.append(this.#container);
  10966. } else if (item.type === "endMarkedContent") {
  10967. this.#container = this.#container.parentNode;
  10968. }
  10969. continue;
  10970. }
  10971. textContentItemsStr.push(item.str);
  10972. this.#appendText(item);
  10973. }
  10974. }
  10975. #appendText(geom) {
  10976. const textDiv = document.createElement("span");
  10977. const textDivProperties = {
  10978. angle: 0,
  10979. canvasWidth: 0,
  10980. hasText: geom.str !== "",
  10981. hasEOL: geom.hasEOL,
  10982. fontSize: 0
  10983. };
  10984. this.#textDivs.push(textDiv);
  10985. const tx = Util.transform(this.#transform, geom.transform);
  10986. let angle = Math.atan2(tx[1], tx[0]);
  10987. const style = this.#styleCache[geom.fontName];
  10988. if (style.vertical) {
  10989. angle += Math.PI / 2;
  10990. }
  10991. let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
  10992. fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
  10993. const fontHeight = Math.hypot(tx[2], tx[3]);
  10994. const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, this.#lang);
  10995. let left, top;
  10996. if (angle === 0) {
  10997. left = tx[4];
  10998. top = tx[5] - fontAscent;
  10999. } else {
  11000. left = tx[4] + fontAscent * Math.sin(angle);
  11001. top = tx[5] - fontAscent * Math.cos(angle);
  11002. }
  11003. const scaleFactorStr = "calc(var(--scale-factor)*";
  11004. const divStyle = textDiv.style;
  11005. if (this.#container === this.#rootContainer) {
  11006. divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
  11007. divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
  11008. } else {
  11009. divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
  11010. divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  11011. }
  11012. divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;
  11013. divStyle.fontFamily = fontFamily;
  11014. textDivProperties.fontSize = fontHeight;
  11015. textDiv.setAttribute("role", "presentation");
  11016. textDiv.textContent = geom.str;
  11017. textDiv.dir = geom.dir;
  11018. if (this.#fontInspectorEnabled) {
  11019. textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
  11020. }
  11021. if (angle !== 0) {
  11022. textDivProperties.angle = angle * (180 / Math.PI);
  11023. }
  11024. let shouldScaleText = false;
  11025. if (geom.str.length > 1) {
  11026. shouldScaleText = true;
  11027. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  11028. const absScaleX = Math.abs(geom.transform[0]),
  11029. absScaleY = Math.abs(geom.transform[3]);
  11030. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  11031. shouldScaleText = true;
  11032. }
  11033. }
  11034. if (shouldScaleText) {
  11035. textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  11036. }
  11037. this.#textDivProperties.set(textDiv, textDivProperties);
  11038. this.#layoutTextParams.div = textDiv;
  11039. this.#layoutTextParams.properties = textDivProperties;
  11040. this.#layout(this.#layoutTextParams);
  11041. if (textDivProperties.hasText) {
  11042. this.#container.append(textDiv);
  11043. }
  11044. if (textDivProperties.hasEOL) {
  11045. const br = document.createElement("br");
  11046. br.setAttribute("role", "presentation");
  11047. this.#container.append(br);
  11048. }
  11049. }
  11050. #layout(params) {
  11051. const {
  11052. div,
  11053. properties,
  11054. ctx
  11055. } = params;
  11056. const {
  11057. style
  11058. } = div;
  11059. let transform = "";
  11060. if (TextLayer.#minFontSize > 1) {
  11061. transform = `scale(${1 / TextLayer.#minFontSize})`;
  11062. }
  11063. if (properties.canvasWidth !== 0 && properties.hasText) {
  11064. const {
  11065. fontFamily
  11066. } = style;
  11067. const {
  11068. canvasWidth,
  11069. fontSize
  11070. } = properties;
  11071. TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);
  11072. const {
  11073. width
  11074. } = ctx.measureText(div.textContent);
  11075. if (width > 0) {
  11076. transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`;
  11077. }
  11078. }
  11079. if (properties.angle !== 0) {
  11080. transform = `rotate(${properties.angle}deg) ${transform}`;
  11081. }
  11082. if (transform.length > 0) {
  11083. style.transform = transform;
  11084. }
  11085. }
  11086. static cleanup() {
  11087. if (this.#pendingTextLayers.size > 0) {
  11088. return;
  11089. }
  11090. this.#ascentCache.clear();
  11091. for (const {
  11092. canvas
  11093. } of this.#canvasContexts.values()) {
  11094. canvas.remove();
  11095. }
  11096. this.#canvasContexts.clear();
  11097. }
  11098. static #getCtx(lang = null) {
  11099. let ctx = this.#canvasContexts.get(lang ||= "");
  11100. if (!ctx) {
  11101. const canvas = document.createElement("canvas");
  11102. canvas.className = "hiddenCanvasElement";
  11103. canvas.lang = lang;
  11104. document.body.append(canvas);
  11105. ctx = canvas.getContext("2d", {
  11106. alpha: false,
  11107. willReadFrequently: true
  11108. });
  11109. this.#canvasContexts.set(lang, ctx);
  11110. this.#canvasCtxFonts.set(ctx, {
  11111. size: 0,
  11112. family: ""
  11113. });
  11114. }
  11115. return ctx;
  11116. }
  11117. static #ensureCtxFont(ctx, size, family) {
  11118. const cached = this.#canvasCtxFonts.get(ctx);
  11119. if (size === cached.size && family === cached.family) {
  11120. return;
  11121. }
  11122. ctx.font = `${size}px ${family}`;
  11123. cached.size = size;
  11124. cached.family = family;
  11125. }
  11126. static #ensureMinFontSizeComputed() {
  11127. if (this.#minFontSize !== null) {
  11128. return;
  11129. }
  11130. const div = document.createElement("div");
  11131. div.style.opacity = 0;
  11132. div.style.lineHeight = 1;
  11133. div.style.fontSize = "1px";
  11134. div.style.position = "absolute";
  11135. div.textContent = "X";
  11136. document.body.append(div);
  11137. this.#minFontSize = div.getBoundingClientRect().height;
  11138. div.remove();
  11139. }
  11140. static #getAscent(fontFamily, lang) {
  11141. const cachedAscent = this.#ascentCache.get(fontFamily);
  11142. if (cachedAscent) {
  11143. return cachedAscent;
  11144. }
  11145. const ctx = this.#getCtx(lang);
  11146. ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
  11147. this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);
  11148. const metrics = ctx.measureText("");
  11149. let ascent = metrics.fontBoundingBoxAscent;
  11150. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  11151. if (ascent) {
  11152. const ratio = ascent / (ascent + descent);
  11153. this.#ascentCache.set(fontFamily, ratio);
  11154. ctx.canvas.width = ctx.canvas.height = 0;
  11155. return ratio;
  11156. }
  11157. ctx.strokeStyle = "red";
  11158. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  11159. ctx.strokeText("g", 0, 0);
  11160. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  11161. descent = 0;
  11162. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  11163. if (pixels[i] > 0) {
  11164. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  11165. break;
  11166. }
  11167. }
  11168. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  11169. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  11170. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  11171. ascent = 0;
  11172. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  11173. if (pixels[i] > 0) {
  11174. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  11175. break;
  11176. }
  11177. }
  11178. ctx.canvas.width = ctx.canvas.height = 0;
  11179. const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT;
  11180. this.#ascentCache.set(fontFamily, ratio);
  11181. return ratio;
  11182. }
  11183. }
  11184. ;// ./src/display/xfa_text.js
  11185. class XfaText {
  11186. static textContent(xfa) {
  11187. const items = [];
  11188. const output = {
  11189. items,
  11190. styles: Object.create(null)
  11191. };
  11192. function walk(node) {
  11193. if (!node) {
  11194. return;
  11195. }
  11196. let str = null;
  11197. const name = node.name;
  11198. if (name === "#text") {
  11199. str = node.value;
  11200. } else if (!XfaText.shouldBuildText(name)) {
  11201. return;
  11202. } else if (node?.attributes?.textContent) {
  11203. str = node.attributes.textContent;
  11204. } else if (node.value) {
  11205. str = node.value;
  11206. }
  11207. if (str !== null) {
  11208. items.push({
  11209. str
  11210. });
  11211. }
  11212. if (!node.children) {
  11213. return;
  11214. }
  11215. for (const child of node.children) {
  11216. walk(child);
  11217. }
  11218. }
  11219. walk(xfa);
  11220. return output;
  11221. }
  11222. static shouldBuildText(name) {
  11223. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  11224. }
  11225. }
  11226. ;// ./src/display/api.js
  11227. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  11228. const RENDERING_CANCELLED_TIMEOUT = 100;
  11229. const DELAYED_CLEANUP_TIMEOUT = 5000;
  11230. const DefaultCanvasFactory = isNodeJS ? NodeCanvasFactory : DOMCanvasFactory;
  11231. const DefaultCMapReaderFactory = isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory;
  11232. const DefaultFilterFactory = isNodeJS ? NodeFilterFactory : DOMFilterFactory;
  11233. const DefaultStandardFontDataFactory = isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory;
  11234. function getDocument(src = {}) {
  11235. if (typeof src === "string" || src instanceof URL) {
  11236. src = {
  11237. url: src
  11238. };
  11239. } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
  11240. src = {
  11241. data: src
  11242. };
  11243. }
  11244. const task = new PDFDocumentLoadingTask();
  11245. const {
  11246. docId
  11247. } = task;
  11248. const url = src.url ? getUrlProp(src.url) : null;
  11249. const data = src.data ? getDataProp(src.data) : null;
  11250. const httpHeaders = src.httpHeaders || null;
  11251. const withCredentials = src.withCredentials === true;
  11252. const password = src.password ?? null;
  11253. const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  11254. const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
  11255. let worker = src.worker instanceof PDFWorker ? src.worker : null;
  11256. const verbosity = src.verbosity;
  11257. const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
  11258. const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
  11259. const cMapPacked = src.cMapPacked !== false;
  11260. const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
  11261. const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
  11262. const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
  11263. const ignoreErrors = src.stopAtErrors !== true;
  11264. const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  11265. const isEvalSupported = src.isEvalSupported !== false;
  11266. const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
  11267. const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (util_FeatureTest.platform.isFirefox || !globalThis.chrome);
  11268. const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
  11269. const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
  11270. const fontExtraProperties = src.fontExtraProperties === true;
  11271. const enableXfa = src.enableXfa === true;
  11272. const ownerDocument = src.ownerDocument || globalThis.document;
  11273. const disableRange = src.disableRange === true;
  11274. const disableStream = src.disableStream === true;
  11275. const disableAutoFetch = src.disableAutoFetch === true;
  11276. const pdfBug = src.pdfBug === true;
  11277. const CanvasFactory = src.CanvasFactory || DefaultCanvasFactory;
  11278. const FilterFactory = src.FilterFactory || DefaultFilterFactory;
  11279. const enableHWA = src.enableHWA === true;
  11280. const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  11281. const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
  11282. const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI);
  11283. const styleElement = null;
  11284. setVerbosityLevel(verbosity);
  11285. const transportFactory = {
  11286. canvasFactory: new CanvasFactory({
  11287. ownerDocument,
  11288. enableHWA
  11289. }),
  11290. filterFactory: new FilterFactory({
  11291. docId,
  11292. ownerDocument
  11293. }),
  11294. cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({
  11295. baseUrl: cMapUrl,
  11296. isCompressed: cMapPacked
  11297. }),
  11298. standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({
  11299. baseUrl: standardFontDataUrl
  11300. })
  11301. };
  11302. if (!worker) {
  11303. const workerParams = {
  11304. verbosity,
  11305. port: GlobalWorkerOptions.workerPort
  11306. };
  11307. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  11308. task._worker = worker;
  11309. }
  11310. const docParams = {
  11311. docId,
  11312. apiVersion: "4.10.38",
  11313. data,
  11314. password,
  11315. disableAutoFetch,
  11316. rangeChunkSize,
  11317. length,
  11318. docBaseUrl,
  11319. enableXfa,
  11320. evaluatorOptions: {
  11321. maxImageSize,
  11322. disableFontFace,
  11323. ignoreErrors,
  11324. isEvalSupported,
  11325. isOffscreenCanvasSupported,
  11326. isImageDecoderSupported,
  11327. canvasMaxAreaInBytes,
  11328. fontExtraProperties,
  11329. useSystemFonts,
  11330. cMapUrl: useWorkerFetch ? cMapUrl : null,
  11331. standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
  11332. }
  11333. };
  11334. const transportParams = {
  11335. disableFontFace,
  11336. fontExtraProperties,
  11337. ownerDocument,
  11338. pdfBug,
  11339. styleElement,
  11340. loadingParams: {
  11341. disableAutoFetch,
  11342. enableXfa
  11343. }
  11344. };
  11345. worker.promise.then(function () {
  11346. if (task.destroyed) {
  11347. throw new Error("Loading aborted");
  11348. }
  11349. if (worker.destroyed) {
  11350. throw new Error("Worker was destroyed");
  11351. }
  11352. const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
  11353. let networkStream;
  11354. if (rangeTransport) {
  11355. networkStream = new PDFDataTransportStream(rangeTransport, {
  11356. disableRange,
  11357. disableStream
  11358. });
  11359. } else if (!data) {
  11360. if (!url) {
  11361. throw new Error("getDocument - no `url` parameter provided.");
  11362. }
  11363. let NetworkStream;
  11364. if (isNodeJS) {
  11365. if (isValidFetchUrl(url)) {
  11366. if (typeof fetch === "undefined" || typeof Response === "undefined" || !("body" in Response.prototype)) {
  11367. throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");
  11368. }
  11369. NetworkStream = PDFFetchStream;
  11370. } else {
  11371. NetworkStream = PDFNodeStream;
  11372. }
  11373. } else {
  11374. NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : PDFNetworkStream;
  11375. }
  11376. networkStream = new NetworkStream({
  11377. url,
  11378. length,
  11379. httpHeaders,
  11380. withCredentials,
  11381. rangeChunkSize,
  11382. disableRange,
  11383. disableStream
  11384. });
  11385. }
  11386. return workerIdPromise.then(workerId => {
  11387. if (task.destroyed) {
  11388. throw new Error("Loading aborted");
  11389. }
  11390. if (worker.destroyed) {
  11391. throw new Error("Worker was destroyed");
  11392. }
  11393. const messageHandler = new MessageHandler(docId, workerId, worker.port);
  11394. const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
  11395. task._transport = transport;
  11396. messageHandler.send("Ready", null);
  11397. });
  11398. }).catch(task._capability.reject);
  11399. return task;
  11400. }
  11401. function getUrlProp(val) {
  11402. if (val instanceof URL) {
  11403. return val.href;
  11404. }
  11405. try {
  11406. return new URL(val, window.location).href;
  11407. } catch {
  11408. if (isNodeJS && typeof val === "string") {
  11409. return val;
  11410. }
  11411. }
  11412. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  11413. }
  11414. function getDataProp(val) {
  11415. if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
  11416. throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
  11417. }
  11418. if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
  11419. return val;
  11420. }
  11421. if (typeof val === "string") {
  11422. return stringToBytes(val);
  11423. }
  11424. if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) {
  11425. return new Uint8Array(val);
  11426. }
  11427. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  11428. }
  11429. function isRefProxy(ref) {
  11430. return typeof ref === "object" && Number.isInteger(ref?.num) && ref.num >= 0 && Number.isInteger(ref?.gen) && ref.gen >= 0;
  11431. }
  11432. class PDFDocumentLoadingTask {
  11433. static #docId = 0;
  11434. constructor() {
  11435. this._capability = Promise.withResolvers();
  11436. this._transport = null;
  11437. this._worker = null;
  11438. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  11439. this.destroyed = false;
  11440. this.onPassword = null;
  11441. this.onProgress = null;
  11442. }
  11443. get promise() {
  11444. return this._capability.promise;
  11445. }
  11446. async destroy() {
  11447. this.destroyed = true;
  11448. try {
  11449. if (this._worker?.port) {
  11450. this._worker._pendingDestroy = true;
  11451. }
  11452. await this._transport?.destroy();
  11453. } catch (ex) {
  11454. if (this._worker?.port) {
  11455. delete this._worker._pendingDestroy;
  11456. }
  11457. throw ex;
  11458. }
  11459. this._transport = null;
  11460. this._worker?.destroy();
  11461. this._worker = null;
  11462. }
  11463. }
  11464. class PDFDataRangeTransport {
  11465. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  11466. this.length = length;
  11467. this.initialData = initialData;
  11468. this.progressiveDone = progressiveDone;
  11469. this.contentDispositionFilename = contentDispositionFilename;
  11470. this._rangeListeners = [];
  11471. this._progressListeners = [];
  11472. this._progressiveReadListeners = [];
  11473. this._progressiveDoneListeners = [];
  11474. this._readyCapability = Promise.withResolvers();
  11475. }
  11476. addRangeListener(listener) {
  11477. this._rangeListeners.push(listener);
  11478. }
  11479. addProgressListener(listener) {
  11480. this._progressListeners.push(listener);
  11481. }
  11482. addProgressiveReadListener(listener) {
  11483. this._progressiveReadListeners.push(listener);
  11484. }
  11485. addProgressiveDoneListener(listener) {
  11486. this._progressiveDoneListeners.push(listener);
  11487. }
  11488. onDataRange(begin, chunk) {
  11489. for (const listener of this._rangeListeners) {
  11490. listener(begin, chunk);
  11491. }
  11492. }
  11493. onDataProgress(loaded, total) {
  11494. this._readyCapability.promise.then(() => {
  11495. for (const listener of this._progressListeners) {
  11496. listener(loaded, total);
  11497. }
  11498. });
  11499. }
  11500. onDataProgressiveRead(chunk) {
  11501. this._readyCapability.promise.then(() => {
  11502. for (const listener of this._progressiveReadListeners) {
  11503. listener(chunk);
  11504. }
  11505. });
  11506. }
  11507. onDataProgressiveDone() {
  11508. this._readyCapability.promise.then(() => {
  11509. for (const listener of this._progressiveDoneListeners) {
  11510. listener();
  11511. }
  11512. });
  11513. }
  11514. transportReady() {
  11515. this._readyCapability.resolve();
  11516. }
  11517. requestDataRange(begin, end) {
  11518. unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
  11519. }
  11520. abort() {}
  11521. }
  11522. class PDFDocumentProxy {
  11523. constructor(pdfInfo, transport) {
  11524. this._pdfInfo = pdfInfo;
  11525. this._transport = transport;
  11526. }
  11527. get annotationStorage() {
  11528. return this._transport.annotationStorage;
  11529. }
  11530. get canvasFactory() {
  11531. return this._transport.canvasFactory;
  11532. }
  11533. get filterFactory() {
  11534. return this._transport.filterFactory;
  11535. }
  11536. get numPages() {
  11537. return this._pdfInfo.numPages;
  11538. }
  11539. get fingerprints() {
  11540. return this._pdfInfo.fingerprints;
  11541. }
  11542. get isPureXfa() {
  11543. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  11544. }
  11545. get allXfaHtml() {
  11546. return this._transport._htmlForXfa;
  11547. }
  11548. getPage(pageNumber) {
  11549. return this._transport.getPage(pageNumber);
  11550. }
  11551. getPageIndex(ref) {
  11552. return this._transport.getPageIndex(ref);
  11553. }
  11554. getDestinations() {
  11555. return this._transport.getDestinations();
  11556. }
  11557. getDestination(id) {
  11558. return this._transport.getDestination(id);
  11559. }
  11560. getPageLabels() {
  11561. return this._transport.getPageLabels();
  11562. }
  11563. getPageLayout() {
  11564. return this._transport.getPageLayout();
  11565. }
  11566. getPageMode() {
  11567. return this._transport.getPageMode();
  11568. }
  11569. getViewerPreferences() {
  11570. return this._transport.getViewerPreferences();
  11571. }
  11572. getOpenAction() {
  11573. return this._transport.getOpenAction();
  11574. }
  11575. getAttachments() {
  11576. return this._transport.getAttachments();
  11577. }
  11578. getJSActions() {
  11579. return this._transport.getDocJSActions();
  11580. }
  11581. getOutline() {
  11582. return this._transport.getOutline();
  11583. }
  11584. getOptionalContentConfig({
  11585. intent = "display"
  11586. } = {}) {
  11587. const {
  11588. renderingIntent
  11589. } = this._transport.getRenderingIntent(intent);
  11590. return this._transport.getOptionalContentConfig(renderingIntent);
  11591. }
  11592. getPermissions() {
  11593. return this._transport.getPermissions();
  11594. }
  11595. getMetadata() {
  11596. return this._transport.getMetadata();
  11597. }
  11598. getMarkInfo() {
  11599. return this._transport.getMarkInfo();
  11600. }
  11601. getData() {
  11602. return this._transport.getData();
  11603. }
  11604. saveDocument() {
  11605. return this._transport.saveDocument();
  11606. }
  11607. getDownloadInfo() {
  11608. return this._transport.downloadInfoCapability.promise;
  11609. }
  11610. cleanup(keepLoadedFonts = false) {
  11611. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  11612. }
  11613. destroy() {
  11614. return this.loadingTask.destroy();
  11615. }
  11616. cachedPageNumber(ref) {
  11617. return this._transport.cachedPageNumber(ref);
  11618. }
  11619. get loadingParams() {
  11620. return this._transport.loadingParams;
  11621. }
  11622. get loadingTask() {
  11623. return this._transport.loadingTask;
  11624. }
  11625. getFieldObjects() {
  11626. return this._transport.getFieldObjects();
  11627. }
  11628. hasJSActions() {
  11629. return this._transport.hasJSActions();
  11630. }
  11631. getCalculationOrderIds() {
  11632. return this._transport.getCalculationOrderIds();
  11633. }
  11634. }
  11635. class PDFPageProxy {
  11636. #delayedCleanupTimeout = null;
  11637. #pendingCleanup = false;
  11638. constructor(pageIndex, pageInfo, transport, pdfBug = false) {
  11639. this._pageIndex = pageIndex;
  11640. this._pageInfo = pageInfo;
  11641. this._transport = transport;
  11642. this._stats = pdfBug ? new StatTimer() : null;
  11643. this._pdfBug = pdfBug;
  11644. this.commonObjs = transport.commonObjs;
  11645. this.objs = new PDFObjects();
  11646. this._maybeCleanupAfterRender = false;
  11647. this._intentStates = new Map();
  11648. this.destroyed = false;
  11649. }
  11650. get pageNumber() {
  11651. return this._pageIndex + 1;
  11652. }
  11653. get rotate() {
  11654. return this._pageInfo.rotate;
  11655. }
  11656. get ref() {
  11657. return this._pageInfo.ref;
  11658. }
  11659. get userUnit() {
  11660. return this._pageInfo.userUnit;
  11661. }
  11662. get view() {
  11663. return this._pageInfo.view;
  11664. }
  11665. getViewport({
  11666. scale,
  11667. rotation = this.rotate,
  11668. offsetX = 0,
  11669. offsetY = 0,
  11670. dontFlip = false
  11671. } = {}) {
  11672. return new PageViewport({
  11673. viewBox: this.view,
  11674. userUnit: this.userUnit,
  11675. scale,
  11676. rotation,
  11677. offsetX,
  11678. offsetY,
  11679. dontFlip
  11680. });
  11681. }
  11682. getAnnotations({
  11683. intent = "display"
  11684. } = {}) {
  11685. const {
  11686. renderingIntent
  11687. } = this._transport.getRenderingIntent(intent);
  11688. return this._transport.getAnnotations(this._pageIndex, renderingIntent);
  11689. }
  11690. getJSActions() {
  11691. return this._transport.getPageJSActions(this._pageIndex);
  11692. }
  11693. get filterFactory() {
  11694. return this._transport.filterFactory;
  11695. }
  11696. get isPureXfa() {
  11697. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  11698. }
  11699. async getXfa() {
  11700. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  11701. }
  11702. render({
  11703. canvasContext,
  11704. viewport,
  11705. intent = "display",
  11706. annotationMode = AnnotationMode.ENABLE,
  11707. transform = null,
  11708. background = null,
  11709. optionalContentConfigPromise = null,
  11710. annotationCanvasMap = null,
  11711. pageColors = null,
  11712. printAnnotationStorage = null,
  11713. isEditing = false
  11714. }) {
  11715. this._stats?.time("Overall");
  11716. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);
  11717. const {
  11718. renderingIntent,
  11719. cacheKey
  11720. } = intentArgs;
  11721. this.#pendingCleanup = false;
  11722. this.#abortDelayedCleanup();
  11723. optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
  11724. let intentState = this._intentStates.get(cacheKey);
  11725. if (!intentState) {
  11726. intentState = Object.create(null);
  11727. this._intentStates.set(cacheKey, intentState);
  11728. }
  11729. if (intentState.streamReaderCancelTimeout) {
  11730. clearTimeout(intentState.streamReaderCancelTimeout);
  11731. intentState.streamReaderCancelTimeout = null;
  11732. }
  11733. const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  11734. if (!intentState.displayReadyCapability) {
  11735. intentState.displayReadyCapability = Promise.withResolvers();
  11736. intentState.operatorList = {
  11737. fnArray: [],
  11738. argsArray: [],
  11739. lastChunk: false,
  11740. separateAnnots: null
  11741. };
  11742. this._stats?.time("Page Request");
  11743. this._pumpOperatorList(intentArgs);
  11744. }
  11745. const complete = error => {
  11746. intentState.renderTasks.delete(internalRenderTask);
  11747. if (this._maybeCleanupAfterRender || intentPrint) {
  11748. this.#pendingCleanup = true;
  11749. }
  11750. this.#tryCleanup(!intentPrint);
  11751. if (error) {
  11752. internalRenderTask.capability.reject(error);
  11753. this._abortOperatorList({
  11754. intentState,
  11755. reason: error instanceof Error ? error : new Error(error)
  11756. });
  11757. } else {
  11758. internalRenderTask.capability.resolve();
  11759. }
  11760. if (this._stats) {
  11761. this._stats.timeEnd("Rendering");
  11762. this._stats.timeEnd("Overall");
  11763. if (globalThis.Stats?.enabled) {
  11764. globalThis.Stats.add(this.pageNumber, this._stats);
  11765. }
  11766. }
  11767. };
  11768. const internalRenderTask = new InternalRenderTask({
  11769. callback: complete,
  11770. params: {
  11771. canvasContext,
  11772. viewport,
  11773. transform,
  11774. background
  11775. },
  11776. objs: this.objs,
  11777. commonObjs: this.commonObjs,
  11778. annotationCanvasMap,
  11779. operatorList: intentState.operatorList,
  11780. pageIndex: this._pageIndex,
  11781. canvasFactory: this._transport.canvasFactory,
  11782. filterFactory: this._transport.filterFactory,
  11783. useRequestAnimationFrame: !intentPrint,
  11784. pdfBug: this._pdfBug,
  11785. pageColors
  11786. });
  11787. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  11788. const renderTask = internalRenderTask.task;
  11789. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  11790. if (this.destroyed) {
  11791. complete();
  11792. return;
  11793. }
  11794. this._stats?.time("Rendering");
  11795. if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
  11796. throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods.");
  11797. }
  11798. internalRenderTask.initializeGraphics({
  11799. transparency,
  11800. optionalContentConfig
  11801. });
  11802. internalRenderTask.operatorListChanged();
  11803. }).catch(complete);
  11804. return renderTask;
  11805. }
  11806. getOperatorList({
  11807. intent = "display",
  11808. annotationMode = AnnotationMode.ENABLE,
  11809. printAnnotationStorage = null,
  11810. isEditing = false
  11811. } = {}) {
  11812. function operatorListChanged() {
  11813. if (intentState.operatorList.lastChunk) {
  11814. intentState.opListReadCapability.resolve(intentState.operatorList);
  11815. intentState.renderTasks.delete(opListTask);
  11816. }
  11817. }
  11818. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);
  11819. let intentState = this._intentStates.get(intentArgs.cacheKey);
  11820. if (!intentState) {
  11821. intentState = Object.create(null);
  11822. this._intentStates.set(intentArgs.cacheKey, intentState);
  11823. }
  11824. let opListTask;
  11825. if (!intentState.opListReadCapability) {
  11826. opListTask = Object.create(null);
  11827. opListTask.operatorListChanged = operatorListChanged;
  11828. intentState.opListReadCapability = Promise.withResolvers();
  11829. (intentState.renderTasks ||= new Set()).add(opListTask);
  11830. intentState.operatorList = {
  11831. fnArray: [],
  11832. argsArray: [],
  11833. lastChunk: false,
  11834. separateAnnots: null
  11835. };
  11836. this._stats?.time("Page Request");
  11837. this._pumpOperatorList(intentArgs);
  11838. }
  11839. return intentState.opListReadCapability.promise;
  11840. }
  11841. streamTextContent({
  11842. includeMarkedContent = false,
  11843. disableNormalization = false
  11844. } = {}) {
  11845. const TEXT_CONTENT_CHUNK_SIZE = 100;
  11846. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  11847. pageIndex: this._pageIndex,
  11848. includeMarkedContent: includeMarkedContent === true,
  11849. disableNormalization: disableNormalization === true
  11850. }, {
  11851. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  11852. size(textContent) {
  11853. return textContent.items.length;
  11854. }
  11855. });
  11856. }
  11857. getTextContent(params = {}) {
  11858. if (this._transport._htmlForXfa) {
  11859. return this.getXfa().then(xfa => XfaText.textContent(xfa));
  11860. }
  11861. const readableStream = this.streamTextContent(params);
  11862. return new Promise(function (resolve, reject) {
  11863. function pump() {
  11864. reader.read().then(function ({
  11865. value,
  11866. done
  11867. }) {
  11868. if (done) {
  11869. resolve(textContent);
  11870. return;
  11871. }
  11872. textContent.lang ??= value.lang;
  11873. Object.assign(textContent.styles, value.styles);
  11874. textContent.items.push(...value.items);
  11875. pump();
  11876. }, reject);
  11877. }
  11878. const reader = readableStream.getReader();
  11879. const textContent = {
  11880. items: [],
  11881. styles: Object.create(null),
  11882. lang: null
  11883. };
  11884. pump();
  11885. });
  11886. }
  11887. getStructTree() {
  11888. return this._transport.getStructTree(this._pageIndex);
  11889. }
  11890. _destroy() {
  11891. this.destroyed = true;
  11892. const waitOn = [];
  11893. for (const intentState of this._intentStates.values()) {
  11894. this._abortOperatorList({
  11895. intentState,
  11896. reason: new Error("Page was destroyed."),
  11897. force: true
  11898. });
  11899. if (intentState.opListReadCapability) {
  11900. continue;
  11901. }
  11902. for (const internalRenderTask of intentState.renderTasks) {
  11903. waitOn.push(internalRenderTask.completed);
  11904. internalRenderTask.cancel();
  11905. }
  11906. }
  11907. this.objs.clear();
  11908. this.#pendingCleanup = false;
  11909. this.#abortDelayedCleanup();
  11910. return Promise.all(waitOn);
  11911. }
  11912. cleanup(resetStats = false) {
  11913. this.#pendingCleanup = true;
  11914. const success = this.#tryCleanup(false);
  11915. if (resetStats && success) {
  11916. this._stats &&= new StatTimer();
  11917. }
  11918. return success;
  11919. }
  11920. #tryCleanup(delayed = false) {
  11921. this.#abortDelayedCleanup();
  11922. if (!this.#pendingCleanup || this.destroyed) {
  11923. return false;
  11924. }
  11925. if (delayed) {
  11926. this.#delayedCleanupTimeout = setTimeout(() => {
  11927. this.#delayedCleanupTimeout = null;
  11928. this.#tryCleanup(false);
  11929. }, DELAYED_CLEANUP_TIMEOUT);
  11930. return false;
  11931. }
  11932. for (const {
  11933. renderTasks,
  11934. operatorList
  11935. } of this._intentStates.values()) {
  11936. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  11937. return false;
  11938. }
  11939. }
  11940. this._intentStates.clear();
  11941. this.objs.clear();
  11942. this.#pendingCleanup = false;
  11943. return true;
  11944. }
  11945. #abortDelayedCleanup() {
  11946. if (this.#delayedCleanupTimeout) {
  11947. clearTimeout(this.#delayedCleanupTimeout);
  11948. this.#delayedCleanupTimeout = null;
  11949. }
  11950. }
  11951. _startRenderPage(transparency, cacheKey) {
  11952. const intentState = this._intentStates.get(cacheKey);
  11953. if (!intentState) {
  11954. return;
  11955. }
  11956. this._stats?.timeEnd("Page Request");
  11957. intentState.displayReadyCapability?.resolve(transparency);
  11958. }
  11959. _renderPageChunk(operatorListChunk, intentState) {
  11960. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  11961. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  11962. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  11963. }
  11964. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  11965. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  11966. for (const internalRenderTask of intentState.renderTasks) {
  11967. internalRenderTask.operatorListChanged();
  11968. }
  11969. if (operatorListChunk.lastChunk) {
  11970. this.#tryCleanup(true);
  11971. }
  11972. }
  11973. _pumpOperatorList({
  11974. renderingIntent,
  11975. cacheKey,
  11976. annotationStorageSerializable,
  11977. modifiedIds
  11978. }) {
  11979. const {
  11980. map,
  11981. transfer
  11982. } = annotationStorageSerializable;
  11983. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  11984. pageIndex: this._pageIndex,
  11985. intent: renderingIntent,
  11986. cacheKey,
  11987. annotationStorage: map,
  11988. modifiedIds
  11989. }, transfer);
  11990. const reader = readableStream.getReader();
  11991. const intentState = this._intentStates.get(cacheKey);
  11992. intentState.streamReader = reader;
  11993. const pump = () => {
  11994. reader.read().then(({
  11995. value,
  11996. done
  11997. }) => {
  11998. if (done) {
  11999. intentState.streamReader = null;
  12000. return;
  12001. }
  12002. if (this._transport.destroyed) {
  12003. return;
  12004. }
  12005. this._renderPageChunk(value, intentState);
  12006. pump();
  12007. }, reason => {
  12008. intentState.streamReader = null;
  12009. if (this._transport.destroyed) {
  12010. return;
  12011. }
  12012. if (intentState.operatorList) {
  12013. intentState.operatorList.lastChunk = true;
  12014. for (const internalRenderTask of intentState.renderTasks) {
  12015. internalRenderTask.operatorListChanged();
  12016. }
  12017. this.#tryCleanup(true);
  12018. }
  12019. if (intentState.displayReadyCapability) {
  12020. intentState.displayReadyCapability.reject(reason);
  12021. } else if (intentState.opListReadCapability) {
  12022. intentState.opListReadCapability.reject(reason);
  12023. } else {
  12024. throw reason;
  12025. }
  12026. });
  12027. };
  12028. pump();
  12029. }
  12030. _abortOperatorList({
  12031. intentState,
  12032. reason,
  12033. force = false
  12034. }) {
  12035. if (!intentState.streamReader) {
  12036. return;
  12037. }
  12038. if (intentState.streamReaderCancelTimeout) {
  12039. clearTimeout(intentState.streamReaderCancelTimeout);
  12040. intentState.streamReaderCancelTimeout = null;
  12041. }
  12042. if (!force) {
  12043. if (intentState.renderTasks.size > 0) {
  12044. return;
  12045. }
  12046. if (reason instanceof RenderingCancelledException) {
  12047. let delay = RENDERING_CANCELLED_TIMEOUT;
  12048. if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
  12049. delay += reason.extraDelay;
  12050. }
  12051. intentState.streamReaderCancelTimeout = setTimeout(() => {
  12052. intentState.streamReaderCancelTimeout = null;
  12053. this._abortOperatorList({
  12054. intentState,
  12055. reason,
  12056. force: true
  12057. });
  12058. }, delay);
  12059. return;
  12060. }
  12061. }
  12062. intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {});
  12063. intentState.streamReader = null;
  12064. if (this._transport.destroyed) {
  12065. return;
  12066. }
  12067. for (const [curCacheKey, curIntentState] of this._intentStates) {
  12068. if (curIntentState === intentState) {
  12069. this._intentStates.delete(curCacheKey);
  12070. break;
  12071. }
  12072. }
  12073. this.cleanup();
  12074. }
  12075. get stats() {
  12076. return this._stats;
  12077. }
  12078. }
  12079. class LoopbackPort {
  12080. #listeners = new Map();
  12081. #deferred = Promise.resolve();
  12082. postMessage(obj, transfer) {
  12083. const event = {
  12084. data: structuredClone(obj, transfer ? {
  12085. transfer
  12086. } : null)
  12087. };
  12088. this.#deferred.then(() => {
  12089. for (const [listener] of this.#listeners) {
  12090. listener.call(this, event);
  12091. }
  12092. });
  12093. }
  12094. addEventListener(name, listener, options = null) {
  12095. let rmAbort = null;
  12096. if (options?.signal instanceof AbortSignal) {
  12097. const {
  12098. signal
  12099. } = options;
  12100. if (signal.aborted) {
  12101. warn("LoopbackPort - cannot use an `aborted` signal.");
  12102. return;
  12103. }
  12104. const onAbort = () => this.removeEventListener(name, listener);
  12105. rmAbort = () => signal.removeEventListener("abort", onAbort);
  12106. signal.addEventListener("abort", onAbort);
  12107. }
  12108. this.#listeners.set(listener, rmAbort);
  12109. }
  12110. removeEventListener(name, listener) {
  12111. const rmAbort = this.#listeners.get(listener);
  12112. rmAbort?.();
  12113. this.#listeners.delete(listener);
  12114. }
  12115. terminate() {
  12116. for (const [, rmAbort] of this.#listeners) {
  12117. rmAbort?.();
  12118. }
  12119. this.#listeners.clear();
  12120. }
  12121. }
  12122. class PDFWorker {
  12123. static #fakeWorkerId = 0;
  12124. static #isWorkerDisabled = false;
  12125. static #workerPorts;
  12126. static {
  12127. if (isNodeJS) {
  12128. this.#isWorkerDisabled = true;
  12129. GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";
  12130. }
  12131. this._isSameOrigin = (baseUrl, otherUrl) => {
  12132. let base;
  12133. try {
  12134. base = new URL(baseUrl);
  12135. if (!base.origin || base.origin === "null") {
  12136. return false;
  12137. }
  12138. } catch {
  12139. return false;
  12140. }
  12141. const other = new URL(otherUrl, base);
  12142. return base.origin === other.origin;
  12143. };
  12144. this._createCDNWrapper = url => {
  12145. const wrapper = `await import("${url}");`;
  12146. return URL.createObjectURL(new Blob([wrapper], {
  12147. type: "text/javascript"
  12148. }));
  12149. };
  12150. }
  12151. constructor({
  12152. name = null,
  12153. port = null,
  12154. verbosity = getVerbosityLevel()
  12155. } = {}) {
  12156. this.name = name;
  12157. this.destroyed = false;
  12158. this.verbosity = verbosity;
  12159. this._readyCapability = Promise.withResolvers();
  12160. this._port = null;
  12161. this._webWorker = null;
  12162. this._messageHandler = null;
  12163. if (port) {
  12164. if (PDFWorker.#workerPorts?.has(port)) {
  12165. throw new Error("Cannot use more than one PDFWorker per port.");
  12166. }
  12167. (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);
  12168. this._initializeFromPort(port);
  12169. return;
  12170. }
  12171. this._initialize();
  12172. }
  12173. get promise() {
  12174. return this._readyCapability.promise;
  12175. }
  12176. #resolve() {
  12177. this._readyCapability.resolve();
  12178. this._messageHandler.send("configure", {
  12179. verbosity: this.verbosity
  12180. });
  12181. }
  12182. get port() {
  12183. return this._port;
  12184. }
  12185. get messageHandler() {
  12186. return this._messageHandler;
  12187. }
  12188. _initializeFromPort(port) {
  12189. this._port = port;
  12190. this._messageHandler = new MessageHandler("main", "worker", port);
  12191. this._messageHandler.on("ready", function () {});
  12192. this.#resolve();
  12193. }
  12194. _initialize() {
  12195. if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) {
  12196. this._setupFakeWorker();
  12197. return;
  12198. }
  12199. let {
  12200. workerSrc
  12201. } = PDFWorker;
  12202. try {
  12203. if (!PDFWorker._isSameOrigin(window.location.href, workerSrc)) {
  12204. workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);
  12205. }
  12206. const worker = new Worker(workerSrc, {
  12207. type: "module"
  12208. });
  12209. const messageHandler = new MessageHandler("main", "worker", worker);
  12210. const terminateEarly = () => {
  12211. ac.abort();
  12212. messageHandler.destroy();
  12213. worker.terminate();
  12214. if (this.destroyed) {
  12215. this._readyCapability.reject(new Error("Worker was destroyed"));
  12216. } else {
  12217. this._setupFakeWorker();
  12218. }
  12219. };
  12220. const ac = new AbortController();
  12221. worker.addEventListener("error", () => {
  12222. if (!this._webWorker) {
  12223. terminateEarly();
  12224. }
  12225. }, {
  12226. signal: ac.signal
  12227. });
  12228. messageHandler.on("test", data => {
  12229. ac.abort();
  12230. if (this.destroyed || !data) {
  12231. terminateEarly();
  12232. return;
  12233. }
  12234. this._messageHandler = messageHandler;
  12235. this._port = worker;
  12236. this._webWorker = worker;
  12237. this.#resolve();
  12238. });
  12239. messageHandler.on("ready", data => {
  12240. ac.abort();
  12241. if (this.destroyed) {
  12242. terminateEarly();
  12243. return;
  12244. }
  12245. try {
  12246. sendTest();
  12247. } catch {
  12248. this._setupFakeWorker();
  12249. }
  12250. });
  12251. const sendTest = () => {
  12252. const testObj = new Uint8Array();
  12253. messageHandler.send("test", testObj, [testObj.buffer]);
  12254. };
  12255. sendTest();
  12256. return;
  12257. } catch {
  12258. info("The worker has been disabled.");
  12259. }
  12260. this._setupFakeWorker();
  12261. }
  12262. _setupFakeWorker() {
  12263. if (!PDFWorker.#isWorkerDisabled) {
  12264. warn("Setting up fake worker.");
  12265. PDFWorker.#isWorkerDisabled = true;
  12266. }
  12267. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  12268. if (this.destroyed) {
  12269. this._readyCapability.reject(new Error("Worker was destroyed"));
  12270. return;
  12271. }
  12272. const port = new LoopbackPort();
  12273. this._port = port;
  12274. const id = `fake${PDFWorker.#fakeWorkerId++}`;
  12275. const workerHandler = new MessageHandler(id + "_worker", id, port);
  12276. WorkerMessageHandler.setup(workerHandler, port);
  12277. this._messageHandler = new MessageHandler(id, id + "_worker", port);
  12278. this.#resolve();
  12279. }).catch(reason => {
  12280. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  12281. });
  12282. }
  12283. destroy() {
  12284. this.destroyed = true;
  12285. this._webWorker?.terminate();
  12286. this._webWorker = null;
  12287. PDFWorker.#workerPorts?.delete(this._port);
  12288. this._port = null;
  12289. this._messageHandler?.destroy();
  12290. this._messageHandler = null;
  12291. }
  12292. static fromPort(params) {
  12293. if (!params?.port) {
  12294. throw new Error("PDFWorker.fromPort - invalid method signature.");
  12295. }
  12296. const cachedPort = this.#workerPorts?.get(params.port);
  12297. if (cachedPort) {
  12298. if (cachedPort._pendingDestroy) {
  12299. throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
  12300. }
  12301. return cachedPort;
  12302. }
  12303. return new PDFWorker(params);
  12304. }
  12305. static get workerSrc() {
  12306. if (GlobalWorkerOptions.workerSrc) {
  12307. return GlobalWorkerOptions.workerSrc;
  12308. }
  12309. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  12310. }
  12311. static get #mainThreadWorkerMessageHandler() {
  12312. try {
  12313. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  12314. } catch {
  12315. return null;
  12316. }
  12317. }
  12318. static get _setupFakeWorkerGlobal() {
  12319. const loader = async () => {
  12320. if (this.#mainThreadWorkerMessageHandler) {
  12321. return this.#mainThreadWorkerMessageHandler;
  12322. }
  12323. const worker = await import(/*webpackIgnore: true*/this.workerSrc);
  12324. return worker.WorkerMessageHandler;
  12325. };
  12326. return shadow(this, "_setupFakeWorkerGlobal", loader());
  12327. }
  12328. }
  12329. class WorkerTransport {
  12330. #methodPromises = new Map();
  12331. #pageCache = new Map();
  12332. #pagePromises = new Map();
  12333. #pageRefCache = new Map();
  12334. #passwordCapability = null;
  12335. constructor(messageHandler, loadingTask, networkStream, params, factory) {
  12336. this.messageHandler = messageHandler;
  12337. this.loadingTask = loadingTask;
  12338. this.commonObjs = new PDFObjects();
  12339. this.fontLoader = new FontLoader({
  12340. ownerDocument: params.ownerDocument,
  12341. styleElement: params.styleElement
  12342. });
  12343. this.loadingParams = params.loadingParams;
  12344. this._params = params;
  12345. this.canvasFactory = factory.canvasFactory;
  12346. this.filterFactory = factory.filterFactory;
  12347. this.cMapReaderFactory = factory.cMapReaderFactory;
  12348. this.standardFontDataFactory = factory.standardFontDataFactory;
  12349. this.destroyed = false;
  12350. this.destroyCapability = null;
  12351. this._networkStream = networkStream;
  12352. this._fullReader = null;
  12353. this._lastProgress = null;
  12354. this.downloadInfoCapability = Promise.withResolvers();
  12355. this.setupMessageHandler();
  12356. }
  12357. #cacheSimpleMethod(name, data = null) {
  12358. const cachedPromise = this.#methodPromises.get(name);
  12359. if (cachedPromise) {
  12360. return cachedPromise;
  12361. }
  12362. const promise = this.messageHandler.sendWithPromise(name, data);
  12363. this.#methodPromises.set(name, promise);
  12364. return promise;
  12365. }
  12366. get annotationStorage() {
  12367. return shadow(this, "annotationStorage", new AnnotationStorage());
  12368. }
  12369. getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {
  12370. let renderingIntent = RenderingIntentFlag.DISPLAY;
  12371. let annotationStorageSerializable = SerializableEmpty;
  12372. switch (intent) {
  12373. case "any":
  12374. renderingIntent = RenderingIntentFlag.ANY;
  12375. break;
  12376. case "display":
  12377. break;
  12378. case "print":
  12379. renderingIntent = RenderingIntentFlag.PRINT;
  12380. break;
  12381. default:
  12382. warn(`getRenderingIntent - invalid intent: ${intent}`);
  12383. }
  12384. const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  12385. switch (annotationMode) {
  12386. case AnnotationMode.DISABLE:
  12387. renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
  12388. break;
  12389. case AnnotationMode.ENABLE:
  12390. break;
  12391. case AnnotationMode.ENABLE_FORMS:
  12392. renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
  12393. break;
  12394. case AnnotationMode.ENABLE_STORAGE:
  12395. renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
  12396. annotationStorageSerializable = annotationStorage.serializable;
  12397. break;
  12398. default:
  12399. warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  12400. }
  12401. if (isEditing) {
  12402. renderingIntent += RenderingIntentFlag.IS_EDITING;
  12403. }
  12404. if (isOpList) {
  12405. renderingIntent += RenderingIntentFlag.OPLIST;
  12406. }
  12407. const {
  12408. ids: modifiedIds,
  12409. hash: modifiedIdsHash
  12410. } = annotationStorage.modifiedIds;
  12411. const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];
  12412. return {
  12413. renderingIntent,
  12414. cacheKey: cacheKeyBuf.join("_"),
  12415. annotationStorageSerializable,
  12416. modifiedIds
  12417. };
  12418. }
  12419. destroy() {
  12420. if (this.destroyCapability) {
  12421. return this.destroyCapability.promise;
  12422. }
  12423. this.destroyed = true;
  12424. this.destroyCapability = Promise.withResolvers();
  12425. this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
  12426. const waitOn = [];
  12427. for (const page of this.#pageCache.values()) {
  12428. waitOn.push(page._destroy());
  12429. }
  12430. this.#pageCache.clear();
  12431. this.#pagePromises.clear();
  12432. this.#pageRefCache.clear();
  12433. if (this.hasOwnProperty("annotationStorage")) {
  12434. this.annotationStorage.resetModified();
  12435. }
  12436. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  12437. waitOn.push(terminated);
  12438. Promise.all(waitOn).then(() => {
  12439. this.commonObjs.clear();
  12440. this.fontLoader.clear();
  12441. this.#methodPromises.clear();
  12442. this.filterFactory.destroy();
  12443. TextLayer.cleanup();
  12444. this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
  12445. this.messageHandler?.destroy();
  12446. this.messageHandler = null;
  12447. this.destroyCapability.resolve();
  12448. }, this.destroyCapability.reject);
  12449. return this.destroyCapability.promise;
  12450. }
  12451. setupMessageHandler() {
  12452. const {
  12453. messageHandler,
  12454. loadingTask
  12455. } = this;
  12456. messageHandler.on("GetReader", (data, sink) => {
  12457. assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  12458. this._fullReader = this._networkStream.getFullReader();
  12459. this._fullReader.onProgress = evt => {
  12460. this._lastProgress = {
  12461. loaded: evt.loaded,
  12462. total: evt.total
  12463. };
  12464. };
  12465. sink.onPull = () => {
  12466. this._fullReader.read().then(function ({
  12467. value,
  12468. done
  12469. }) {
  12470. if (done) {
  12471. sink.close();
  12472. return;
  12473. }
  12474. assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
  12475. sink.enqueue(new Uint8Array(value), 1, [value]);
  12476. }).catch(reason => {
  12477. sink.error(reason);
  12478. });
  12479. };
  12480. sink.onCancel = reason => {
  12481. this._fullReader.cancel(reason);
  12482. sink.ready.catch(readyReason => {
  12483. if (this.destroyed) {
  12484. return;
  12485. }
  12486. throw readyReason;
  12487. });
  12488. };
  12489. });
  12490. messageHandler.on("ReaderHeadersReady", async data => {
  12491. await this._fullReader.headersReady;
  12492. const {
  12493. isStreamingSupported,
  12494. isRangeSupported,
  12495. contentLength
  12496. } = this._fullReader;
  12497. if (!isStreamingSupported || !isRangeSupported) {
  12498. if (this._lastProgress) {
  12499. loadingTask.onProgress?.(this._lastProgress);
  12500. }
  12501. this._fullReader.onProgress = evt => {
  12502. loadingTask.onProgress?.({
  12503. loaded: evt.loaded,
  12504. total: evt.total
  12505. });
  12506. };
  12507. }
  12508. return {
  12509. isStreamingSupported,
  12510. isRangeSupported,
  12511. contentLength
  12512. };
  12513. });
  12514. messageHandler.on("GetRangeReader", (data, sink) => {
  12515. assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  12516. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  12517. if (!rangeReader) {
  12518. sink.close();
  12519. return;
  12520. }
  12521. sink.onPull = () => {
  12522. rangeReader.read().then(function ({
  12523. value,
  12524. done
  12525. }) {
  12526. if (done) {
  12527. sink.close();
  12528. return;
  12529. }
  12530. assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
  12531. sink.enqueue(new Uint8Array(value), 1, [value]);
  12532. }).catch(reason => {
  12533. sink.error(reason);
  12534. });
  12535. };
  12536. sink.onCancel = reason => {
  12537. rangeReader.cancel(reason);
  12538. sink.ready.catch(readyReason => {
  12539. if (this.destroyed) {
  12540. return;
  12541. }
  12542. throw readyReason;
  12543. });
  12544. };
  12545. });
  12546. messageHandler.on("GetDoc", ({
  12547. pdfInfo
  12548. }) => {
  12549. this._numPages = pdfInfo.numPages;
  12550. this._htmlForXfa = pdfInfo.htmlForXfa;
  12551. delete pdfInfo.htmlForXfa;
  12552. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  12553. });
  12554. messageHandler.on("DocException", ex => {
  12555. loadingTask._capability.reject(wrapReason(ex));
  12556. });
  12557. messageHandler.on("PasswordRequest", ex => {
  12558. this.#passwordCapability = Promise.withResolvers();
  12559. try {
  12560. if (!loadingTask.onPassword) {
  12561. throw wrapReason(ex);
  12562. }
  12563. const updatePassword = password => {
  12564. if (password instanceof Error) {
  12565. this.#passwordCapability.reject(password);
  12566. } else {
  12567. this.#passwordCapability.resolve({
  12568. password
  12569. });
  12570. }
  12571. };
  12572. loadingTask.onPassword(updatePassword, ex.code);
  12573. } catch (err) {
  12574. this.#passwordCapability.reject(err);
  12575. }
  12576. return this.#passwordCapability.promise;
  12577. });
  12578. messageHandler.on("DataLoaded", data => {
  12579. loadingTask.onProgress?.({
  12580. loaded: data.length,
  12581. total: data.length
  12582. });
  12583. this.downloadInfoCapability.resolve(data);
  12584. });
  12585. messageHandler.on("StartRenderPage", data => {
  12586. if (this.destroyed) {
  12587. return;
  12588. }
  12589. const page = this.#pageCache.get(data.pageIndex);
  12590. page._startRenderPage(data.transparency, data.cacheKey);
  12591. });
  12592. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  12593. if (this.destroyed) {
  12594. return null;
  12595. }
  12596. if (this.commonObjs.has(id)) {
  12597. return null;
  12598. }
  12599. switch (type) {
  12600. case "Font":
  12601. const {
  12602. disableFontFace,
  12603. fontExtraProperties,
  12604. pdfBug
  12605. } = this._params;
  12606. if ("error" in exportedData) {
  12607. const exportedError = exportedData.error;
  12608. warn(`Error during font loading: ${exportedError}`);
  12609. this.commonObjs.resolve(id, exportedError);
  12610. break;
  12611. }
  12612. const inspectFont = pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
  12613. const font = new FontFaceObject(exportedData, {
  12614. disableFontFace,
  12615. fontExtraProperties,
  12616. inspectFont
  12617. });
  12618. this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
  12619. id
  12620. })).finally(() => {
  12621. if (!fontExtraProperties && font.data) {
  12622. font.data = null;
  12623. }
  12624. this.commonObjs.resolve(id, font);
  12625. });
  12626. break;
  12627. case "CopyLocalImage":
  12628. const {
  12629. imageRef
  12630. } = exportedData;
  12631. assert(imageRef, "The imageRef must be defined.");
  12632. for (const pageProxy of this.#pageCache.values()) {
  12633. for (const [, data] of pageProxy.objs) {
  12634. if (data?.ref !== imageRef) {
  12635. continue;
  12636. }
  12637. if (!data.dataLen) {
  12638. return null;
  12639. }
  12640. this.commonObjs.resolve(id, structuredClone(data));
  12641. return data.dataLen;
  12642. }
  12643. }
  12644. break;
  12645. case "FontPath":
  12646. case "Image":
  12647. case "Pattern":
  12648. this.commonObjs.resolve(id, exportedData);
  12649. break;
  12650. default:
  12651. throw new Error(`Got unknown common object type ${type}`);
  12652. }
  12653. return null;
  12654. });
  12655. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  12656. if (this.destroyed) {
  12657. return;
  12658. }
  12659. const pageProxy = this.#pageCache.get(pageIndex);
  12660. if (pageProxy.objs.has(id)) {
  12661. return;
  12662. }
  12663. if (pageProxy._intentStates.size === 0) {
  12664. imageData?.bitmap?.close();
  12665. return;
  12666. }
  12667. switch (type) {
  12668. case "Image":
  12669. pageProxy.objs.resolve(id, imageData);
  12670. if (imageData?.dataLen > MAX_IMAGE_SIZE_TO_CACHE) {
  12671. pageProxy._maybeCleanupAfterRender = true;
  12672. }
  12673. break;
  12674. case "Pattern":
  12675. pageProxy.objs.resolve(id, imageData);
  12676. break;
  12677. default:
  12678. throw new Error(`Got unknown object type ${type}`);
  12679. }
  12680. });
  12681. messageHandler.on("DocProgress", data => {
  12682. if (this.destroyed) {
  12683. return;
  12684. }
  12685. loadingTask.onProgress?.({
  12686. loaded: data.loaded,
  12687. total: data.total
  12688. });
  12689. });
  12690. messageHandler.on("FetchBuiltInCMap", async data => {
  12691. if (this.destroyed) {
  12692. throw new Error("Worker was destroyed.");
  12693. }
  12694. if (!this.cMapReaderFactory) {
  12695. throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");
  12696. }
  12697. return this.cMapReaderFactory.fetch(data);
  12698. });
  12699. messageHandler.on("FetchStandardFontData", async data => {
  12700. if (this.destroyed) {
  12701. throw new Error("Worker was destroyed.");
  12702. }
  12703. if (!this.standardFontDataFactory) {
  12704. throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");
  12705. }
  12706. return this.standardFontDataFactory.fetch(data);
  12707. });
  12708. }
  12709. getData() {
  12710. return this.messageHandler.sendWithPromise("GetData", null);
  12711. }
  12712. saveDocument() {
  12713. if (this.annotationStorage.size <= 0) {
  12714. warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  12715. }
  12716. const {
  12717. map,
  12718. transfer
  12719. } = this.annotationStorage.serializable;
  12720. return this.messageHandler.sendWithPromise("SaveDocument", {
  12721. isPureXfa: !!this._htmlForXfa,
  12722. numPages: this._numPages,
  12723. annotationStorage: map,
  12724. filename: this._fullReader?.filename ?? null
  12725. }, transfer).finally(() => {
  12726. this.annotationStorage.resetModified();
  12727. });
  12728. }
  12729. getPage(pageNumber) {
  12730. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  12731. return Promise.reject(new Error("Invalid page request."));
  12732. }
  12733. const pageIndex = pageNumber - 1,
  12734. cachedPromise = this.#pagePromises.get(pageIndex);
  12735. if (cachedPromise) {
  12736. return cachedPromise;
  12737. }
  12738. const promise = this.messageHandler.sendWithPromise("GetPage", {
  12739. pageIndex
  12740. }).then(pageInfo => {
  12741. if (this.destroyed) {
  12742. throw new Error("Transport destroyed");
  12743. }
  12744. if (pageInfo.refStr) {
  12745. this.#pageRefCache.set(pageInfo.refStr, pageNumber);
  12746. }
  12747. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
  12748. this.#pageCache.set(pageIndex, page);
  12749. return page;
  12750. });
  12751. this.#pagePromises.set(pageIndex, promise);
  12752. return promise;
  12753. }
  12754. getPageIndex(ref) {
  12755. if (!isRefProxy(ref)) {
  12756. return Promise.reject(new Error("Invalid pageIndex request."));
  12757. }
  12758. return this.messageHandler.sendWithPromise("GetPageIndex", {
  12759. num: ref.num,
  12760. gen: ref.gen
  12761. });
  12762. }
  12763. getAnnotations(pageIndex, intent) {
  12764. return this.messageHandler.sendWithPromise("GetAnnotations", {
  12765. pageIndex,
  12766. intent
  12767. });
  12768. }
  12769. getFieldObjects() {
  12770. return this.#cacheSimpleMethod("GetFieldObjects");
  12771. }
  12772. hasJSActions() {
  12773. return this.#cacheSimpleMethod("HasJSActions");
  12774. }
  12775. getCalculationOrderIds() {
  12776. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  12777. }
  12778. getDestinations() {
  12779. return this.messageHandler.sendWithPromise("GetDestinations", null);
  12780. }
  12781. getDestination(id) {
  12782. if (typeof id !== "string") {
  12783. return Promise.reject(new Error("Invalid destination request."));
  12784. }
  12785. return this.messageHandler.sendWithPromise("GetDestination", {
  12786. id
  12787. });
  12788. }
  12789. getPageLabels() {
  12790. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  12791. }
  12792. getPageLayout() {
  12793. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  12794. }
  12795. getPageMode() {
  12796. return this.messageHandler.sendWithPromise("GetPageMode", null);
  12797. }
  12798. getViewerPreferences() {
  12799. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  12800. }
  12801. getOpenAction() {
  12802. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  12803. }
  12804. getAttachments() {
  12805. return this.messageHandler.sendWithPromise("GetAttachments", null);
  12806. }
  12807. getDocJSActions() {
  12808. return this.#cacheSimpleMethod("GetDocJSActions");
  12809. }
  12810. getPageJSActions(pageIndex) {
  12811. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  12812. pageIndex
  12813. });
  12814. }
  12815. getStructTree(pageIndex) {
  12816. return this.messageHandler.sendWithPromise("GetStructTree", {
  12817. pageIndex
  12818. });
  12819. }
  12820. getOutline() {
  12821. return this.messageHandler.sendWithPromise("GetOutline", null);
  12822. }
  12823. getOptionalContentConfig(renderingIntent) {
  12824. return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent));
  12825. }
  12826. getPermissions() {
  12827. return this.messageHandler.sendWithPromise("GetPermissions", null);
  12828. }
  12829. getMetadata() {
  12830. const name = "GetMetadata",
  12831. cachedPromise = this.#methodPromises.get(name);
  12832. if (cachedPromise) {
  12833. return cachedPromise;
  12834. }
  12835. const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({
  12836. info: results[0],
  12837. metadata: results[1] ? new Metadata(results[1]) : null,
  12838. contentDispositionFilename: this._fullReader?.filename ?? null,
  12839. contentLength: this._fullReader?.contentLength ?? null
  12840. }));
  12841. this.#methodPromises.set(name, promise);
  12842. return promise;
  12843. }
  12844. getMarkInfo() {
  12845. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  12846. }
  12847. async startCleanup(keepLoadedFonts = false) {
  12848. if (this.destroyed) {
  12849. return;
  12850. }
  12851. await this.messageHandler.sendWithPromise("Cleanup", null);
  12852. for (const page of this.#pageCache.values()) {
  12853. const cleanupSuccessful = page.cleanup();
  12854. if (!cleanupSuccessful) {
  12855. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  12856. }
  12857. }
  12858. this.commonObjs.clear();
  12859. if (!keepLoadedFonts) {
  12860. this.fontLoader.clear();
  12861. }
  12862. this.#methodPromises.clear();
  12863. this.filterFactory.destroy(true);
  12864. TextLayer.cleanup();
  12865. }
  12866. cachedPageNumber(ref) {
  12867. if (!isRefProxy(ref)) {
  12868. return null;
  12869. }
  12870. const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
  12871. return this.#pageRefCache.get(refStr) ?? null;
  12872. }
  12873. }
  12874. const INITIAL_DATA = Symbol("INITIAL_DATA");
  12875. class PDFObjects {
  12876. #objs = Object.create(null);
  12877. #ensureObj(objId) {
  12878. return this.#objs[objId] ||= {
  12879. ...Promise.withResolvers(),
  12880. data: INITIAL_DATA
  12881. };
  12882. }
  12883. get(objId, callback = null) {
  12884. if (callback) {
  12885. const obj = this.#ensureObj(objId);
  12886. obj.promise.then(() => callback(obj.data));
  12887. return null;
  12888. }
  12889. const obj = this.#objs[objId];
  12890. if (!obj || obj.data === INITIAL_DATA) {
  12891. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  12892. }
  12893. return obj.data;
  12894. }
  12895. has(objId) {
  12896. const obj = this.#objs[objId];
  12897. return !!obj && obj.data !== INITIAL_DATA;
  12898. }
  12899. delete(objId) {
  12900. const obj = this.#objs[objId];
  12901. if (!obj || obj.data === INITIAL_DATA) {
  12902. return false;
  12903. }
  12904. delete this.#objs[objId];
  12905. return true;
  12906. }
  12907. resolve(objId, data = null) {
  12908. const obj = this.#ensureObj(objId);
  12909. obj.data = data;
  12910. obj.resolve();
  12911. }
  12912. clear() {
  12913. for (const objId in this.#objs) {
  12914. const {
  12915. data
  12916. } = this.#objs[objId];
  12917. data?.bitmap?.close();
  12918. }
  12919. this.#objs = Object.create(null);
  12920. }
  12921. *[Symbol.iterator]() {
  12922. for (const objId in this.#objs) {
  12923. const {
  12924. data
  12925. } = this.#objs[objId];
  12926. if (data === INITIAL_DATA) {
  12927. continue;
  12928. }
  12929. yield [objId, data];
  12930. }
  12931. }
  12932. }
  12933. class RenderTask {
  12934. #internalRenderTask = null;
  12935. constructor(internalRenderTask) {
  12936. this.#internalRenderTask = internalRenderTask;
  12937. this.onContinue = null;
  12938. }
  12939. get promise() {
  12940. return this.#internalRenderTask.capability.promise;
  12941. }
  12942. cancel(extraDelay = 0) {
  12943. this.#internalRenderTask.cancel(null, extraDelay);
  12944. }
  12945. get separateAnnots() {
  12946. const {
  12947. separateAnnots
  12948. } = this.#internalRenderTask.operatorList;
  12949. if (!separateAnnots) {
  12950. return false;
  12951. }
  12952. const {
  12953. annotationCanvasMap
  12954. } = this.#internalRenderTask;
  12955. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  12956. }
  12957. }
  12958. class InternalRenderTask {
  12959. #rAF = null;
  12960. static #canvasInUse = new WeakSet();
  12961. constructor({
  12962. callback,
  12963. params,
  12964. objs,
  12965. commonObjs,
  12966. annotationCanvasMap,
  12967. operatorList,
  12968. pageIndex,
  12969. canvasFactory,
  12970. filterFactory,
  12971. useRequestAnimationFrame = false,
  12972. pdfBug = false,
  12973. pageColors = null
  12974. }) {
  12975. this.callback = callback;
  12976. this.params = params;
  12977. this.objs = objs;
  12978. this.commonObjs = commonObjs;
  12979. this.annotationCanvasMap = annotationCanvasMap;
  12980. this.operatorListIdx = null;
  12981. this.operatorList = operatorList;
  12982. this._pageIndex = pageIndex;
  12983. this.canvasFactory = canvasFactory;
  12984. this.filterFactory = filterFactory;
  12985. this._pdfBug = pdfBug;
  12986. this.pageColors = pageColors;
  12987. this.running = false;
  12988. this.graphicsReadyCallback = null;
  12989. this.graphicsReady = false;
  12990. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  12991. this.cancelled = false;
  12992. this.capability = Promise.withResolvers();
  12993. this.task = new RenderTask(this);
  12994. this._cancelBound = this.cancel.bind(this);
  12995. this._continueBound = this._continue.bind(this);
  12996. this._scheduleNextBound = this._scheduleNext.bind(this);
  12997. this._nextBound = this._next.bind(this);
  12998. this._canvas = params.canvasContext.canvas;
  12999. }
  13000. get completed() {
  13001. return this.capability.promise.catch(function () {});
  13002. }
  13003. initializeGraphics({
  13004. transparency = false,
  13005. optionalContentConfig
  13006. }) {
  13007. if (this.cancelled) {
  13008. return;
  13009. }
  13010. if (this._canvas) {
  13011. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  13012. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  13013. }
  13014. InternalRenderTask.#canvasInUse.add(this._canvas);
  13015. }
  13016. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  13017. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  13018. this.stepper.init(this.operatorList);
  13019. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  13020. }
  13021. const {
  13022. canvasContext,
  13023. viewport,
  13024. transform,
  13025. background
  13026. } = this.params;
  13027. this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  13028. optionalContentConfig
  13029. }, this.annotationCanvasMap, this.pageColors);
  13030. this.gfx.beginDrawing({
  13031. transform,
  13032. viewport,
  13033. transparency,
  13034. background
  13035. });
  13036. this.operatorListIdx = 0;
  13037. this.graphicsReady = true;
  13038. this.graphicsReadyCallback?.();
  13039. }
  13040. cancel(error = null, extraDelay = 0) {
  13041. this.running = false;
  13042. this.cancelled = true;
  13043. this.gfx?.endDrawing();
  13044. if (this.#rAF) {
  13045. window.cancelAnimationFrame(this.#rAF);
  13046. this.#rAF = null;
  13047. }
  13048. InternalRenderTask.#canvasInUse.delete(this._canvas);
  13049. this.callback(error || new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay));
  13050. }
  13051. operatorListChanged() {
  13052. if (!this.graphicsReady) {
  13053. this.graphicsReadyCallback ||= this._continueBound;
  13054. return;
  13055. }
  13056. this.stepper?.updateOperatorList(this.operatorList);
  13057. if (this.running) {
  13058. return;
  13059. }
  13060. this._continue();
  13061. }
  13062. _continue() {
  13063. this.running = true;
  13064. if (this.cancelled) {
  13065. return;
  13066. }
  13067. if (this.task.onContinue) {
  13068. this.task.onContinue(this._scheduleNextBound);
  13069. } else {
  13070. this._scheduleNext();
  13071. }
  13072. }
  13073. _scheduleNext() {
  13074. if (this._useRequestAnimationFrame) {
  13075. this.#rAF = window.requestAnimationFrame(() => {
  13076. this.#rAF = null;
  13077. this._nextBound().catch(this._cancelBound);
  13078. });
  13079. } else {
  13080. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  13081. }
  13082. }
  13083. async _next() {
  13084. if (this.cancelled) {
  13085. return;
  13086. }
  13087. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  13088. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  13089. this.running = false;
  13090. if (this.operatorList.lastChunk) {
  13091. this.gfx.endDrawing();
  13092. InternalRenderTask.#canvasInUse.delete(this._canvas);
  13093. this.callback();
  13094. }
  13095. }
  13096. }
  13097. }
  13098. const version = "4.10.38";
  13099. const build = "f9bea397f";
  13100. ;// ./src/shared/scripting_utils.js
  13101. function makeColorComp(n) {
  13102. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  13103. }
  13104. function scaleAndClamp(x) {
  13105. return Math.max(0, Math.min(255, 255 * x));
  13106. }
  13107. class ColorConverters {
  13108. static CMYK_G([c, y, m, k]) {
  13109. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  13110. }
  13111. static G_CMYK([g]) {
  13112. return ["CMYK", 0, 0, 0, 1 - g];
  13113. }
  13114. static G_RGB([g]) {
  13115. return ["RGB", g, g, g];
  13116. }
  13117. static G_rgb([g]) {
  13118. g = scaleAndClamp(g);
  13119. return [g, g, g];
  13120. }
  13121. static G_HTML([g]) {
  13122. const G = makeColorComp(g);
  13123. return `#${G}${G}${G}`;
  13124. }
  13125. static RGB_G([r, g, b]) {
  13126. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  13127. }
  13128. static RGB_rgb(color) {
  13129. return color.map(scaleAndClamp);
  13130. }
  13131. static RGB_HTML(color) {
  13132. return `#${color.map(makeColorComp).join("")}`;
  13133. }
  13134. static T_HTML() {
  13135. return "#00000000";
  13136. }
  13137. static T_rgb() {
  13138. return [null];
  13139. }
  13140. static CMYK_RGB([c, y, m, k]) {
  13141. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  13142. }
  13143. static CMYK_rgb([c, y, m, k]) {
  13144. return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
  13145. }
  13146. static CMYK_HTML(components) {
  13147. const rgb = this.CMYK_RGB(components).slice(1);
  13148. return this.RGB_HTML(rgb);
  13149. }
  13150. static RGB_CMYK([r, g, b]) {
  13151. const c = 1 - r;
  13152. const m = 1 - g;
  13153. const y = 1 - b;
  13154. const k = Math.min(c, m, y);
  13155. return ["CMYK", c, m, y, k];
  13156. }
  13157. }
  13158. ;// ./src/display/svg_factory.js
  13159. class BaseSVGFactory {
  13160. create(width, height, skipDimensions = false) {
  13161. if (width <= 0 || height <= 0) {
  13162. throw new Error("Invalid SVG dimensions");
  13163. }
  13164. const svg = this._createSVG("svg:svg");
  13165. svg.setAttribute("version", "1.1");
  13166. if (!skipDimensions) {
  13167. svg.setAttribute("width", `${width}px`);
  13168. svg.setAttribute("height", `${height}px`);
  13169. }
  13170. svg.setAttribute("preserveAspectRatio", "none");
  13171. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  13172. return svg;
  13173. }
  13174. createElement(type) {
  13175. if (typeof type !== "string") {
  13176. throw new Error("Invalid SVG element type");
  13177. }
  13178. return this._createSVG(type);
  13179. }
  13180. _createSVG(type) {
  13181. unreachable("Abstract method `_createSVG` called.");
  13182. }
  13183. }
  13184. class DOMSVGFactory extends BaseSVGFactory {
  13185. _createSVG(type) {
  13186. return document.createElementNS(SVG_NS, type);
  13187. }
  13188. }
  13189. ;// ./src/display/xfa_layer.js
  13190. class XfaLayer {
  13191. static setupStorage(html, id, element, storage, intent) {
  13192. const storedData = storage.getValue(id, {
  13193. value: null
  13194. });
  13195. switch (element.name) {
  13196. case "textarea":
  13197. if (storedData.value !== null) {
  13198. html.textContent = storedData.value;
  13199. }
  13200. if (intent === "print") {
  13201. break;
  13202. }
  13203. html.addEventListener("input", event => {
  13204. storage.setValue(id, {
  13205. value: event.target.value
  13206. });
  13207. });
  13208. break;
  13209. case "input":
  13210. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  13211. if (storedData.value === element.attributes.xfaOn) {
  13212. html.setAttribute("checked", true);
  13213. } else if (storedData.value === element.attributes.xfaOff) {
  13214. html.removeAttribute("checked");
  13215. }
  13216. if (intent === "print") {
  13217. break;
  13218. }
  13219. html.addEventListener("change", event => {
  13220. storage.setValue(id, {
  13221. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  13222. });
  13223. });
  13224. } else {
  13225. if (storedData.value !== null) {
  13226. html.setAttribute("value", storedData.value);
  13227. }
  13228. if (intent === "print") {
  13229. break;
  13230. }
  13231. html.addEventListener("input", event => {
  13232. storage.setValue(id, {
  13233. value: event.target.value
  13234. });
  13235. });
  13236. }
  13237. break;
  13238. case "select":
  13239. if (storedData.value !== null) {
  13240. html.setAttribute("value", storedData.value);
  13241. for (const option of element.children) {
  13242. if (option.attributes.value === storedData.value) {
  13243. option.attributes.selected = true;
  13244. } else if (option.attributes.hasOwnProperty("selected")) {
  13245. delete option.attributes.selected;
  13246. }
  13247. }
  13248. }
  13249. html.addEventListener("input", event => {
  13250. const options = event.target.options;
  13251. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  13252. storage.setValue(id, {
  13253. value
  13254. });
  13255. });
  13256. break;
  13257. }
  13258. }
  13259. static setAttributes({
  13260. html,
  13261. element,
  13262. storage = null,
  13263. intent,
  13264. linkService
  13265. }) {
  13266. const {
  13267. attributes
  13268. } = element;
  13269. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  13270. if (attributes.type === "radio") {
  13271. attributes.name = `${attributes.name}-${intent}`;
  13272. }
  13273. for (const [key, value] of Object.entries(attributes)) {
  13274. if (value === null || value === undefined) {
  13275. continue;
  13276. }
  13277. switch (key) {
  13278. case "class":
  13279. if (value.length) {
  13280. html.setAttribute(key, value.join(" "));
  13281. }
  13282. break;
  13283. case "dataId":
  13284. break;
  13285. case "id":
  13286. html.setAttribute("data-element-id", value);
  13287. break;
  13288. case "style":
  13289. Object.assign(html.style, value);
  13290. break;
  13291. case "textContent":
  13292. html.textContent = value;
  13293. break;
  13294. default:
  13295. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  13296. html.setAttribute(key, value);
  13297. }
  13298. }
  13299. }
  13300. if (isHTMLAnchorElement) {
  13301. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  13302. }
  13303. if (storage && attributes.dataId) {
  13304. this.setupStorage(html, attributes.dataId, element, storage);
  13305. }
  13306. }
  13307. static render(parameters) {
  13308. const storage = parameters.annotationStorage;
  13309. const linkService = parameters.linkService;
  13310. const root = parameters.xfaHtml;
  13311. const intent = parameters.intent || "display";
  13312. const rootHtml = document.createElement(root.name);
  13313. if (root.attributes) {
  13314. this.setAttributes({
  13315. html: rootHtml,
  13316. element: root,
  13317. intent,
  13318. linkService
  13319. });
  13320. }
  13321. const isNotForRichText = intent !== "richText";
  13322. const rootDiv = parameters.div;
  13323. rootDiv.append(rootHtml);
  13324. if (parameters.viewport) {
  13325. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  13326. rootDiv.style.transform = transform;
  13327. }
  13328. if (isNotForRichText) {
  13329. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  13330. }
  13331. const textDivs = [];
  13332. if (root.children.length === 0) {
  13333. if (root.value) {
  13334. const node = document.createTextNode(root.value);
  13335. rootHtml.append(node);
  13336. if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
  13337. textDivs.push(node);
  13338. }
  13339. }
  13340. return {
  13341. textDivs
  13342. };
  13343. }
  13344. const stack = [[root, -1, rootHtml]];
  13345. while (stack.length > 0) {
  13346. const [parent, i, html] = stack.at(-1);
  13347. if (i + 1 === parent.children.length) {
  13348. stack.pop();
  13349. continue;
  13350. }
  13351. const child = parent.children[++stack.at(-1)[1]];
  13352. if (child === null) {
  13353. continue;
  13354. }
  13355. const {
  13356. name
  13357. } = child;
  13358. if (name === "#text") {
  13359. const node = document.createTextNode(child.value);
  13360. textDivs.push(node);
  13361. html.append(node);
  13362. continue;
  13363. }
  13364. const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
  13365. html.append(childHtml);
  13366. if (child.attributes) {
  13367. this.setAttributes({
  13368. html: childHtml,
  13369. element: child,
  13370. storage,
  13371. intent,
  13372. linkService
  13373. });
  13374. }
  13375. if (child.children?.length > 0) {
  13376. stack.push([child, -1, childHtml]);
  13377. } else if (child.value) {
  13378. const node = document.createTextNode(child.value);
  13379. if (isNotForRichText && XfaText.shouldBuildText(name)) {
  13380. textDivs.push(node);
  13381. }
  13382. childHtml.append(node);
  13383. }
  13384. }
  13385. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  13386. el.setAttribute("readOnly", true);
  13387. }
  13388. return {
  13389. textDivs
  13390. };
  13391. }
  13392. static update(parameters) {
  13393. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  13394. parameters.div.style.transform = transform;
  13395. parameters.div.hidden = false;
  13396. }
  13397. }
  13398. ;// ./src/display/annotation_layer.js
  13399. const DEFAULT_TAB_INDEX = 1000;
  13400. const annotation_layer_DEFAULT_FONT_SIZE = 9;
  13401. const GetElementsByNameSet = new WeakSet();
  13402. function getRectDims(rect) {
  13403. return {
  13404. width: rect[2] - rect[0],
  13405. height: rect[3] - rect[1]
  13406. };
  13407. }
  13408. class AnnotationElementFactory {
  13409. static create(parameters) {
  13410. const subtype = parameters.data.annotationType;
  13411. switch (subtype) {
  13412. case AnnotationType.LINK:
  13413. return new LinkAnnotationElement(parameters);
  13414. case AnnotationType.TEXT:
  13415. return new TextAnnotationElement(parameters);
  13416. case AnnotationType.WIDGET:
  13417. const fieldType = parameters.data.fieldType;
  13418. switch (fieldType) {
  13419. case "Tx":
  13420. return new TextWidgetAnnotationElement(parameters);
  13421. case "Btn":
  13422. if (parameters.data.radioButton) {
  13423. return new RadioButtonWidgetAnnotationElement(parameters);
  13424. } else if (parameters.data.checkBox) {
  13425. return new CheckboxWidgetAnnotationElement(parameters);
  13426. }
  13427. return new PushButtonWidgetAnnotationElement(parameters);
  13428. case "Ch":
  13429. return new ChoiceWidgetAnnotationElement(parameters);
  13430. case "Sig":
  13431. return new SignatureWidgetAnnotationElement(parameters);
  13432. }
  13433. return new WidgetAnnotationElement(parameters);
  13434. case AnnotationType.POPUP:
  13435. return new PopupAnnotationElement(parameters);
  13436. case AnnotationType.FREETEXT:
  13437. return new FreeTextAnnotationElement(parameters);
  13438. case AnnotationType.LINE:
  13439. return new LineAnnotationElement(parameters);
  13440. case AnnotationType.SQUARE:
  13441. return new SquareAnnotationElement(parameters);
  13442. case AnnotationType.CIRCLE:
  13443. return new CircleAnnotationElement(parameters);
  13444. case AnnotationType.POLYLINE:
  13445. return new PolylineAnnotationElement(parameters);
  13446. case AnnotationType.CARET:
  13447. return new CaretAnnotationElement(parameters);
  13448. case AnnotationType.INK:
  13449. return new InkAnnotationElement(parameters);
  13450. case AnnotationType.POLYGON:
  13451. return new PolygonAnnotationElement(parameters);
  13452. case AnnotationType.HIGHLIGHT:
  13453. return new HighlightAnnotationElement(parameters);
  13454. case AnnotationType.UNDERLINE:
  13455. return new UnderlineAnnotationElement(parameters);
  13456. case AnnotationType.SQUIGGLY:
  13457. return new SquigglyAnnotationElement(parameters);
  13458. case AnnotationType.STRIKEOUT:
  13459. return new StrikeOutAnnotationElement(parameters);
  13460. case AnnotationType.STAMP:
  13461. return new StampAnnotationElement(parameters);
  13462. case AnnotationType.FILEATTACHMENT:
  13463. return new FileAttachmentAnnotationElement(parameters);
  13464. default:
  13465. return new AnnotationElement(parameters);
  13466. }
  13467. }
  13468. }
  13469. class AnnotationElement {
  13470. #updates = null;
  13471. #hasBorder = false;
  13472. #popupElement = null;
  13473. constructor(parameters, {
  13474. isRenderable = false,
  13475. ignoreBorder = false,
  13476. createQuadrilaterals = false
  13477. } = {}) {
  13478. this.isRenderable = isRenderable;
  13479. this.data = parameters.data;
  13480. this.layer = parameters.layer;
  13481. this.linkService = parameters.linkService;
  13482. this.downloadManager = parameters.downloadManager;
  13483. this.imageResourcesPath = parameters.imageResourcesPath;
  13484. this.renderForms = parameters.renderForms;
  13485. this.svgFactory = parameters.svgFactory;
  13486. this.annotationStorage = parameters.annotationStorage;
  13487. this.enableScripting = parameters.enableScripting;
  13488. this.hasJSActions = parameters.hasJSActions;
  13489. this._fieldObjects = parameters.fieldObjects;
  13490. this.parent = parameters.parent;
  13491. if (isRenderable) {
  13492. this.container = this._createContainer(ignoreBorder);
  13493. }
  13494. if (createQuadrilaterals) {
  13495. this._createQuadrilaterals();
  13496. }
  13497. }
  13498. static _hasPopupData({
  13499. titleObj,
  13500. contentsObj,
  13501. richText
  13502. }) {
  13503. return !!(titleObj?.str || contentsObj?.str || richText?.str);
  13504. }
  13505. get _isEditable() {
  13506. return this.data.isEditable;
  13507. }
  13508. get hasPopupData() {
  13509. return AnnotationElement._hasPopupData(this.data);
  13510. }
  13511. updateEdited(params) {
  13512. if (!this.container) {
  13513. return;
  13514. }
  13515. this.#updates ||= {
  13516. rect: this.data.rect.slice(0)
  13517. };
  13518. const {
  13519. rect
  13520. } = params;
  13521. if (rect) {
  13522. this.#setRectEdited(rect);
  13523. }
  13524. this.#popupElement?.popup.updateEdited(params);
  13525. }
  13526. resetEdited() {
  13527. if (!this.#updates) {
  13528. return;
  13529. }
  13530. this.#setRectEdited(this.#updates.rect);
  13531. this.#popupElement?.popup.resetEdited();
  13532. this.#updates = null;
  13533. }
  13534. #setRectEdited(rect) {
  13535. const {
  13536. container: {
  13537. style
  13538. },
  13539. data: {
  13540. rect: currentRect,
  13541. rotation
  13542. },
  13543. parent: {
  13544. viewport: {
  13545. rawDims: {
  13546. pageWidth,
  13547. pageHeight,
  13548. pageX,
  13549. pageY
  13550. }
  13551. }
  13552. }
  13553. } = this;
  13554. currentRect?.splice(0, 4, ...rect);
  13555. const {
  13556. width,
  13557. height
  13558. } = getRectDims(rect);
  13559. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  13560. style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
  13561. if (rotation === 0) {
  13562. style.width = `${100 * width / pageWidth}%`;
  13563. style.height = `${100 * height / pageHeight}%`;
  13564. } else {
  13565. this.setRotation(rotation);
  13566. }
  13567. }
  13568. _createContainer(ignoreBorder) {
  13569. const {
  13570. data,
  13571. parent: {
  13572. page,
  13573. viewport
  13574. }
  13575. } = this;
  13576. const container = document.createElement("section");
  13577. container.setAttribute("data-annotation-id", data.id);
  13578. if (!(this instanceof WidgetAnnotationElement)) {
  13579. container.tabIndex = DEFAULT_TAB_INDEX;
  13580. }
  13581. const {
  13582. style
  13583. } = container;
  13584. style.zIndex = this.parent.zIndex++;
  13585. if (data.alternativeText) {
  13586. container.title = data.alternativeText;
  13587. }
  13588. if (data.noRotate) {
  13589. container.classList.add("norotate");
  13590. }
  13591. if (!data.rect || this instanceof PopupAnnotationElement) {
  13592. const {
  13593. rotation
  13594. } = data;
  13595. if (!data.hasOwnCanvas && rotation !== 0) {
  13596. this.setRotation(rotation, container);
  13597. }
  13598. return container;
  13599. }
  13600. const {
  13601. width,
  13602. height
  13603. } = getRectDims(data.rect);
  13604. if (!ignoreBorder && data.borderStyle.width > 0) {
  13605. style.borderWidth = `${data.borderStyle.width}px`;
  13606. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  13607. const verticalRadius = data.borderStyle.verticalCornerRadius;
  13608. if (horizontalRadius > 0 || verticalRadius > 0) {
  13609. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  13610. style.borderRadius = radius;
  13611. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  13612. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  13613. style.borderRadius = radius;
  13614. }
  13615. switch (data.borderStyle.style) {
  13616. case AnnotationBorderStyleType.SOLID:
  13617. style.borderStyle = "solid";
  13618. break;
  13619. case AnnotationBorderStyleType.DASHED:
  13620. style.borderStyle = "dashed";
  13621. break;
  13622. case AnnotationBorderStyleType.BEVELED:
  13623. warn("Unimplemented border style: beveled");
  13624. break;
  13625. case AnnotationBorderStyleType.INSET:
  13626. warn("Unimplemented border style: inset");
  13627. break;
  13628. case AnnotationBorderStyleType.UNDERLINE:
  13629. style.borderBottomStyle = "solid";
  13630. break;
  13631. default:
  13632. break;
  13633. }
  13634. const borderColor = data.borderColor || null;
  13635. if (borderColor) {
  13636. this.#hasBorder = true;
  13637. style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  13638. } else {
  13639. style.borderWidth = 0;
  13640. }
  13641. }
  13642. 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]]);
  13643. const {
  13644. pageWidth,
  13645. pageHeight,
  13646. pageX,
  13647. pageY
  13648. } = viewport.rawDims;
  13649. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  13650. style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
  13651. const {
  13652. rotation
  13653. } = data;
  13654. if (data.hasOwnCanvas || rotation === 0) {
  13655. style.width = `${100 * width / pageWidth}%`;
  13656. style.height = `${100 * height / pageHeight}%`;
  13657. } else {
  13658. this.setRotation(rotation, container);
  13659. }
  13660. return container;
  13661. }
  13662. setRotation(angle, container = this.container) {
  13663. if (!this.data.rect) {
  13664. return;
  13665. }
  13666. const {
  13667. pageWidth,
  13668. pageHeight
  13669. } = this.parent.viewport.rawDims;
  13670. const {
  13671. width,
  13672. height
  13673. } = getRectDims(this.data.rect);
  13674. let elementWidth, elementHeight;
  13675. if (angle % 180 === 0) {
  13676. elementWidth = 100 * width / pageWidth;
  13677. elementHeight = 100 * height / pageHeight;
  13678. } else {
  13679. elementWidth = 100 * height / pageWidth;
  13680. elementHeight = 100 * width / pageHeight;
  13681. }
  13682. container.style.width = `${elementWidth}%`;
  13683. container.style.height = `${elementHeight}%`;
  13684. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  13685. }
  13686. get _commonActions() {
  13687. const setColor = (jsName, styleName, event) => {
  13688. const color = event.detail[jsName];
  13689. const colorType = color[0];
  13690. const colorArray = color.slice(1);
  13691. event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
  13692. this.annotationStorage.setValue(this.data.id, {
  13693. [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
  13694. });
  13695. };
  13696. return shadow(this, "_commonActions", {
  13697. display: event => {
  13698. const {
  13699. display
  13700. } = event.detail;
  13701. const hidden = display % 2 === 1;
  13702. this.container.style.visibility = hidden ? "hidden" : "visible";
  13703. this.annotationStorage.setValue(this.data.id, {
  13704. noView: hidden,
  13705. noPrint: display === 1 || display === 2
  13706. });
  13707. },
  13708. print: event => {
  13709. this.annotationStorage.setValue(this.data.id, {
  13710. noPrint: !event.detail.print
  13711. });
  13712. },
  13713. hidden: event => {
  13714. const {
  13715. hidden
  13716. } = event.detail;
  13717. this.container.style.visibility = hidden ? "hidden" : "visible";
  13718. this.annotationStorage.setValue(this.data.id, {
  13719. noPrint: hidden,
  13720. noView: hidden
  13721. });
  13722. },
  13723. focus: event => {
  13724. setTimeout(() => event.target.focus({
  13725. preventScroll: false
  13726. }), 0);
  13727. },
  13728. userName: event => {
  13729. event.target.title = event.detail.userName;
  13730. },
  13731. readonly: event => {
  13732. event.target.disabled = event.detail.readonly;
  13733. },
  13734. required: event => {
  13735. this._setRequired(event.target, event.detail.required);
  13736. },
  13737. bgColor: event => {
  13738. setColor("bgColor", "backgroundColor", event);
  13739. },
  13740. fillColor: event => {
  13741. setColor("fillColor", "backgroundColor", event);
  13742. },
  13743. fgColor: event => {
  13744. setColor("fgColor", "color", event);
  13745. },
  13746. textColor: event => {
  13747. setColor("textColor", "color", event);
  13748. },
  13749. borderColor: event => {
  13750. setColor("borderColor", "borderColor", event);
  13751. },
  13752. strokeColor: event => {
  13753. setColor("strokeColor", "borderColor", event);
  13754. },
  13755. rotation: event => {
  13756. const angle = event.detail.rotation;
  13757. this.setRotation(angle);
  13758. this.annotationStorage.setValue(this.data.id, {
  13759. rotation: angle
  13760. });
  13761. }
  13762. });
  13763. }
  13764. _dispatchEventFromSandbox(actions, jsEvent) {
  13765. const commonActions = this._commonActions;
  13766. for (const name of Object.keys(jsEvent.detail)) {
  13767. const action = actions[name] || commonActions[name];
  13768. action?.(jsEvent);
  13769. }
  13770. }
  13771. _setDefaultPropertiesFromJS(element) {
  13772. if (!this.enableScripting) {
  13773. return;
  13774. }
  13775. const storedData = this.annotationStorage.getRawValue(this.data.id);
  13776. if (!storedData) {
  13777. return;
  13778. }
  13779. const commonActions = this._commonActions;
  13780. for (const [actionName, detail] of Object.entries(storedData)) {
  13781. const action = commonActions[actionName];
  13782. if (action) {
  13783. const eventProxy = {
  13784. detail: {
  13785. [actionName]: detail
  13786. },
  13787. target: element
  13788. };
  13789. action(eventProxy);
  13790. delete storedData[actionName];
  13791. }
  13792. }
  13793. }
  13794. _createQuadrilaterals() {
  13795. if (!this.container) {
  13796. return;
  13797. }
  13798. const {
  13799. quadPoints
  13800. } = this.data;
  13801. if (!quadPoints) {
  13802. return;
  13803. }
  13804. const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x));
  13805. if (quadPoints.length === 8) {
  13806. const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);
  13807. if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
  13808. return;
  13809. }
  13810. }
  13811. const {
  13812. style
  13813. } = this.container;
  13814. let svgBuffer;
  13815. if (this.#hasBorder) {
  13816. const {
  13817. borderColor,
  13818. borderWidth
  13819. } = style;
  13820. style.borderWidth = 0;
  13821. 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}">`];
  13822. this.container.classList.add("hasBorder");
  13823. }
  13824. const width = rectTrX - rectBlX;
  13825. const height = rectTrY - rectBlY;
  13826. const {
  13827. svgFactory
  13828. } = this;
  13829. const svg = svgFactory.createElement("svg");
  13830. svg.classList.add("quadrilateralsContainer");
  13831. svg.setAttribute("width", 0);
  13832. svg.setAttribute("height", 0);
  13833. const defs = svgFactory.createElement("defs");
  13834. svg.append(defs);
  13835. const clipPath = svgFactory.createElement("clipPath");
  13836. const id = `clippath_${this.data.id}`;
  13837. clipPath.setAttribute("id", id);
  13838. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  13839. defs.append(clipPath);
  13840. for (let i = 2, ii = quadPoints.length; i < ii; i += 8) {
  13841. const trX = quadPoints[i];
  13842. const trY = quadPoints[i + 1];
  13843. const blX = quadPoints[i + 2];
  13844. const blY = quadPoints[i + 3];
  13845. const rect = svgFactory.createElement("rect");
  13846. const x = (blX - rectBlX) / width;
  13847. const y = (rectTrY - trY) / height;
  13848. const rectWidth = (trX - blX) / width;
  13849. const rectHeight = (trY - blY) / height;
  13850. rect.setAttribute("x", x);
  13851. rect.setAttribute("y", y);
  13852. rect.setAttribute("width", rectWidth);
  13853. rect.setAttribute("height", rectHeight);
  13854. clipPath.append(rect);
  13855. svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);
  13856. }
  13857. if (this.#hasBorder) {
  13858. svgBuffer.push(`</g></svg>')`);
  13859. style.backgroundImage = svgBuffer.join("");
  13860. }
  13861. this.container.append(svg);
  13862. this.container.style.clipPath = `url(#${id})`;
  13863. }
  13864. _createPopup() {
  13865. const {
  13866. data
  13867. } = this;
  13868. const popup = this.#popupElement = new PopupAnnotationElement({
  13869. data: {
  13870. color: data.color,
  13871. titleObj: data.titleObj,
  13872. modificationDate: data.modificationDate,
  13873. contentsObj: data.contentsObj,
  13874. richText: data.richText,
  13875. parentRect: data.rect,
  13876. borderStyle: 0,
  13877. id: `popup_${data.id}`,
  13878. rotation: data.rotation
  13879. },
  13880. parent: this.parent,
  13881. elements: [this]
  13882. });
  13883. this.parent.div.append(popup.render());
  13884. }
  13885. render() {
  13886. unreachable("Abstract method `AnnotationElement.render` called");
  13887. }
  13888. _getElementsByName(name, skipId = null) {
  13889. const fields = [];
  13890. if (this._fieldObjects) {
  13891. const fieldObj = this._fieldObjects[name];
  13892. if (fieldObj) {
  13893. for (const {
  13894. page,
  13895. id,
  13896. exportValues
  13897. } of fieldObj) {
  13898. if (page === -1) {
  13899. continue;
  13900. }
  13901. if (id === skipId) {
  13902. continue;
  13903. }
  13904. const exportValue = typeof exportValues === "string" ? exportValues : null;
  13905. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  13906. if (domElement && !GetElementsByNameSet.has(domElement)) {
  13907. warn(`_getElementsByName - element not allowed: ${id}`);
  13908. continue;
  13909. }
  13910. fields.push({
  13911. id,
  13912. exportValue,
  13913. domElement
  13914. });
  13915. }
  13916. }
  13917. return fields;
  13918. }
  13919. for (const domElement of document.getElementsByName(name)) {
  13920. const {
  13921. exportValue
  13922. } = domElement;
  13923. const id = domElement.getAttribute("data-element-id");
  13924. if (id === skipId) {
  13925. continue;
  13926. }
  13927. if (!GetElementsByNameSet.has(domElement)) {
  13928. continue;
  13929. }
  13930. fields.push({
  13931. id,
  13932. exportValue,
  13933. domElement
  13934. });
  13935. }
  13936. return fields;
  13937. }
  13938. show() {
  13939. if (this.container) {
  13940. this.container.hidden = false;
  13941. }
  13942. this.popup?.maybeShow();
  13943. }
  13944. hide() {
  13945. if (this.container) {
  13946. this.container.hidden = true;
  13947. }
  13948. this.popup?.forceHide();
  13949. }
  13950. getElementsToTriggerPopup() {
  13951. return this.container;
  13952. }
  13953. addHighlightArea() {
  13954. const triggers = this.getElementsToTriggerPopup();
  13955. if (Array.isArray(triggers)) {
  13956. for (const element of triggers) {
  13957. element.classList.add("highlightArea");
  13958. }
  13959. } else {
  13960. triggers.classList.add("highlightArea");
  13961. }
  13962. }
  13963. _editOnDoubleClick() {
  13964. if (!this._isEditable) {
  13965. return;
  13966. }
  13967. const {
  13968. annotationEditorType: mode,
  13969. data: {
  13970. id: editId
  13971. }
  13972. } = this;
  13973. this.container.addEventListener("dblclick", () => {
  13974. this.linkService.eventBus?.dispatch("switchannotationeditormode", {
  13975. source: this,
  13976. mode,
  13977. editId
  13978. });
  13979. });
  13980. }
  13981. }
  13982. class LinkAnnotationElement extends AnnotationElement {
  13983. constructor(parameters, options = null) {
  13984. super(parameters, {
  13985. isRenderable: true,
  13986. ignoreBorder: !!options?.ignoreBorder,
  13987. createQuadrilaterals: true
  13988. });
  13989. this.isTooltipOnly = parameters.data.isTooltipOnly;
  13990. }
  13991. render() {
  13992. const {
  13993. data,
  13994. linkService
  13995. } = this;
  13996. const link = document.createElement("a");
  13997. link.setAttribute("data-element-id", data.id);
  13998. let isBound = false;
  13999. if (data.url) {
  14000. linkService.addLinkAttributes(link, data.url, data.newWindow);
  14001. isBound = true;
  14002. } else if (data.action) {
  14003. this._bindNamedAction(link, data.action);
  14004. isBound = true;
  14005. } else if (data.attachment) {
  14006. this.#bindAttachment(link, data.attachment, data.attachmentDest);
  14007. isBound = true;
  14008. } else if (data.setOCGState) {
  14009. this.#bindSetOCGState(link, data.setOCGState);
  14010. isBound = true;
  14011. } else if (data.dest) {
  14012. this._bindLink(link, data.dest);
  14013. isBound = true;
  14014. } else {
  14015. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  14016. this._bindJSAction(link, data);
  14017. isBound = true;
  14018. }
  14019. if (data.resetForm) {
  14020. this._bindResetFormAction(link, data.resetForm);
  14021. isBound = true;
  14022. } else if (this.isTooltipOnly && !isBound) {
  14023. this._bindLink(link, "");
  14024. isBound = true;
  14025. }
  14026. }
  14027. this.container.classList.add("linkAnnotation");
  14028. if (isBound) {
  14029. this.container.append(link);
  14030. }
  14031. return this.container;
  14032. }
  14033. #setInternalLink() {
  14034. this.container.setAttribute("data-internal-link", "");
  14035. }
  14036. _bindLink(link, destination) {
  14037. link.href = this.linkService.getDestinationHash(destination);
  14038. link.onclick = () => {
  14039. if (destination) {
  14040. this.linkService.goToDestination(destination);
  14041. }
  14042. return false;
  14043. };
  14044. if (destination || destination === "") {
  14045. this.#setInternalLink();
  14046. }
  14047. }
  14048. _bindNamedAction(link, action) {
  14049. link.href = this.linkService.getAnchorUrl("");
  14050. link.onclick = () => {
  14051. this.linkService.executeNamedAction(action);
  14052. return false;
  14053. };
  14054. this.#setInternalLink();
  14055. }
  14056. #bindAttachment(link, attachment, dest = null) {
  14057. link.href = this.linkService.getAnchorUrl("");
  14058. if (attachment.description) {
  14059. link.title = attachment.description;
  14060. }
  14061. link.onclick = () => {
  14062. this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
  14063. return false;
  14064. };
  14065. this.#setInternalLink();
  14066. }
  14067. #bindSetOCGState(link, action) {
  14068. link.href = this.linkService.getAnchorUrl("");
  14069. link.onclick = () => {
  14070. this.linkService.executeSetOCGState(action);
  14071. return false;
  14072. };
  14073. this.#setInternalLink();
  14074. }
  14075. _bindJSAction(link, data) {
  14076. link.href = this.linkService.getAnchorUrl("");
  14077. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  14078. for (const name of Object.keys(data.actions)) {
  14079. const jsName = map.get(name);
  14080. if (!jsName) {
  14081. continue;
  14082. }
  14083. link[jsName] = () => {
  14084. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14085. source: this,
  14086. detail: {
  14087. id: data.id,
  14088. name
  14089. }
  14090. });
  14091. return false;
  14092. };
  14093. }
  14094. if (!link.onclick) {
  14095. link.onclick = () => false;
  14096. }
  14097. this.#setInternalLink();
  14098. }
  14099. _bindResetFormAction(link, resetForm) {
  14100. const otherClickAction = link.onclick;
  14101. if (!otherClickAction) {
  14102. link.href = this.linkService.getAnchorUrl("");
  14103. }
  14104. this.#setInternalLink();
  14105. if (!this._fieldObjects) {
  14106. warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  14107. if (!otherClickAction) {
  14108. link.onclick = () => false;
  14109. }
  14110. return;
  14111. }
  14112. link.onclick = () => {
  14113. otherClickAction?.();
  14114. const {
  14115. fields: resetFormFields,
  14116. refs: resetFormRefs,
  14117. include
  14118. } = resetForm;
  14119. const allFields = [];
  14120. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  14121. const fieldIds = new Set(resetFormRefs);
  14122. for (const fieldName of resetFormFields) {
  14123. const fields = this._fieldObjects[fieldName] || [];
  14124. for (const {
  14125. id
  14126. } of fields) {
  14127. fieldIds.add(id);
  14128. }
  14129. }
  14130. for (const fields of Object.values(this._fieldObjects)) {
  14131. for (const field of fields) {
  14132. if (fieldIds.has(field.id) === include) {
  14133. allFields.push(field);
  14134. }
  14135. }
  14136. }
  14137. } else {
  14138. for (const fields of Object.values(this._fieldObjects)) {
  14139. allFields.push(...fields);
  14140. }
  14141. }
  14142. const storage = this.annotationStorage;
  14143. const allIds = [];
  14144. for (const field of allFields) {
  14145. const {
  14146. id
  14147. } = field;
  14148. allIds.push(id);
  14149. switch (field.type) {
  14150. case "text":
  14151. {
  14152. const value = field.defaultValue || "";
  14153. storage.setValue(id, {
  14154. value
  14155. });
  14156. break;
  14157. }
  14158. case "checkbox":
  14159. case "radiobutton":
  14160. {
  14161. const value = field.defaultValue === field.exportValues;
  14162. storage.setValue(id, {
  14163. value
  14164. });
  14165. break;
  14166. }
  14167. case "combobox":
  14168. case "listbox":
  14169. {
  14170. const value = field.defaultValue || "";
  14171. storage.setValue(id, {
  14172. value
  14173. });
  14174. break;
  14175. }
  14176. default:
  14177. continue;
  14178. }
  14179. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  14180. if (!domElement) {
  14181. continue;
  14182. } else if (!GetElementsByNameSet.has(domElement)) {
  14183. warn(`_bindResetFormAction - element not allowed: ${id}`);
  14184. continue;
  14185. }
  14186. domElement.dispatchEvent(new Event("resetform"));
  14187. }
  14188. if (this.enableScripting) {
  14189. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14190. source: this,
  14191. detail: {
  14192. id: "app",
  14193. ids: allIds,
  14194. name: "ResetForm"
  14195. }
  14196. });
  14197. }
  14198. return false;
  14199. };
  14200. }
  14201. }
  14202. class TextAnnotationElement extends AnnotationElement {
  14203. constructor(parameters) {
  14204. super(parameters, {
  14205. isRenderable: true
  14206. });
  14207. }
  14208. render() {
  14209. this.container.classList.add("textAnnotation");
  14210. const image = document.createElement("img");
  14211. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  14212. image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
  14213. image.setAttribute("data-l10n-args", JSON.stringify({
  14214. type: this.data.name
  14215. }));
  14216. if (!this.data.popupRef && this.hasPopupData) {
  14217. this._createPopup();
  14218. }
  14219. this.container.append(image);
  14220. return this.container;
  14221. }
  14222. }
  14223. class WidgetAnnotationElement extends AnnotationElement {
  14224. render() {
  14225. return this.container;
  14226. }
  14227. showElementAndHideCanvas(element) {
  14228. if (this.data.hasOwnCanvas) {
  14229. if (element.previousSibling?.nodeName === "CANVAS") {
  14230. element.previousSibling.hidden = true;
  14231. }
  14232. element.hidden = false;
  14233. }
  14234. }
  14235. _getKeyModifier(event) {
  14236. return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
  14237. }
  14238. _setEventListener(element, elementData, baseName, eventName, valueGetter) {
  14239. if (baseName.includes("mouse")) {
  14240. element.addEventListener(baseName, event => {
  14241. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14242. source: this,
  14243. detail: {
  14244. id: this.data.id,
  14245. name: eventName,
  14246. value: valueGetter(event),
  14247. shift: event.shiftKey,
  14248. modifier: this._getKeyModifier(event)
  14249. }
  14250. });
  14251. });
  14252. } else {
  14253. element.addEventListener(baseName, event => {
  14254. if (baseName === "blur") {
  14255. if (!elementData.focused || !event.relatedTarget) {
  14256. return;
  14257. }
  14258. elementData.focused = false;
  14259. } else if (baseName === "focus") {
  14260. if (elementData.focused) {
  14261. return;
  14262. }
  14263. elementData.focused = true;
  14264. }
  14265. if (!valueGetter) {
  14266. return;
  14267. }
  14268. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14269. source: this,
  14270. detail: {
  14271. id: this.data.id,
  14272. name: eventName,
  14273. value: valueGetter(event)
  14274. }
  14275. });
  14276. });
  14277. }
  14278. }
  14279. _setEventListeners(element, elementData, names, getter) {
  14280. for (const [baseName, eventName] of names) {
  14281. if (eventName === "Action" || this.data.actions?.[eventName]) {
  14282. if (eventName === "Focus" || eventName === "Blur") {
  14283. elementData ||= {
  14284. focused: false
  14285. };
  14286. }
  14287. this._setEventListener(element, elementData, baseName, eventName, getter);
  14288. if (eventName === "Focus" && !this.data.actions?.Blur) {
  14289. this._setEventListener(element, elementData, "blur", "Blur", null);
  14290. } else if (eventName === "Blur" && !this.data.actions?.Focus) {
  14291. this._setEventListener(element, elementData, "focus", "Focus", null);
  14292. }
  14293. }
  14294. }
  14295. }
  14296. _setBackgroundColor(element) {
  14297. const color = this.data.backgroundColor || null;
  14298. element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);
  14299. }
  14300. _setTextStyle(element) {
  14301. const TEXT_ALIGNMENT = ["left", "center", "right"];
  14302. const {
  14303. fontColor
  14304. } = this.data.defaultAppearanceData;
  14305. const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
  14306. const style = element.style;
  14307. let computedFontSize;
  14308. const BORDER_SIZE = 2;
  14309. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  14310. if (this.data.multiLine) {
  14311. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  14312. const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
  14313. const lineHeight = height / numberOfLines;
  14314. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
  14315. } else {
  14316. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  14317. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
  14318. }
  14319. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  14320. style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  14321. if (this.data.textAlignment !== null) {
  14322. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  14323. }
  14324. }
  14325. _setRequired(element, isRequired) {
  14326. if (isRequired) {
  14327. element.setAttribute("required", true);
  14328. } else {
  14329. element.removeAttribute("required");
  14330. }
  14331. element.setAttribute("aria-required", isRequired);
  14332. }
  14333. }
  14334. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  14335. constructor(parameters) {
  14336. const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  14337. super(parameters, {
  14338. isRenderable
  14339. });
  14340. }
  14341. setPropertyOnSiblings(base, key, value, keyInStorage) {
  14342. const storage = this.annotationStorage;
  14343. for (const element of this._getElementsByName(base.name, base.id)) {
  14344. if (element.domElement) {
  14345. element.domElement[key] = value;
  14346. }
  14347. storage.setValue(element.id, {
  14348. [keyInStorage]: value
  14349. });
  14350. }
  14351. }
  14352. render() {
  14353. const storage = this.annotationStorage;
  14354. const id = this.data.id;
  14355. this.container.classList.add("textWidgetAnnotation");
  14356. let element = null;
  14357. if (this.renderForms) {
  14358. const storedData = storage.getValue(id, {
  14359. value: this.data.fieldValue
  14360. });
  14361. let textContent = storedData.value || "";
  14362. const maxLen = storage.getValue(id, {
  14363. charLimit: this.data.maxLen
  14364. }).charLimit;
  14365. if (maxLen && textContent.length > maxLen) {
  14366. textContent = textContent.slice(0, maxLen);
  14367. }
  14368. let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
  14369. if (fieldFormattedValues && this.data.comb) {
  14370. fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
  14371. }
  14372. const elementData = {
  14373. userValue: textContent,
  14374. formattedValue: fieldFormattedValues,
  14375. lastCommittedValue: null,
  14376. commitKey: 1,
  14377. focused: false
  14378. };
  14379. if (this.data.multiLine) {
  14380. element = document.createElement("textarea");
  14381. element.textContent = fieldFormattedValues ?? textContent;
  14382. if (this.data.doNotScroll) {
  14383. element.style.overflowY = "hidden";
  14384. }
  14385. } else {
  14386. element = document.createElement("input");
  14387. element.type = "text";
  14388. element.setAttribute("value", fieldFormattedValues ?? textContent);
  14389. if (this.data.doNotScroll) {
  14390. element.style.overflowX = "hidden";
  14391. }
  14392. }
  14393. if (this.data.hasOwnCanvas) {
  14394. element.hidden = true;
  14395. }
  14396. GetElementsByNameSet.add(element);
  14397. element.setAttribute("data-element-id", id);
  14398. element.disabled = this.data.readOnly;
  14399. element.name = this.data.fieldName;
  14400. element.tabIndex = DEFAULT_TAB_INDEX;
  14401. this._setRequired(element, this.data.required);
  14402. if (maxLen) {
  14403. element.maxLength = maxLen;
  14404. }
  14405. element.addEventListener("input", event => {
  14406. storage.setValue(id, {
  14407. value: event.target.value
  14408. });
  14409. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  14410. elementData.formattedValue = null;
  14411. });
  14412. element.addEventListener("resetform", event => {
  14413. const defaultValue = this.data.defaultFieldValue ?? "";
  14414. element.value = elementData.userValue = defaultValue;
  14415. elementData.formattedValue = null;
  14416. });
  14417. let blurListener = event => {
  14418. const {
  14419. formattedValue
  14420. } = elementData;
  14421. if (formattedValue !== null && formattedValue !== undefined) {
  14422. event.target.value = formattedValue;
  14423. }
  14424. event.target.scrollLeft = 0;
  14425. };
  14426. if (this.enableScripting && this.hasJSActions) {
  14427. element.addEventListener("focus", event => {
  14428. if (elementData.focused) {
  14429. return;
  14430. }
  14431. const {
  14432. target
  14433. } = event;
  14434. if (elementData.userValue) {
  14435. target.value = elementData.userValue;
  14436. }
  14437. elementData.lastCommittedValue = target.value;
  14438. elementData.commitKey = 1;
  14439. if (!this.data.actions?.Focus) {
  14440. elementData.focused = true;
  14441. }
  14442. });
  14443. element.addEventListener("updatefromsandbox", jsEvent => {
  14444. this.showElementAndHideCanvas(jsEvent.target);
  14445. const actions = {
  14446. value(event) {
  14447. elementData.userValue = event.detail.value ?? "";
  14448. storage.setValue(id, {
  14449. value: elementData.userValue.toString()
  14450. });
  14451. event.target.value = elementData.userValue;
  14452. },
  14453. formattedValue(event) {
  14454. const {
  14455. formattedValue
  14456. } = event.detail;
  14457. elementData.formattedValue = formattedValue;
  14458. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  14459. event.target.value = formattedValue;
  14460. }
  14461. storage.setValue(id, {
  14462. formattedValue
  14463. });
  14464. },
  14465. selRange(event) {
  14466. event.target.setSelectionRange(...event.detail.selRange);
  14467. },
  14468. charLimit: event => {
  14469. const {
  14470. charLimit
  14471. } = event.detail;
  14472. const {
  14473. target
  14474. } = event;
  14475. if (charLimit === 0) {
  14476. target.removeAttribute("maxLength");
  14477. return;
  14478. }
  14479. target.setAttribute("maxLength", charLimit);
  14480. let value = elementData.userValue;
  14481. if (!value || value.length <= charLimit) {
  14482. return;
  14483. }
  14484. value = value.slice(0, charLimit);
  14485. target.value = elementData.userValue = value;
  14486. storage.setValue(id, {
  14487. value
  14488. });
  14489. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14490. source: this,
  14491. detail: {
  14492. id,
  14493. name: "Keystroke",
  14494. value,
  14495. willCommit: true,
  14496. commitKey: 1,
  14497. selStart: target.selectionStart,
  14498. selEnd: target.selectionEnd
  14499. }
  14500. });
  14501. }
  14502. };
  14503. this._dispatchEventFromSandbox(actions, jsEvent);
  14504. });
  14505. element.addEventListener("keydown", event => {
  14506. elementData.commitKey = 1;
  14507. let commitKey = -1;
  14508. if (event.key === "Escape") {
  14509. commitKey = 0;
  14510. } else if (event.key === "Enter" && !this.data.multiLine) {
  14511. commitKey = 2;
  14512. } else if (event.key === "Tab") {
  14513. elementData.commitKey = 3;
  14514. }
  14515. if (commitKey === -1) {
  14516. return;
  14517. }
  14518. const {
  14519. value
  14520. } = event.target;
  14521. if (elementData.lastCommittedValue === value) {
  14522. return;
  14523. }
  14524. elementData.lastCommittedValue = value;
  14525. elementData.userValue = value;
  14526. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14527. source: this,
  14528. detail: {
  14529. id,
  14530. name: "Keystroke",
  14531. value,
  14532. willCommit: true,
  14533. commitKey,
  14534. selStart: event.target.selectionStart,
  14535. selEnd: event.target.selectionEnd
  14536. }
  14537. });
  14538. });
  14539. const _blurListener = blurListener;
  14540. blurListener = null;
  14541. element.addEventListener("blur", event => {
  14542. if (!elementData.focused || !event.relatedTarget) {
  14543. return;
  14544. }
  14545. if (!this.data.actions?.Blur) {
  14546. elementData.focused = false;
  14547. }
  14548. const {
  14549. value
  14550. } = event.target;
  14551. elementData.userValue = value;
  14552. if (elementData.lastCommittedValue !== value) {
  14553. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14554. source: this,
  14555. detail: {
  14556. id,
  14557. name: "Keystroke",
  14558. value,
  14559. willCommit: true,
  14560. commitKey: elementData.commitKey,
  14561. selStart: event.target.selectionStart,
  14562. selEnd: event.target.selectionEnd
  14563. }
  14564. });
  14565. }
  14566. _blurListener(event);
  14567. });
  14568. if (this.data.actions?.Keystroke) {
  14569. element.addEventListener("beforeinput", event => {
  14570. elementData.lastCommittedValue = null;
  14571. const {
  14572. data,
  14573. target
  14574. } = event;
  14575. const {
  14576. value,
  14577. selectionStart,
  14578. selectionEnd
  14579. } = target;
  14580. let selStart = selectionStart,
  14581. selEnd = selectionEnd;
  14582. switch (event.inputType) {
  14583. case "deleteWordBackward":
  14584. {
  14585. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  14586. if (match) {
  14587. selStart -= match[0].length;
  14588. }
  14589. break;
  14590. }
  14591. case "deleteWordForward":
  14592. {
  14593. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  14594. if (match) {
  14595. selEnd += match[0].length;
  14596. }
  14597. break;
  14598. }
  14599. case "deleteContentBackward":
  14600. if (selectionStart === selectionEnd) {
  14601. selStart -= 1;
  14602. }
  14603. break;
  14604. case "deleteContentForward":
  14605. if (selectionStart === selectionEnd) {
  14606. selEnd += 1;
  14607. }
  14608. break;
  14609. }
  14610. event.preventDefault();
  14611. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14612. source: this,
  14613. detail: {
  14614. id,
  14615. name: "Keystroke",
  14616. value,
  14617. change: data || "",
  14618. willCommit: false,
  14619. selStart,
  14620. selEnd
  14621. }
  14622. });
  14623. });
  14624. }
  14625. this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  14626. }
  14627. if (blurListener) {
  14628. element.addEventListener("blur", blurListener);
  14629. }
  14630. if (this.data.comb) {
  14631. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  14632. const combWidth = fieldWidth / maxLen;
  14633. element.classList.add("comb");
  14634. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  14635. }
  14636. } else {
  14637. element = document.createElement("div");
  14638. element.textContent = this.data.fieldValue;
  14639. element.style.verticalAlign = "middle";
  14640. element.style.display = "table-cell";
  14641. if (this.data.hasOwnCanvas) {
  14642. element.hidden = true;
  14643. }
  14644. }
  14645. this._setTextStyle(element);
  14646. this._setBackgroundColor(element);
  14647. this._setDefaultPropertiesFromJS(element);
  14648. this.container.append(element);
  14649. return this.container;
  14650. }
  14651. }
  14652. class SignatureWidgetAnnotationElement extends WidgetAnnotationElement {
  14653. constructor(parameters) {
  14654. super(parameters, {
  14655. isRenderable: !!parameters.data.hasOwnCanvas
  14656. });
  14657. }
  14658. }
  14659. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  14660. constructor(parameters) {
  14661. super(parameters, {
  14662. isRenderable: parameters.renderForms
  14663. });
  14664. }
  14665. render() {
  14666. const storage = this.annotationStorage;
  14667. const data = this.data;
  14668. const id = data.id;
  14669. let value = storage.getValue(id, {
  14670. value: data.exportValue === data.fieldValue
  14671. }).value;
  14672. if (typeof value === "string") {
  14673. value = value !== "Off";
  14674. storage.setValue(id, {
  14675. value
  14676. });
  14677. }
  14678. this.container.classList.add("buttonWidgetAnnotation", "checkBox");
  14679. const element = document.createElement("input");
  14680. GetElementsByNameSet.add(element);
  14681. element.setAttribute("data-element-id", id);
  14682. element.disabled = data.readOnly;
  14683. this._setRequired(element, this.data.required);
  14684. element.type = "checkbox";
  14685. element.name = data.fieldName;
  14686. if (value) {
  14687. element.setAttribute("checked", true);
  14688. }
  14689. element.setAttribute("exportValue", data.exportValue);
  14690. element.tabIndex = DEFAULT_TAB_INDEX;
  14691. element.addEventListener("change", event => {
  14692. const {
  14693. name,
  14694. checked
  14695. } = event.target;
  14696. for (const checkbox of this._getElementsByName(name, id)) {
  14697. const curChecked = checked && checkbox.exportValue === data.exportValue;
  14698. if (checkbox.domElement) {
  14699. checkbox.domElement.checked = curChecked;
  14700. }
  14701. storage.setValue(checkbox.id, {
  14702. value: curChecked
  14703. });
  14704. }
  14705. storage.setValue(id, {
  14706. value: checked
  14707. });
  14708. });
  14709. element.addEventListener("resetform", event => {
  14710. const defaultValue = data.defaultFieldValue || "Off";
  14711. event.target.checked = defaultValue === data.exportValue;
  14712. });
  14713. if (this.enableScripting && this.hasJSActions) {
  14714. element.addEventListener("updatefromsandbox", jsEvent => {
  14715. const actions = {
  14716. value(event) {
  14717. event.target.checked = event.detail.value !== "Off";
  14718. storage.setValue(id, {
  14719. value: event.target.checked
  14720. });
  14721. }
  14722. };
  14723. this._dispatchEventFromSandbox(actions, jsEvent);
  14724. });
  14725. 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);
  14726. }
  14727. this._setBackgroundColor(element);
  14728. this._setDefaultPropertiesFromJS(element);
  14729. this.container.append(element);
  14730. return this.container;
  14731. }
  14732. }
  14733. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  14734. constructor(parameters) {
  14735. super(parameters, {
  14736. isRenderable: parameters.renderForms
  14737. });
  14738. }
  14739. render() {
  14740. this.container.classList.add("buttonWidgetAnnotation", "radioButton");
  14741. const storage = this.annotationStorage;
  14742. const data = this.data;
  14743. const id = data.id;
  14744. let value = storage.getValue(id, {
  14745. value: data.fieldValue === data.buttonValue
  14746. }).value;
  14747. if (typeof value === "string") {
  14748. value = value !== data.buttonValue;
  14749. storage.setValue(id, {
  14750. value
  14751. });
  14752. }
  14753. if (value) {
  14754. for (const radio of this._getElementsByName(data.fieldName, id)) {
  14755. storage.setValue(radio.id, {
  14756. value: false
  14757. });
  14758. }
  14759. }
  14760. const element = document.createElement("input");
  14761. GetElementsByNameSet.add(element);
  14762. element.setAttribute("data-element-id", id);
  14763. element.disabled = data.readOnly;
  14764. this._setRequired(element, this.data.required);
  14765. element.type = "radio";
  14766. element.name = data.fieldName;
  14767. if (value) {
  14768. element.setAttribute("checked", true);
  14769. }
  14770. element.tabIndex = DEFAULT_TAB_INDEX;
  14771. element.addEventListener("change", event => {
  14772. const {
  14773. name,
  14774. checked
  14775. } = event.target;
  14776. for (const radio of this._getElementsByName(name, id)) {
  14777. storage.setValue(radio.id, {
  14778. value: false
  14779. });
  14780. }
  14781. storage.setValue(id, {
  14782. value: checked
  14783. });
  14784. });
  14785. element.addEventListener("resetform", event => {
  14786. const defaultValue = data.defaultFieldValue;
  14787. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  14788. });
  14789. if (this.enableScripting && this.hasJSActions) {
  14790. const pdfButtonValue = data.buttonValue;
  14791. element.addEventListener("updatefromsandbox", jsEvent => {
  14792. const actions = {
  14793. value: event => {
  14794. const checked = pdfButtonValue === event.detail.value;
  14795. for (const radio of this._getElementsByName(event.target.name)) {
  14796. const curChecked = checked && radio.id === id;
  14797. if (radio.domElement) {
  14798. radio.domElement.checked = curChecked;
  14799. }
  14800. storage.setValue(radio.id, {
  14801. value: curChecked
  14802. });
  14803. }
  14804. }
  14805. };
  14806. this._dispatchEventFromSandbox(actions, jsEvent);
  14807. });
  14808. 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);
  14809. }
  14810. this._setBackgroundColor(element);
  14811. this._setDefaultPropertiesFromJS(element);
  14812. this.container.append(element);
  14813. return this.container;
  14814. }
  14815. }
  14816. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  14817. constructor(parameters) {
  14818. super(parameters, {
  14819. ignoreBorder: parameters.data.hasAppearance
  14820. });
  14821. }
  14822. render() {
  14823. const container = super.render();
  14824. container.classList.add("buttonWidgetAnnotation", "pushButton");
  14825. const linkElement = container.lastChild;
  14826. if (this.enableScripting && this.hasJSActions && linkElement) {
  14827. this._setDefaultPropertiesFromJS(linkElement);
  14828. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  14829. this._dispatchEventFromSandbox({}, jsEvent);
  14830. });
  14831. }
  14832. return container;
  14833. }
  14834. }
  14835. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  14836. constructor(parameters) {
  14837. super(parameters, {
  14838. isRenderable: parameters.renderForms
  14839. });
  14840. }
  14841. render() {
  14842. this.container.classList.add("choiceWidgetAnnotation");
  14843. const storage = this.annotationStorage;
  14844. const id = this.data.id;
  14845. const storedData = storage.getValue(id, {
  14846. value: this.data.fieldValue
  14847. });
  14848. const selectElement = document.createElement("select");
  14849. GetElementsByNameSet.add(selectElement);
  14850. selectElement.setAttribute("data-element-id", id);
  14851. selectElement.disabled = this.data.readOnly;
  14852. this._setRequired(selectElement, this.data.required);
  14853. selectElement.name = this.data.fieldName;
  14854. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  14855. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  14856. if (!this.data.combo) {
  14857. selectElement.size = this.data.options.length;
  14858. if (this.data.multiSelect) {
  14859. selectElement.multiple = true;
  14860. }
  14861. }
  14862. selectElement.addEventListener("resetform", event => {
  14863. const defaultValue = this.data.defaultFieldValue;
  14864. for (const option of selectElement.options) {
  14865. option.selected = option.value === defaultValue;
  14866. }
  14867. });
  14868. for (const option of this.data.options) {
  14869. const optionElement = document.createElement("option");
  14870. optionElement.textContent = option.displayValue;
  14871. optionElement.value = option.exportValue;
  14872. if (storedData.value.includes(option.exportValue)) {
  14873. optionElement.setAttribute("selected", true);
  14874. addAnEmptyEntry = false;
  14875. }
  14876. selectElement.append(optionElement);
  14877. }
  14878. let removeEmptyEntry = null;
  14879. if (addAnEmptyEntry) {
  14880. const noneOptionElement = document.createElement("option");
  14881. noneOptionElement.value = " ";
  14882. noneOptionElement.setAttribute("hidden", true);
  14883. noneOptionElement.setAttribute("selected", true);
  14884. selectElement.prepend(noneOptionElement);
  14885. removeEmptyEntry = () => {
  14886. noneOptionElement.remove();
  14887. selectElement.removeEventListener("input", removeEmptyEntry);
  14888. removeEmptyEntry = null;
  14889. };
  14890. selectElement.addEventListener("input", removeEmptyEntry);
  14891. }
  14892. const getValue = isExport => {
  14893. const name = isExport ? "value" : "textContent";
  14894. const {
  14895. options,
  14896. multiple
  14897. } = selectElement;
  14898. if (!multiple) {
  14899. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  14900. }
  14901. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  14902. };
  14903. let selectedValues = getValue(false);
  14904. const getItems = event => {
  14905. const options = event.target.options;
  14906. return Array.prototype.map.call(options, option => ({
  14907. displayValue: option.textContent,
  14908. exportValue: option.value
  14909. }));
  14910. };
  14911. if (this.enableScripting && this.hasJSActions) {
  14912. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  14913. const actions = {
  14914. value(event) {
  14915. removeEmptyEntry?.();
  14916. const value = event.detail.value;
  14917. const values = new Set(Array.isArray(value) ? value : [value]);
  14918. for (const option of selectElement.options) {
  14919. option.selected = values.has(option.value);
  14920. }
  14921. storage.setValue(id, {
  14922. value: getValue(true)
  14923. });
  14924. selectedValues = getValue(false);
  14925. },
  14926. multipleSelection(event) {
  14927. selectElement.multiple = true;
  14928. },
  14929. remove(event) {
  14930. const options = selectElement.options;
  14931. const index = event.detail.remove;
  14932. options[index].selected = false;
  14933. selectElement.remove(index);
  14934. if (options.length > 0) {
  14935. const i = Array.prototype.findIndex.call(options, option => option.selected);
  14936. if (i === -1) {
  14937. options[0].selected = true;
  14938. }
  14939. }
  14940. storage.setValue(id, {
  14941. value: getValue(true),
  14942. items: getItems(event)
  14943. });
  14944. selectedValues = getValue(false);
  14945. },
  14946. clear(event) {
  14947. while (selectElement.length !== 0) {
  14948. selectElement.remove(0);
  14949. }
  14950. storage.setValue(id, {
  14951. value: null,
  14952. items: []
  14953. });
  14954. selectedValues = getValue(false);
  14955. },
  14956. insert(event) {
  14957. const {
  14958. index,
  14959. displayValue,
  14960. exportValue
  14961. } = event.detail.insert;
  14962. const selectChild = selectElement.children[index];
  14963. const optionElement = document.createElement("option");
  14964. optionElement.textContent = displayValue;
  14965. optionElement.value = exportValue;
  14966. if (selectChild) {
  14967. selectChild.before(optionElement);
  14968. } else {
  14969. selectElement.append(optionElement);
  14970. }
  14971. storage.setValue(id, {
  14972. value: getValue(true),
  14973. items: getItems(event)
  14974. });
  14975. selectedValues = getValue(false);
  14976. },
  14977. items(event) {
  14978. const {
  14979. items
  14980. } = event.detail;
  14981. while (selectElement.length !== 0) {
  14982. selectElement.remove(0);
  14983. }
  14984. for (const item of items) {
  14985. const {
  14986. displayValue,
  14987. exportValue
  14988. } = item;
  14989. const optionElement = document.createElement("option");
  14990. optionElement.textContent = displayValue;
  14991. optionElement.value = exportValue;
  14992. selectElement.append(optionElement);
  14993. }
  14994. if (selectElement.options.length > 0) {
  14995. selectElement.options[0].selected = true;
  14996. }
  14997. storage.setValue(id, {
  14998. value: getValue(true),
  14999. items: getItems(event)
  15000. });
  15001. selectedValues = getValue(false);
  15002. },
  15003. indices(event) {
  15004. const indices = new Set(event.detail.indices);
  15005. for (const option of event.target.options) {
  15006. option.selected = indices.has(option.index);
  15007. }
  15008. storage.setValue(id, {
  15009. value: getValue(true)
  15010. });
  15011. selectedValues = getValue(false);
  15012. },
  15013. editable(event) {
  15014. event.target.disabled = !event.detail.editable;
  15015. }
  15016. };
  15017. this._dispatchEventFromSandbox(actions, jsEvent);
  15018. });
  15019. selectElement.addEventListener("input", event => {
  15020. const exportValue = getValue(true);
  15021. const change = getValue(false);
  15022. storage.setValue(id, {
  15023. value: exportValue
  15024. });
  15025. event.preventDefault();
  15026. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  15027. source: this,
  15028. detail: {
  15029. id,
  15030. name: "Keystroke",
  15031. value: selectedValues,
  15032. change,
  15033. changeEx: exportValue,
  15034. willCommit: false,
  15035. commitKey: 1,
  15036. keyDown: false
  15037. }
  15038. });
  15039. });
  15040. 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);
  15041. } else {
  15042. selectElement.addEventListener("input", function (event) {
  15043. storage.setValue(id, {
  15044. value: getValue(true)
  15045. });
  15046. });
  15047. }
  15048. if (this.data.combo) {
  15049. this._setTextStyle(selectElement);
  15050. } else {}
  15051. this._setBackgroundColor(selectElement);
  15052. this._setDefaultPropertiesFromJS(selectElement);
  15053. this.container.append(selectElement);
  15054. return this.container;
  15055. }
  15056. }
  15057. class PopupAnnotationElement extends AnnotationElement {
  15058. constructor(parameters) {
  15059. const {
  15060. data,
  15061. elements
  15062. } = parameters;
  15063. super(parameters, {
  15064. isRenderable: AnnotationElement._hasPopupData(data)
  15065. });
  15066. this.elements = elements;
  15067. this.popup = null;
  15068. }
  15069. render() {
  15070. this.container.classList.add("popupAnnotation");
  15071. const popup = this.popup = new PopupElement({
  15072. container: this.container,
  15073. color: this.data.color,
  15074. titleObj: this.data.titleObj,
  15075. modificationDate: this.data.modificationDate,
  15076. contentsObj: this.data.contentsObj,
  15077. richText: this.data.richText,
  15078. rect: this.data.rect,
  15079. parentRect: this.data.parentRect || null,
  15080. parent: this.parent,
  15081. elements: this.elements,
  15082. open: this.data.open
  15083. });
  15084. const elementIds = [];
  15085. for (const element of this.elements) {
  15086. element.popup = popup;
  15087. element.container.ariaHasPopup = "dialog";
  15088. elementIds.push(element.data.id);
  15089. element.addHighlightArea();
  15090. }
  15091. this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(","));
  15092. return this.container;
  15093. }
  15094. }
  15095. class PopupElement {
  15096. #boundKeyDown = this.#keyDown.bind(this);
  15097. #boundHide = this.#hide.bind(this);
  15098. #boundShow = this.#show.bind(this);
  15099. #boundToggle = this.#toggle.bind(this);
  15100. #color = null;
  15101. #container = null;
  15102. #contentsObj = null;
  15103. #dateObj = null;
  15104. #elements = null;
  15105. #parent = null;
  15106. #parentRect = null;
  15107. #pinned = false;
  15108. #popup = null;
  15109. #position = null;
  15110. #rect = null;
  15111. #richText = null;
  15112. #titleObj = null;
  15113. #updates = null;
  15114. #wasVisible = false;
  15115. constructor({
  15116. container,
  15117. color,
  15118. elements,
  15119. titleObj,
  15120. modificationDate,
  15121. contentsObj,
  15122. richText,
  15123. parent,
  15124. rect,
  15125. parentRect,
  15126. open
  15127. }) {
  15128. this.#container = container;
  15129. this.#titleObj = titleObj;
  15130. this.#contentsObj = contentsObj;
  15131. this.#richText = richText;
  15132. this.#parent = parent;
  15133. this.#color = color;
  15134. this.#rect = rect;
  15135. this.#parentRect = parentRect;
  15136. this.#elements = elements;
  15137. this.#dateObj = PDFDateString.toDateObject(modificationDate);
  15138. this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());
  15139. for (const element of this.trigger) {
  15140. element.addEventListener("click", this.#boundToggle);
  15141. element.addEventListener("mouseenter", this.#boundShow);
  15142. element.addEventListener("mouseleave", this.#boundHide);
  15143. element.classList.add("popupTriggerArea");
  15144. }
  15145. for (const element of elements) {
  15146. element.container?.addEventListener("keydown", this.#boundKeyDown);
  15147. }
  15148. this.#container.hidden = true;
  15149. if (open) {
  15150. this.#toggle();
  15151. }
  15152. }
  15153. render() {
  15154. if (this.#popup) {
  15155. return;
  15156. }
  15157. const popup = this.#popup = document.createElement("div");
  15158. popup.className = "popup";
  15159. if (this.#color) {
  15160. const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
  15161. if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) {
  15162. popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
  15163. } else {
  15164. const BACKGROUND_ENLIGHT = 0.7;
  15165. popup.style.backgroundColor = Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c)));
  15166. }
  15167. }
  15168. const header = document.createElement("span");
  15169. header.className = "header";
  15170. const title = document.createElement("h1");
  15171. header.append(title);
  15172. ({
  15173. dir: title.dir,
  15174. str: title.textContent
  15175. } = this.#titleObj);
  15176. popup.append(header);
  15177. if (this.#dateObj) {
  15178. const modificationDate = document.createElement("span");
  15179. modificationDate.classList.add("popupDate");
  15180. modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");
  15181. modificationDate.setAttribute("data-l10n-args", JSON.stringify({
  15182. dateObj: this.#dateObj.valueOf()
  15183. }));
  15184. header.append(modificationDate);
  15185. }
  15186. const html = this.#html;
  15187. if (html) {
  15188. XfaLayer.render({
  15189. xfaHtml: html,
  15190. intent: "richText",
  15191. div: popup
  15192. });
  15193. popup.lastChild.classList.add("richText", "popupContent");
  15194. } else {
  15195. const contents = this._formatContents(this.#contentsObj);
  15196. popup.append(contents);
  15197. }
  15198. this.#container.append(popup);
  15199. }
  15200. get #html() {
  15201. const richText = this.#richText;
  15202. const contentsObj = this.#contentsObj;
  15203. if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
  15204. return this.#richText.html || null;
  15205. }
  15206. return null;
  15207. }
  15208. get #fontSize() {
  15209. return this.#html?.attributes?.style?.fontSize || 0;
  15210. }
  15211. get #fontColor() {
  15212. return this.#html?.attributes?.style?.color || null;
  15213. }
  15214. #makePopupContent(text) {
  15215. const popupLines = [];
  15216. const popupContent = {
  15217. str: text,
  15218. html: {
  15219. name: "div",
  15220. attributes: {
  15221. dir: "auto"
  15222. },
  15223. children: [{
  15224. name: "p",
  15225. children: popupLines
  15226. }]
  15227. }
  15228. };
  15229. const lineAttributes = {
  15230. style: {
  15231. color: this.#fontColor,
  15232. fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--scale-factor))` : ""
  15233. }
  15234. };
  15235. for (const line of text.split("\n")) {
  15236. popupLines.push({
  15237. name: "span",
  15238. value: line,
  15239. attributes: lineAttributes
  15240. });
  15241. }
  15242. return popupContent;
  15243. }
  15244. _formatContents({
  15245. str,
  15246. dir
  15247. }) {
  15248. const p = document.createElement("p");
  15249. p.classList.add("popupContent");
  15250. p.dir = dir;
  15251. const lines = str.split(/(?:\r\n?|\n)/);
  15252. for (let i = 0, ii = lines.length; i < ii; ++i) {
  15253. const line = lines[i];
  15254. p.append(document.createTextNode(line));
  15255. if (i < ii - 1) {
  15256. p.append(document.createElement("br"));
  15257. }
  15258. }
  15259. return p;
  15260. }
  15261. #keyDown(event) {
  15262. if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
  15263. return;
  15264. }
  15265. if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
  15266. this.#toggle();
  15267. }
  15268. }
  15269. updateEdited({
  15270. rect,
  15271. popupContent
  15272. }) {
  15273. this.#updates ||= {
  15274. contentsObj: this.#contentsObj,
  15275. richText: this.#richText
  15276. };
  15277. if (rect) {
  15278. this.#position = null;
  15279. }
  15280. if (popupContent) {
  15281. this.#richText = this.#makePopupContent(popupContent);
  15282. this.#contentsObj = null;
  15283. }
  15284. this.#popup?.remove();
  15285. this.#popup = null;
  15286. }
  15287. resetEdited() {
  15288. if (!this.#updates) {
  15289. return;
  15290. }
  15291. ({
  15292. contentsObj: this.#contentsObj,
  15293. richText: this.#richText
  15294. } = this.#updates);
  15295. this.#updates = null;
  15296. this.#popup?.remove();
  15297. this.#popup = null;
  15298. this.#position = null;
  15299. }
  15300. #setPosition() {
  15301. if (this.#position !== null) {
  15302. return;
  15303. }
  15304. const {
  15305. page: {
  15306. view
  15307. },
  15308. viewport: {
  15309. rawDims: {
  15310. pageWidth,
  15311. pageHeight,
  15312. pageX,
  15313. pageY
  15314. }
  15315. }
  15316. } = this.#parent;
  15317. let useParentRect = !!this.#parentRect;
  15318. let rect = useParentRect ? this.#parentRect : this.#rect;
  15319. for (const element of this.#elements) {
  15320. if (!rect || Util.intersect(element.data.rect, rect) !== null) {
  15321. rect = element.data.rect;
  15322. useParentRect = true;
  15323. break;
  15324. }
  15325. }
  15326. const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
  15327. const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
  15328. const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
  15329. const popupLeft = normalizedRect[0] + parentWidth;
  15330. const popupTop = normalizedRect[1];
  15331. this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
  15332. const {
  15333. style
  15334. } = this.#container;
  15335. style.left = `${this.#position[0]}%`;
  15336. style.top = `${this.#position[1]}%`;
  15337. }
  15338. #toggle() {
  15339. this.#pinned = !this.#pinned;
  15340. if (this.#pinned) {
  15341. this.#show();
  15342. this.#container.addEventListener("click", this.#boundToggle);
  15343. this.#container.addEventListener("keydown", this.#boundKeyDown);
  15344. } else {
  15345. this.#hide();
  15346. this.#container.removeEventListener("click", this.#boundToggle);
  15347. this.#container.removeEventListener("keydown", this.#boundKeyDown);
  15348. }
  15349. }
  15350. #show() {
  15351. if (!this.#popup) {
  15352. this.render();
  15353. }
  15354. if (!this.isVisible) {
  15355. this.#setPosition();
  15356. this.#container.hidden = false;
  15357. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;
  15358. } else if (this.#pinned) {
  15359. this.#container.classList.add("focused");
  15360. }
  15361. }
  15362. #hide() {
  15363. this.#container.classList.remove("focused");
  15364. if (this.#pinned || !this.isVisible) {
  15365. return;
  15366. }
  15367. this.#container.hidden = true;
  15368. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;
  15369. }
  15370. forceHide() {
  15371. this.#wasVisible = this.isVisible;
  15372. if (!this.#wasVisible) {
  15373. return;
  15374. }
  15375. this.#container.hidden = true;
  15376. }
  15377. maybeShow() {
  15378. if (!this.#wasVisible) {
  15379. return;
  15380. }
  15381. if (!this.#popup) {
  15382. this.#show();
  15383. }
  15384. this.#wasVisible = false;
  15385. this.#container.hidden = false;
  15386. }
  15387. get isVisible() {
  15388. return this.#container.hidden === false;
  15389. }
  15390. }
  15391. class FreeTextAnnotationElement extends AnnotationElement {
  15392. constructor(parameters) {
  15393. super(parameters, {
  15394. isRenderable: true,
  15395. ignoreBorder: true
  15396. });
  15397. this.textContent = parameters.data.textContent;
  15398. this.textPosition = parameters.data.textPosition;
  15399. this.annotationEditorType = AnnotationEditorType.FREETEXT;
  15400. }
  15401. render() {
  15402. this.container.classList.add("freeTextAnnotation");
  15403. if (this.textContent) {
  15404. const content = document.createElement("div");
  15405. content.classList.add("annotationTextContent");
  15406. content.setAttribute("role", "comment");
  15407. for (const line of this.textContent) {
  15408. const lineSpan = document.createElement("span");
  15409. lineSpan.textContent = line;
  15410. content.append(lineSpan);
  15411. }
  15412. this.container.append(content);
  15413. }
  15414. if (!this.data.popupRef && this.hasPopupData) {
  15415. this._createPopup();
  15416. }
  15417. this._editOnDoubleClick();
  15418. return this.container;
  15419. }
  15420. }
  15421. class LineAnnotationElement extends AnnotationElement {
  15422. #line = null;
  15423. constructor(parameters) {
  15424. super(parameters, {
  15425. isRenderable: true,
  15426. ignoreBorder: true
  15427. });
  15428. }
  15429. render() {
  15430. this.container.classList.add("lineAnnotation");
  15431. const data = this.data;
  15432. const {
  15433. width,
  15434. height
  15435. } = getRectDims(data.rect);
  15436. const svg = this.svgFactory.create(width, height, true);
  15437. const line = this.#line = this.svgFactory.createElement("svg:line");
  15438. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  15439. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  15440. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  15441. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  15442. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  15443. line.setAttribute("stroke", "transparent");
  15444. line.setAttribute("fill", "transparent");
  15445. svg.append(line);
  15446. this.container.append(svg);
  15447. if (!data.popupRef && this.hasPopupData) {
  15448. this._createPopup();
  15449. }
  15450. return this.container;
  15451. }
  15452. getElementsToTriggerPopup() {
  15453. return this.#line;
  15454. }
  15455. addHighlightArea() {
  15456. this.container.classList.add("highlightArea");
  15457. }
  15458. }
  15459. class SquareAnnotationElement extends AnnotationElement {
  15460. #square = null;
  15461. constructor(parameters) {
  15462. super(parameters, {
  15463. isRenderable: true,
  15464. ignoreBorder: true
  15465. });
  15466. }
  15467. render() {
  15468. this.container.classList.add("squareAnnotation");
  15469. const data = this.data;
  15470. const {
  15471. width,
  15472. height
  15473. } = getRectDims(data.rect);
  15474. const svg = this.svgFactory.create(width, height, true);
  15475. const borderWidth = data.borderStyle.width;
  15476. const square = this.#square = this.svgFactory.createElement("svg:rect");
  15477. square.setAttribute("x", borderWidth / 2);
  15478. square.setAttribute("y", borderWidth / 2);
  15479. square.setAttribute("width", width - borderWidth);
  15480. square.setAttribute("height", height - borderWidth);
  15481. square.setAttribute("stroke-width", borderWidth || 1);
  15482. square.setAttribute("stroke", "transparent");
  15483. square.setAttribute("fill", "transparent");
  15484. svg.append(square);
  15485. this.container.append(svg);
  15486. if (!data.popupRef && this.hasPopupData) {
  15487. this._createPopup();
  15488. }
  15489. return this.container;
  15490. }
  15491. getElementsToTriggerPopup() {
  15492. return this.#square;
  15493. }
  15494. addHighlightArea() {
  15495. this.container.classList.add("highlightArea");
  15496. }
  15497. }
  15498. class CircleAnnotationElement extends AnnotationElement {
  15499. #circle = null;
  15500. constructor(parameters) {
  15501. super(parameters, {
  15502. isRenderable: true,
  15503. ignoreBorder: true
  15504. });
  15505. }
  15506. render() {
  15507. this.container.classList.add("circleAnnotation");
  15508. const data = this.data;
  15509. const {
  15510. width,
  15511. height
  15512. } = getRectDims(data.rect);
  15513. const svg = this.svgFactory.create(width, height, true);
  15514. const borderWidth = data.borderStyle.width;
  15515. const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
  15516. circle.setAttribute("cx", width / 2);
  15517. circle.setAttribute("cy", height / 2);
  15518. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  15519. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  15520. circle.setAttribute("stroke-width", borderWidth || 1);
  15521. circle.setAttribute("stroke", "transparent");
  15522. circle.setAttribute("fill", "transparent");
  15523. svg.append(circle);
  15524. this.container.append(svg);
  15525. if (!data.popupRef && this.hasPopupData) {
  15526. this._createPopup();
  15527. }
  15528. return this.container;
  15529. }
  15530. getElementsToTriggerPopup() {
  15531. return this.#circle;
  15532. }
  15533. addHighlightArea() {
  15534. this.container.classList.add("highlightArea");
  15535. }
  15536. }
  15537. class PolylineAnnotationElement extends AnnotationElement {
  15538. #polyline = null;
  15539. constructor(parameters) {
  15540. super(parameters, {
  15541. isRenderable: true,
  15542. ignoreBorder: true
  15543. });
  15544. this.containerClassName = "polylineAnnotation";
  15545. this.svgElementName = "svg:polyline";
  15546. }
  15547. render() {
  15548. this.container.classList.add(this.containerClassName);
  15549. const {
  15550. data: {
  15551. rect,
  15552. vertices,
  15553. borderStyle,
  15554. popupRef
  15555. }
  15556. } = this;
  15557. if (!vertices) {
  15558. return this.container;
  15559. }
  15560. const {
  15561. width,
  15562. height
  15563. } = getRectDims(rect);
  15564. const svg = this.svgFactory.create(width, height, true);
  15565. let points = [];
  15566. for (let i = 0, ii = vertices.length; i < ii; i += 2) {
  15567. const x = vertices[i] - rect[0];
  15568. const y = rect[3] - vertices[i + 1];
  15569. points.push(`${x},${y}`);
  15570. }
  15571. points = points.join(" ");
  15572. const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
  15573. polyline.setAttribute("points", points);
  15574. polyline.setAttribute("stroke-width", borderStyle.width || 1);
  15575. polyline.setAttribute("stroke", "transparent");
  15576. polyline.setAttribute("fill", "transparent");
  15577. svg.append(polyline);
  15578. this.container.append(svg);
  15579. if (!popupRef && this.hasPopupData) {
  15580. this._createPopup();
  15581. }
  15582. return this.container;
  15583. }
  15584. getElementsToTriggerPopup() {
  15585. return this.#polyline;
  15586. }
  15587. addHighlightArea() {
  15588. this.container.classList.add("highlightArea");
  15589. }
  15590. }
  15591. class PolygonAnnotationElement extends PolylineAnnotationElement {
  15592. constructor(parameters) {
  15593. super(parameters);
  15594. this.containerClassName = "polygonAnnotation";
  15595. this.svgElementName = "svg:polygon";
  15596. }
  15597. }
  15598. class CaretAnnotationElement extends AnnotationElement {
  15599. constructor(parameters) {
  15600. super(parameters, {
  15601. isRenderable: true,
  15602. ignoreBorder: true
  15603. });
  15604. }
  15605. render() {
  15606. this.container.classList.add("caretAnnotation");
  15607. if (!this.data.popupRef && this.hasPopupData) {
  15608. this._createPopup();
  15609. }
  15610. return this.container;
  15611. }
  15612. }
  15613. class InkAnnotationElement extends AnnotationElement {
  15614. #polylinesGroupElement = null;
  15615. #polylines = [];
  15616. constructor(parameters) {
  15617. super(parameters, {
  15618. isRenderable: true,
  15619. ignoreBorder: true
  15620. });
  15621. this.containerClassName = "inkAnnotation";
  15622. this.svgElementName = "svg:polyline";
  15623. this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;
  15624. }
  15625. #getTransform(rotation, rect) {
  15626. switch (rotation) {
  15627. case 90:
  15628. return {
  15629. transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`,
  15630. width: rect[3] - rect[1],
  15631. height: rect[2] - rect[0]
  15632. };
  15633. case 180:
  15634. return {
  15635. transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`,
  15636. width: rect[2] - rect[0],
  15637. height: rect[3] - rect[1]
  15638. };
  15639. case 270:
  15640. return {
  15641. transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`,
  15642. width: rect[3] - rect[1],
  15643. height: rect[2] - rect[0]
  15644. };
  15645. default:
  15646. return {
  15647. transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`,
  15648. width: rect[2] - rect[0],
  15649. height: rect[3] - rect[1]
  15650. };
  15651. }
  15652. }
  15653. render() {
  15654. this.container.classList.add(this.containerClassName);
  15655. const {
  15656. data: {
  15657. rect,
  15658. rotation,
  15659. inkLists,
  15660. borderStyle,
  15661. popupRef
  15662. }
  15663. } = this;
  15664. const {
  15665. transform,
  15666. width,
  15667. height
  15668. } = this.#getTransform(rotation, rect);
  15669. const svg = this.svgFactory.create(width, height, true);
  15670. const g = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g");
  15671. svg.append(g);
  15672. g.setAttribute("stroke-width", borderStyle.width || 1);
  15673. g.setAttribute("stroke-linecap", "round");
  15674. g.setAttribute("stroke-linejoin", "round");
  15675. g.setAttribute("stroke-miterlimit", 10);
  15676. g.setAttribute("stroke", "transparent");
  15677. g.setAttribute("fill", "transparent");
  15678. g.setAttribute("transform", transform);
  15679. for (let i = 0, ii = inkLists.length; i < ii; i++) {
  15680. const polyline = this.svgFactory.createElement(this.svgElementName);
  15681. this.#polylines.push(polyline);
  15682. polyline.setAttribute("points", inkLists[i].join(","));
  15683. g.append(polyline);
  15684. }
  15685. if (!popupRef && this.hasPopupData) {
  15686. this._createPopup();
  15687. }
  15688. this.container.append(svg);
  15689. this._editOnDoubleClick();
  15690. return this.container;
  15691. }
  15692. updateEdited(params) {
  15693. super.updateEdited(params);
  15694. const {
  15695. thickness,
  15696. points,
  15697. rect
  15698. } = params;
  15699. const g = this.#polylinesGroupElement;
  15700. if (thickness >= 0) {
  15701. g.setAttribute("stroke-width", thickness || 1);
  15702. }
  15703. if (points) {
  15704. for (let i = 0, ii = this.#polylines.length; i < ii; i++) {
  15705. this.#polylines[i].setAttribute("points", points[i].join(","));
  15706. }
  15707. }
  15708. if (rect) {
  15709. const {
  15710. transform,
  15711. width,
  15712. height
  15713. } = this.#getTransform(this.data.rotation, rect);
  15714. const root = g.parentElement;
  15715. root.setAttribute("viewBox", `0 0 ${width} ${height}`);
  15716. g.setAttribute("transform", transform);
  15717. }
  15718. }
  15719. getElementsToTriggerPopup() {
  15720. return this.#polylines;
  15721. }
  15722. addHighlightArea() {
  15723. this.container.classList.add("highlightArea");
  15724. }
  15725. }
  15726. class HighlightAnnotationElement extends AnnotationElement {
  15727. constructor(parameters) {
  15728. super(parameters, {
  15729. isRenderable: true,
  15730. ignoreBorder: true,
  15731. createQuadrilaterals: true
  15732. });
  15733. this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;
  15734. }
  15735. render() {
  15736. if (!this.data.popupRef && this.hasPopupData) {
  15737. this._createPopup();
  15738. }
  15739. this.container.classList.add("highlightAnnotation");
  15740. this._editOnDoubleClick();
  15741. return this.container;
  15742. }
  15743. }
  15744. class UnderlineAnnotationElement extends AnnotationElement {
  15745. constructor(parameters) {
  15746. super(parameters, {
  15747. isRenderable: true,
  15748. ignoreBorder: true,
  15749. createQuadrilaterals: true
  15750. });
  15751. }
  15752. render() {
  15753. if (!this.data.popupRef && this.hasPopupData) {
  15754. this._createPopup();
  15755. }
  15756. this.container.classList.add("underlineAnnotation");
  15757. return this.container;
  15758. }
  15759. }
  15760. class SquigglyAnnotationElement extends AnnotationElement {
  15761. constructor(parameters) {
  15762. super(parameters, {
  15763. isRenderable: true,
  15764. ignoreBorder: true,
  15765. createQuadrilaterals: true
  15766. });
  15767. }
  15768. render() {
  15769. if (!this.data.popupRef && this.hasPopupData) {
  15770. this._createPopup();
  15771. }
  15772. this.container.classList.add("squigglyAnnotation");
  15773. return this.container;
  15774. }
  15775. }
  15776. class StrikeOutAnnotationElement extends AnnotationElement {
  15777. constructor(parameters) {
  15778. super(parameters, {
  15779. isRenderable: true,
  15780. ignoreBorder: true,
  15781. createQuadrilaterals: true
  15782. });
  15783. }
  15784. render() {
  15785. if (!this.data.popupRef && this.hasPopupData) {
  15786. this._createPopup();
  15787. }
  15788. this.container.classList.add("strikeoutAnnotation");
  15789. return this.container;
  15790. }
  15791. }
  15792. class StampAnnotationElement extends AnnotationElement {
  15793. constructor(parameters) {
  15794. super(parameters, {
  15795. isRenderable: true,
  15796. ignoreBorder: true
  15797. });
  15798. this.annotationEditorType = AnnotationEditorType.STAMP;
  15799. }
  15800. render() {
  15801. this.container.classList.add("stampAnnotation");
  15802. this.container.setAttribute("role", "img");
  15803. if (!this.data.popupRef && this.hasPopupData) {
  15804. this._createPopup();
  15805. }
  15806. this._editOnDoubleClick();
  15807. return this.container;
  15808. }
  15809. }
  15810. class FileAttachmentAnnotationElement extends AnnotationElement {
  15811. #trigger = null;
  15812. constructor(parameters) {
  15813. super(parameters, {
  15814. isRenderable: true
  15815. });
  15816. const {
  15817. file
  15818. } = this.data;
  15819. this.filename = file.filename;
  15820. this.content = file.content;
  15821. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  15822. source: this,
  15823. ...file
  15824. });
  15825. }
  15826. render() {
  15827. this.container.classList.add("fileAttachmentAnnotation");
  15828. const {
  15829. container,
  15830. data
  15831. } = this;
  15832. let trigger;
  15833. if (data.hasAppearance || data.fillAlpha === 0) {
  15834. trigger = document.createElement("div");
  15835. } else {
  15836. trigger = document.createElement("img");
  15837. trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
  15838. if (data.fillAlpha && data.fillAlpha < 1) {
  15839. trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
  15840. }
  15841. }
  15842. trigger.addEventListener("dblclick", this.#download.bind(this));
  15843. this.#trigger = trigger;
  15844. const {
  15845. isMac
  15846. } = util_FeatureTest.platform;
  15847. container.addEventListener("keydown", evt => {
  15848. if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
  15849. this.#download();
  15850. }
  15851. });
  15852. if (!data.popupRef && this.hasPopupData) {
  15853. this._createPopup();
  15854. } else {
  15855. trigger.classList.add("popupTriggerArea");
  15856. }
  15857. container.append(trigger);
  15858. return container;
  15859. }
  15860. getElementsToTriggerPopup() {
  15861. return this.#trigger;
  15862. }
  15863. addHighlightArea() {
  15864. this.container.classList.add("highlightArea");
  15865. }
  15866. #download() {
  15867. this.downloadManager?.openOrDownloadData(this.content, this.filename);
  15868. }
  15869. }
  15870. class AnnotationLayer {
  15871. #accessibilityManager = null;
  15872. #annotationCanvasMap = null;
  15873. #editableAnnotations = new Map();
  15874. #structTreeLayer = null;
  15875. constructor({
  15876. div,
  15877. accessibilityManager,
  15878. annotationCanvasMap,
  15879. annotationEditorUIManager,
  15880. page,
  15881. viewport,
  15882. structTreeLayer
  15883. }) {
  15884. this.div = div;
  15885. this.#accessibilityManager = accessibilityManager;
  15886. this.#annotationCanvasMap = annotationCanvasMap;
  15887. this.#structTreeLayer = structTreeLayer || null;
  15888. this.page = page;
  15889. this.viewport = viewport;
  15890. this.zIndex = 0;
  15891. this._annotationEditorUIManager = annotationEditorUIManager;
  15892. }
  15893. hasEditableAnnotations() {
  15894. return this.#editableAnnotations.size > 0;
  15895. }
  15896. async #appendElement(element, id) {
  15897. const contentElement = element.firstChild || element;
  15898. const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;
  15899. const ariaAttributes = await this.#structTreeLayer?.getAriaAttributes(annotationId);
  15900. if (ariaAttributes) {
  15901. for (const [key, value] of ariaAttributes) {
  15902. contentElement.setAttribute(key, value);
  15903. }
  15904. }
  15905. this.div.append(element);
  15906. this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false);
  15907. }
  15908. async render(params) {
  15909. const {
  15910. annotations
  15911. } = params;
  15912. const layer = this.div;
  15913. setLayerDimensions(layer, this.viewport);
  15914. const popupToElements = new Map();
  15915. const elementParams = {
  15916. data: null,
  15917. layer,
  15918. linkService: params.linkService,
  15919. downloadManager: params.downloadManager,
  15920. imageResourcesPath: params.imageResourcesPath || "",
  15921. renderForms: params.renderForms !== false,
  15922. svgFactory: new DOMSVGFactory(),
  15923. annotationStorage: params.annotationStorage || new AnnotationStorage(),
  15924. enableScripting: params.enableScripting === true,
  15925. hasJSActions: params.hasJSActions,
  15926. fieldObjects: params.fieldObjects,
  15927. parent: this,
  15928. elements: null
  15929. };
  15930. for (const data of annotations) {
  15931. if (data.noHTML) {
  15932. continue;
  15933. }
  15934. const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
  15935. if (!isPopupAnnotation) {
  15936. const {
  15937. width,
  15938. height
  15939. } = getRectDims(data.rect);
  15940. if (width <= 0 || height <= 0) {
  15941. continue;
  15942. }
  15943. } else {
  15944. const elements = popupToElements.get(data.id);
  15945. if (!elements) {
  15946. continue;
  15947. }
  15948. elementParams.elements = elements;
  15949. }
  15950. elementParams.data = data;
  15951. const element = AnnotationElementFactory.create(elementParams);
  15952. if (!element.isRenderable) {
  15953. continue;
  15954. }
  15955. if (!isPopupAnnotation && data.popupRef) {
  15956. const elements = popupToElements.get(data.popupRef);
  15957. if (!elements) {
  15958. popupToElements.set(data.popupRef, [element]);
  15959. } else {
  15960. elements.push(element);
  15961. }
  15962. }
  15963. const rendered = element.render();
  15964. if (data.hidden) {
  15965. rendered.style.visibility = "hidden";
  15966. }
  15967. await this.#appendElement(rendered, data.id);
  15968. if (element._isEditable) {
  15969. this.#editableAnnotations.set(element.data.id, element);
  15970. this._annotationEditorUIManager?.renderAnnotationElement(element);
  15971. }
  15972. }
  15973. this.#setAnnotationCanvasMap();
  15974. }
  15975. update({
  15976. viewport
  15977. }) {
  15978. const layer = this.div;
  15979. this.viewport = viewport;
  15980. setLayerDimensions(layer, {
  15981. rotation: viewport.rotation
  15982. });
  15983. this.#setAnnotationCanvasMap();
  15984. layer.hidden = false;
  15985. }
  15986. #setAnnotationCanvasMap() {
  15987. if (!this.#annotationCanvasMap) {
  15988. return;
  15989. }
  15990. const layer = this.div;
  15991. for (const [id, canvas] of this.#annotationCanvasMap) {
  15992. const element = layer.querySelector(`[data-annotation-id="${id}"]`);
  15993. if (!element) {
  15994. continue;
  15995. }
  15996. canvas.className = "annotationContent";
  15997. const {
  15998. firstChild
  15999. } = element;
  16000. if (!firstChild) {
  16001. element.append(canvas);
  16002. } else if (firstChild.nodeName === "CANVAS") {
  16003. firstChild.replaceWith(canvas);
  16004. } else if (!firstChild.classList.contains("annotationContent")) {
  16005. firstChild.before(canvas);
  16006. } else {
  16007. firstChild.after(canvas);
  16008. }
  16009. }
  16010. this.#annotationCanvasMap.clear();
  16011. }
  16012. getEditableAnnotations() {
  16013. return Array.from(this.#editableAnnotations.values());
  16014. }
  16015. getEditableAnnotation(id) {
  16016. return this.#editableAnnotations.get(id);
  16017. }
  16018. }
  16019. ;// ./src/display/editor/freetext.js
  16020. const EOL_PATTERN = /\r\n?|\n/g;
  16021. class FreeTextEditor extends AnnotationEditor {
  16022. #color;
  16023. #content = "";
  16024. #editorDivId = `${this.id}-editor`;
  16025. #editModeAC = null;
  16026. #fontSize;
  16027. static _freeTextDefaultContent = "";
  16028. static _internalPadding = 0;
  16029. static _defaultColor = null;
  16030. static _defaultFontSize = 10;
  16031. static get _keyboardManager() {
  16032. const proto = FreeTextEditor.prototype;
  16033. const arrowChecker = self => self.isEmpty();
  16034. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  16035. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  16036. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
  16037. bubbles: true
  16038. }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
  16039. args: [-small, 0],
  16040. checker: arrowChecker
  16041. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
  16042. args: [-big, 0],
  16043. checker: arrowChecker
  16044. }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
  16045. args: [small, 0],
  16046. checker: arrowChecker
  16047. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
  16048. args: [big, 0],
  16049. checker: arrowChecker
  16050. }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
  16051. args: [0, -small],
  16052. checker: arrowChecker
  16053. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
  16054. args: [0, -big],
  16055. checker: arrowChecker
  16056. }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
  16057. args: [0, small],
  16058. checker: arrowChecker
  16059. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
  16060. args: [0, big],
  16061. checker: arrowChecker
  16062. }]]));
  16063. }
  16064. static _type = "freetext";
  16065. static _editorType = AnnotationEditorType.FREETEXT;
  16066. constructor(params) {
  16067. super({
  16068. ...params,
  16069. name: "freeTextEditor"
  16070. });
  16071. this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
  16072. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  16073. }
  16074. static initialize(l10n, uiManager) {
  16075. AnnotationEditor.initialize(l10n, uiManager);
  16076. const style = getComputedStyle(document.documentElement);
  16077. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  16078. }
  16079. static updateDefaultParams(type, value) {
  16080. switch (type) {
  16081. case AnnotationEditorParamsType.FREETEXT_SIZE:
  16082. FreeTextEditor._defaultFontSize = value;
  16083. break;
  16084. case AnnotationEditorParamsType.FREETEXT_COLOR:
  16085. FreeTextEditor._defaultColor = value;
  16086. break;
  16087. }
  16088. }
  16089. updateParams(type, value) {
  16090. switch (type) {
  16091. case AnnotationEditorParamsType.FREETEXT_SIZE:
  16092. this.#updateFontSize(value);
  16093. break;
  16094. case AnnotationEditorParamsType.FREETEXT_COLOR:
  16095. this.#updateColor(value);
  16096. break;
  16097. }
  16098. }
  16099. static get defaultPropertiesToUpdate() {
  16100. return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
  16101. }
  16102. get propertiesToUpdate() {
  16103. return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  16104. }
  16105. #updateFontSize(fontSize) {
  16106. const setFontsize = size => {
  16107. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  16108. this.translate(0, -(size - this.#fontSize) * this.parentScale);
  16109. this.#fontSize = size;
  16110. this.#setEditorDimensions();
  16111. };
  16112. const savedFontsize = this.#fontSize;
  16113. this.addCommands({
  16114. cmd: setFontsize.bind(this, fontSize),
  16115. undo: setFontsize.bind(this, savedFontsize),
  16116. post: this._uiManager.updateUI.bind(this._uiManager, this),
  16117. mustExec: true,
  16118. type: AnnotationEditorParamsType.FREETEXT_SIZE,
  16119. overwriteIfSameType: true,
  16120. keepUndo: true
  16121. });
  16122. }
  16123. #updateColor(color) {
  16124. const setColor = col => {
  16125. this.#color = this.editorDiv.style.color = col;
  16126. };
  16127. const savedColor = this.#color;
  16128. this.addCommands({
  16129. cmd: setColor.bind(this, color),
  16130. undo: setColor.bind(this, savedColor),
  16131. post: this._uiManager.updateUI.bind(this._uiManager, this),
  16132. mustExec: true,
  16133. type: AnnotationEditorParamsType.FREETEXT_COLOR,
  16134. overwriteIfSameType: true,
  16135. keepUndo: true
  16136. });
  16137. }
  16138. _translateEmpty(x, y) {
  16139. this._uiManager.translateSelectedEditors(x, y, true);
  16140. }
  16141. getInitialTranslation() {
  16142. const scale = this.parentScale;
  16143. return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  16144. }
  16145. rebuild() {
  16146. if (!this.parent) {
  16147. return;
  16148. }
  16149. super.rebuild();
  16150. if (this.div === null) {
  16151. return;
  16152. }
  16153. if (!this.isAttachedToDOM) {
  16154. this.parent.add(this);
  16155. }
  16156. }
  16157. enableEditMode() {
  16158. if (this.isInEditMode()) {
  16159. return;
  16160. }
  16161. this.parent.setEditingState(false);
  16162. this.parent.updateToolbar(AnnotationEditorType.FREETEXT);
  16163. super.enableEditMode();
  16164. this.overlayDiv.classList.remove("enabled");
  16165. this.editorDiv.contentEditable = true;
  16166. this._isDraggable = false;
  16167. this.div.removeAttribute("aria-activedescendant");
  16168. this.#editModeAC = new AbortController();
  16169. const signal = this._uiManager.combinedSignal(this.#editModeAC);
  16170. this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {
  16171. signal
  16172. });
  16173. this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {
  16174. signal
  16175. });
  16176. this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {
  16177. signal
  16178. });
  16179. this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {
  16180. signal
  16181. });
  16182. this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {
  16183. signal
  16184. });
  16185. }
  16186. disableEditMode() {
  16187. if (!this.isInEditMode()) {
  16188. return;
  16189. }
  16190. this.parent.setEditingState(true);
  16191. super.disableEditMode();
  16192. this.overlayDiv.classList.add("enabled");
  16193. this.editorDiv.contentEditable = false;
  16194. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  16195. this._isDraggable = true;
  16196. this.#editModeAC?.abort();
  16197. this.#editModeAC = null;
  16198. this.div.focus({
  16199. preventScroll: true
  16200. });
  16201. this.isEditing = false;
  16202. this.parent.div.classList.add("freetextEditing");
  16203. }
  16204. focusin(event) {
  16205. if (!this._focusEventsAllowed) {
  16206. return;
  16207. }
  16208. super.focusin(event);
  16209. if (event.target !== this.editorDiv) {
  16210. this.editorDiv.focus();
  16211. }
  16212. }
  16213. onceAdded(focus) {
  16214. if (this.width) {
  16215. return;
  16216. }
  16217. this.enableEditMode();
  16218. if (focus) {
  16219. this.editorDiv.focus();
  16220. }
  16221. if (this._initialOptions?.isCentered) {
  16222. this.center();
  16223. }
  16224. this._initialOptions = null;
  16225. }
  16226. isEmpty() {
  16227. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  16228. }
  16229. remove() {
  16230. this.isEditing = false;
  16231. if (this.parent) {
  16232. this.parent.setEditingState(true);
  16233. this.parent.div.classList.add("freetextEditing");
  16234. }
  16235. super.remove();
  16236. }
  16237. #extractText() {
  16238. const buffer = [];
  16239. this.editorDiv.normalize();
  16240. let prevChild = null;
  16241. for (const child of this.editorDiv.childNodes) {
  16242. if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {
  16243. continue;
  16244. }
  16245. buffer.push(FreeTextEditor.#getNodeContent(child));
  16246. prevChild = child;
  16247. }
  16248. return buffer.join("\n");
  16249. }
  16250. #setEditorDimensions() {
  16251. const [parentWidth, parentHeight] = this.parentDimensions;
  16252. let rect;
  16253. if (this.isAttachedToDOM) {
  16254. rect = this.div.getBoundingClientRect();
  16255. } else {
  16256. const {
  16257. currentLayer,
  16258. div
  16259. } = this;
  16260. const savedDisplay = div.style.display;
  16261. const savedVisibility = div.classList.contains("hidden");
  16262. div.classList.remove("hidden");
  16263. div.style.display = "hidden";
  16264. currentLayer.div.append(this.div);
  16265. rect = div.getBoundingClientRect();
  16266. div.remove();
  16267. div.style.display = savedDisplay;
  16268. div.classList.toggle("hidden", savedVisibility);
  16269. }
  16270. if (this.rotation % 180 === this.parentRotation % 180) {
  16271. this.width = rect.width / parentWidth;
  16272. this.height = rect.height / parentHeight;
  16273. } else {
  16274. this.width = rect.height / parentWidth;
  16275. this.height = rect.width / parentHeight;
  16276. }
  16277. this.fixAndSetPosition();
  16278. }
  16279. commit() {
  16280. if (!this.isInEditMode()) {
  16281. return;
  16282. }
  16283. super.commit();
  16284. this.disableEditMode();
  16285. const savedText = this.#content;
  16286. const newText = this.#content = this.#extractText().trimEnd();
  16287. if (savedText === newText) {
  16288. return;
  16289. }
  16290. const setText = text => {
  16291. this.#content = text;
  16292. if (!text) {
  16293. this.remove();
  16294. return;
  16295. }
  16296. this.#setContent();
  16297. this._uiManager.rebuild(this);
  16298. this.#setEditorDimensions();
  16299. };
  16300. this.addCommands({
  16301. cmd: () => {
  16302. setText(newText);
  16303. },
  16304. undo: () => {
  16305. setText(savedText);
  16306. },
  16307. mustExec: false
  16308. });
  16309. this.#setEditorDimensions();
  16310. }
  16311. shouldGetKeyboardEvents() {
  16312. return this.isInEditMode();
  16313. }
  16314. enterInEditMode() {
  16315. this.enableEditMode();
  16316. this.editorDiv.focus();
  16317. }
  16318. dblclick(event) {
  16319. this.enterInEditMode();
  16320. }
  16321. keydown(event) {
  16322. if (event.target === this.div && event.key === "Enter") {
  16323. this.enterInEditMode();
  16324. event.preventDefault();
  16325. }
  16326. }
  16327. editorDivKeydown(event) {
  16328. FreeTextEditor._keyboardManager.exec(this, event);
  16329. }
  16330. editorDivFocus(event) {
  16331. this.isEditing = true;
  16332. }
  16333. editorDivBlur(event) {
  16334. this.isEditing = false;
  16335. }
  16336. editorDivInput(event) {
  16337. this.parent.div.classList.toggle("freetextEditing", this.isEmpty());
  16338. }
  16339. disableEditing() {
  16340. this.editorDiv.setAttribute("role", "comment");
  16341. this.editorDiv.removeAttribute("aria-multiline");
  16342. }
  16343. enableEditing() {
  16344. this.editorDiv.setAttribute("role", "textbox");
  16345. this.editorDiv.setAttribute("aria-multiline", true);
  16346. }
  16347. render() {
  16348. if (this.div) {
  16349. return this.div;
  16350. }
  16351. let baseX, baseY;
  16352. if (this.width) {
  16353. baseX = this.x;
  16354. baseY = this.y;
  16355. }
  16356. super.render();
  16357. this.editorDiv = document.createElement("div");
  16358. this.editorDiv.className = "internal";
  16359. this.editorDiv.setAttribute("id", this.#editorDivId);
  16360. this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2");
  16361. this.editorDiv.setAttribute("data-l10n-attrs", "default-content");
  16362. this.enableEditing();
  16363. this.editorDiv.contentEditable = true;
  16364. const {
  16365. style
  16366. } = this.editorDiv;
  16367. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  16368. style.color = this.#color;
  16369. this.div.append(this.editorDiv);
  16370. this.overlayDiv = document.createElement("div");
  16371. this.overlayDiv.classList.add("overlay", "enabled");
  16372. this.div.append(this.overlayDiv);
  16373. bindEvents(this, this.div, ["dblclick", "keydown"]);
  16374. if (this.width) {
  16375. const [parentWidth, parentHeight] = this.parentDimensions;
  16376. if (this.annotationElementId) {
  16377. const {
  16378. position
  16379. } = this._initialData;
  16380. let [tx, ty] = this.getInitialTranslation();
  16381. [tx, ty] = this.pageTranslationToScreen(tx, ty);
  16382. const [pageWidth, pageHeight] = this.pageDimensions;
  16383. const [pageX, pageY] = this.pageTranslation;
  16384. let posX, posY;
  16385. switch (this.rotation) {
  16386. case 0:
  16387. posX = baseX + (position[0] - pageX) / pageWidth;
  16388. posY = baseY + this.height - (position[1] - pageY) / pageHeight;
  16389. break;
  16390. case 90:
  16391. posX = baseX + (position[0] - pageX) / pageWidth;
  16392. posY = baseY - (position[1] - pageY) / pageHeight;
  16393. [tx, ty] = [ty, -tx];
  16394. break;
  16395. case 180:
  16396. posX = baseX - this.width + (position[0] - pageX) / pageWidth;
  16397. posY = baseY - (position[1] - pageY) / pageHeight;
  16398. [tx, ty] = [-tx, -ty];
  16399. break;
  16400. case 270:
  16401. posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
  16402. posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
  16403. [tx, ty] = [-ty, tx];
  16404. break;
  16405. }
  16406. this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
  16407. } else {
  16408. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  16409. }
  16410. this.#setContent();
  16411. this._isDraggable = true;
  16412. this.editorDiv.contentEditable = false;
  16413. } else {
  16414. this._isDraggable = false;
  16415. this.editorDiv.contentEditable = true;
  16416. }
  16417. return this.div;
  16418. }
  16419. static #getNodeContent(node) {
  16420. return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
  16421. }
  16422. editorDivPaste(event) {
  16423. const clipboardData = event.clipboardData || window.clipboardData;
  16424. const {
  16425. types
  16426. } = clipboardData;
  16427. if (types.length === 1 && types[0] === "text/plain") {
  16428. return;
  16429. }
  16430. event.preventDefault();
  16431. const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
  16432. if (!paste) {
  16433. return;
  16434. }
  16435. const selection = window.getSelection();
  16436. if (!selection.rangeCount) {
  16437. return;
  16438. }
  16439. this.editorDiv.normalize();
  16440. selection.deleteFromDocument();
  16441. const range = selection.getRangeAt(0);
  16442. if (!paste.includes("\n")) {
  16443. range.insertNode(document.createTextNode(paste));
  16444. this.editorDiv.normalize();
  16445. selection.collapseToStart();
  16446. return;
  16447. }
  16448. const {
  16449. startContainer,
  16450. startOffset
  16451. } = range;
  16452. const bufferBefore = [];
  16453. const bufferAfter = [];
  16454. if (startContainer.nodeType === Node.TEXT_NODE) {
  16455. const parent = startContainer.parentElement;
  16456. bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
  16457. if (parent !== this.editorDiv) {
  16458. let buffer = bufferBefore;
  16459. for (const child of this.editorDiv.childNodes) {
  16460. if (child === parent) {
  16461. buffer = bufferAfter;
  16462. continue;
  16463. }
  16464. buffer.push(FreeTextEditor.#getNodeContent(child));
  16465. }
  16466. }
  16467. bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
  16468. } else if (startContainer === this.editorDiv) {
  16469. let buffer = bufferBefore;
  16470. let i = 0;
  16471. for (const child of this.editorDiv.childNodes) {
  16472. if (i++ === startOffset) {
  16473. buffer = bufferAfter;
  16474. }
  16475. buffer.push(FreeTextEditor.#getNodeContent(child));
  16476. }
  16477. }
  16478. this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
  16479. this.#setContent();
  16480. const newRange = new Range();
  16481. let beforeLength = bufferBefore.reduce((acc, line) => acc + line.length, 0);
  16482. for (const {
  16483. firstChild
  16484. } of this.editorDiv.childNodes) {
  16485. if (firstChild.nodeType === Node.TEXT_NODE) {
  16486. const length = firstChild.nodeValue.length;
  16487. if (beforeLength <= length) {
  16488. newRange.setStart(firstChild, beforeLength);
  16489. newRange.setEnd(firstChild, beforeLength);
  16490. break;
  16491. }
  16492. beforeLength -= length;
  16493. }
  16494. }
  16495. selection.removeAllRanges();
  16496. selection.addRange(newRange);
  16497. }
  16498. #setContent() {
  16499. this.editorDiv.replaceChildren();
  16500. if (!this.#content) {
  16501. return;
  16502. }
  16503. for (const line of this.#content.split("\n")) {
  16504. const div = document.createElement("div");
  16505. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  16506. this.editorDiv.append(div);
  16507. }
  16508. }
  16509. #serializeContent() {
  16510. return this.#content.replaceAll("\xa0", " ");
  16511. }
  16512. static #deserializeContent(content) {
  16513. return content.replaceAll(" ", "\xa0");
  16514. }
  16515. get contentDiv() {
  16516. return this.editorDiv;
  16517. }
  16518. static async deserialize(data, parent, uiManager) {
  16519. let initialData = null;
  16520. if (data instanceof FreeTextAnnotationElement) {
  16521. const {
  16522. data: {
  16523. defaultAppearanceData: {
  16524. fontSize,
  16525. fontColor
  16526. },
  16527. rect,
  16528. rotation,
  16529. id,
  16530. popupRef
  16531. },
  16532. textContent,
  16533. textPosition,
  16534. parent: {
  16535. page: {
  16536. pageNumber
  16537. }
  16538. }
  16539. } = data;
  16540. if (!textContent || textContent.length === 0) {
  16541. return null;
  16542. }
  16543. initialData = data = {
  16544. annotationType: AnnotationEditorType.FREETEXT,
  16545. color: Array.from(fontColor),
  16546. fontSize,
  16547. value: textContent.join("\n"),
  16548. position: textPosition,
  16549. pageIndex: pageNumber - 1,
  16550. rect: rect.slice(0),
  16551. rotation,
  16552. id,
  16553. deleted: false,
  16554. popupRef
  16555. };
  16556. }
  16557. const editor = await super.deserialize(data, parent, uiManager);
  16558. editor.#fontSize = data.fontSize;
  16559. editor.#color = Util.makeHexColor(...data.color);
  16560. editor.#content = FreeTextEditor.#deserializeContent(data.value);
  16561. editor.annotationElementId = data.id || null;
  16562. editor._initialData = initialData;
  16563. return editor;
  16564. }
  16565. serialize(isForCopying = false) {
  16566. if (this.isEmpty()) {
  16567. return null;
  16568. }
  16569. if (this.deleted) {
  16570. return this.serializeDeleted();
  16571. }
  16572. const padding = FreeTextEditor._internalPadding * this.parentScale;
  16573. const rect = this.getRect(padding, padding);
  16574. const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
  16575. const serialized = {
  16576. annotationType: AnnotationEditorType.FREETEXT,
  16577. color,
  16578. fontSize: this.#fontSize,
  16579. value: this.#serializeContent(),
  16580. pageIndex: this.pageIndex,
  16581. rect,
  16582. rotation: this.rotation,
  16583. structTreeParentId: this._structTreeParentId
  16584. };
  16585. if (isForCopying) {
  16586. return serialized;
  16587. }
  16588. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  16589. return null;
  16590. }
  16591. serialized.id = this.annotationElementId;
  16592. return serialized;
  16593. }
  16594. #hasElementChanged(serialized) {
  16595. const {
  16596. value,
  16597. fontSize,
  16598. color,
  16599. pageIndex
  16600. } = this._initialData;
  16601. return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;
  16602. }
  16603. renderAnnotationElement(annotation) {
  16604. const content = super.renderAnnotationElement(annotation);
  16605. if (this.deleted) {
  16606. return content;
  16607. }
  16608. const {
  16609. style
  16610. } = content;
  16611. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  16612. style.color = this.#color;
  16613. content.replaceChildren();
  16614. for (const line of this.#content.split("\n")) {
  16615. const div = document.createElement("div");
  16616. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  16617. content.append(div);
  16618. }
  16619. const padding = FreeTextEditor._internalPadding * this.parentScale;
  16620. annotation.updateEdited({
  16621. rect: this.getRect(padding, padding),
  16622. popupContent: this.#content
  16623. });
  16624. return content;
  16625. }
  16626. resetAnnotationElement(annotation) {
  16627. super.resetAnnotationElement(annotation);
  16628. annotation.resetEdited();
  16629. }
  16630. }
  16631. ;// ./src/display/editor/drawers/outline.js
  16632. class Outline {
  16633. static PRECISION = 1e-4;
  16634. toSVGPath() {
  16635. unreachable("Abstract method `toSVGPath` must be implemented.");
  16636. }
  16637. get box() {
  16638. unreachable("Abstract getter `box` must be implemented.");
  16639. }
  16640. serialize(_bbox, _rotation) {
  16641. unreachable("Abstract method `serialize` must be implemented.");
  16642. }
  16643. static _rescale(src, tx, ty, sx, sy, dest) {
  16644. dest ||= new Float32Array(src.length);
  16645. for (let i = 0, ii = src.length; i < ii; i += 2) {
  16646. dest[i] = tx + src[i] * sx;
  16647. dest[i + 1] = ty + src[i + 1] * sy;
  16648. }
  16649. return dest;
  16650. }
  16651. static _rescaleAndSwap(src, tx, ty, sx, sy, dest) {
  16652. dest ||= new Float32Array(src.length);
  16653. for (let i = 0, ii = src.length; i < ii; i += 2) {
  16654. dest[i] = tx + src[i + 1] * sx;
  16655. dest[i + 1] = ty + src[i] * sy;
  16656. }
  16657. return dest;
  16658. }
  16659. static _translate(src, tx, ty, dest) {
  16660. dest ||= new Float32Array(src.length);
  16661. for (let i = 0, ii = src.length; i < ii; i += 2) {
  16662. dest[i] = tx + src[i];
  16663. dest[i + 1] = ty + src[i + 1];
  16664. }
  16665. return dest;
  16666. }
  16667. static svgRound(x) {
  16668. return Math.round(x * 10000);
  16669. }
  16670. static _normalizePoint(x, y, parentWidth, parentHeight, rotation) {
  16671. switch (rotation) {
  16672. case 90:
  16673. return [1 - y / parentWidth, x / parentHeight];
  16674. case 180:
  16675. return [1 - x / parentWidth, 1 - y / parentHeight];
  16676. case 270:
  16677. return [y / parentWidth, 1 - x / parentHeight];
  16678. default:
  16679. return [x / parentWidth, y / parentHeight];
  16680. }
  16681. }
  16682. static _normalizePagePoint(x, y, rotation) {
  16683. switch (rotation) {
  16684. case 90:
  16685. return [1 - y, x];
  16686. case 180:
  16687. return [1 - x, 1 - y];
  16688. case 270:
  16689. return [y, 1 - x];
  16690. default:
  16691. return [x, y];
  16692. }
  16693. }
  16694. static createBezierPoints(x1, y1, x2, y2, x3, y3) {
  16695. return [(x1 + 5 * x2) / 6, (y1 + 5 * y2) / 6, (5 * x2 + x3) / 6, (5 * y2 + y3) / 6, (x2 + x3) / 2, (y2 + y3) / 2];
  16696. }
  16697. }
  16698. ;// ./src/display/editor/drawers/freedraw.js
  16699. class FreeDrawOutliner {
  16700. #box;
  16701. #bottom = [];
  16702. #innerMargin;
  16703. #isLTR;
  16704. #top = [];
  16705. #last = new Float32Array(18);
  16706. #lastX;
  16707. #lastY;
  16708. #min;
  16709. #min_dist;
  16710. #scaleFactor;
  16711. #thickness;
  16712. #points = [];
  16713. static #MIN_DIST = 8;
  16714. static #MIN_DIFF = 2;
  16715. static #MIN = FreeDrawOutliner.#MIN_DIST + FreeDrawOutliner.#MIN_DIFF;
  16716. constructor({
  16717. x,
  16718. y
  16719. }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  16720. this.#box = box;
  16721. this.#thickness = thickness * scaleFactor;
  16722. this.#isLTR = isLTR;
  16723. this.#last.set([NaN, NaN, NaN, NaN, x, y], 6);
  16724. this.#innerMargin = innerMargin;
  16725. this.#min_dist = FreeDrawOutliner.#MIN_DIST * scaleFactor;
  16726. this.#min = FreeDrawOutliner.#MIN * scaleFactor;
  16727. this.#scaleFactor = scaleFactor;
  16728. this.#points.push(x, y);
  16729. }
  16730. isEmpty() {
  16731. return isNaN(this.#last[8]);
  16732. }
  16733. #getLastCoords() {
  16734. const lastTop = this.#last.subarray(4, 6);
  16735. const lastBottom = this.#last.subarray(16, 18);
  16736. const [x, y, width, height] = this.#box;
  16737. 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];
  16738. }
  16739. add({
  16740. x,
  16741. y
  16742. }) {
  16743. this.#lastX = x;
  16744. this.#lastY = y;
  16745. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16746. let [x1, y1, x2, y2] = this.#last.subarray(8, 12);
  16747. const diffX = x - x2;
  16748. const diffY = y - y2;
  16749. const d = Math.hypot(diffX, diffY);
  16750. if (d < this.#min) {
  16751. return false;
  16752. }
  16753. const diffD = d - this.#min_dist;
  16754. const K = diffD / d;
  16755. const shiftX = K * diffX;
  16756. const shiftY = K * diffY;
  16757. let x0 = x1;
  16758. let y0 = y1;
  16759. x1 = x2;
  16760. y1 = y2;
  16761. x2 += shiftX;
  16762. y2 += shiftY;
  16763. this.#points?.push(x, y);
  16764. const nX = -shiftY / diffD;
  16765. const nY = shiftX / diffD;
  16766. const thX = nX * this.#thickness;
  16767. const thY = nY * this.#thickness;
  16768. this.#last.set(this.#last.subarray(2, 8), 0);
  16769. this.#last.set([x2 + thX, y2 + thY], 4);
  16770. this.#last.set(this.#last.subarray(14, 18), 12);
  16771. this.#last.set([x2 - thX, y2 - thY], 16);
  16772. if (isNaN(this.#last[6])) {
  16773. if (this.#top.length === 0) {
  16774. this.#last.set([x1 + thX, y1 + thY], 2);
  16775. this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
  16776. this.#last.set([x1 - thX, y1 - thY], 14);
  16777. this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
  16778. }
  16779. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  16780. return !this.isEmpty();
  16781. }
  16782. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  16783. const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
  16784. if (angle < Math.PI / 2) {
  16785. [x1, y1, x2, y2] = this.#last.subarray(2, 6);
  16786. this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  16787. [x1, y1, x0, y0] = this.#last.subarray(14, 18);
  16788. this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
  16789. return true;
  16790. }
  16791. [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6);
  16792. 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);
  16793. [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18);
  16794. 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);
  16795. return true;
  16796. }
  16797. toSVGPath() {
  16798. if (this.isEmpty()) {
  16799. return "";
  16800. }
  16801. const top = this.#top;
  16802. const bottom = this.#bottom;
  16803. if (isNaN(this.#last[6]) && !this.isEmpty()) {
  16804. return this.#toSVGPathTwoPoints();
  16805. }
  16806. const buffer = [];
  16807. buffer.push(`M${top[4]} ${top[5]}`);
  16808. for (let i = 6; i < top.length; i += 6) {
  16809. if (isNaN(top[i])) {
  16810. buffer.push(`L${top[i + 4]} ${top[i + 5]}`);
  16811. } else {
  16812. buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`);
  16813. }
  16814. }
  16815. this.#toSVGPathEnd(buffer);
  16816. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  16817. if (isNaN(bottom[i])) {
  16818. buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`);
  16819. } else {
  16820. buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`);
  16821. }
  16822. }
  16823. this.#toSVGPathStart(buffer);
  16824. return buffer.join(" ");
  16825. }
  16826. #toSVGPathTwoPoints() {
  16827. const [x, y, width, height] = this.#box;
  16828. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16829. 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`;
  16830. }
  16831. #toSVGPathStart(buffer) {
  16832. const bottom = this.#bottom;
  16833. buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
  16834. }
  16835. #toSVGPathEnd(buffer) {
  16836. const [x, y, width, height] = this.#box;
  16837. const lastTop = this.#last.subarray(4, 6);
  16838. const lastBottom = this.#last.subarray(16, 18);
  16839. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16840. 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}`);
  16841. }
  16842. newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
  16843. return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  16844. }
  16845. getOutlines() {
  16846. const top = this.#top;
  16847. const bottom = this.#bottom;
  16848. const last = this.#last;
  16849. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16850. const points = new Float32Array((this.#points?.length ?? 0) + 2);
  16851. for (let i = 0, ii = points.length - 2; i < ii; i += 2) {
  16852. points[i] = (this.#points[i] - layerX) / layerWidth;
  16853. points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight;
  16854. }
  16855. points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
  16856. points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
  16857. if (isNaN(last[6]) && !this.isEmpty()) {
  16858. return this.#getOutlineTwoPoints(points);
  16859. }
  16860. const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length);
  16861. let N = top.length;
  16862. for (let i = 0; i < N; i += 2) {
  16863. if (isNaN(top[i])) {
  16864. outline[i] = outline[i + 1] = NaN;
  16865. continue;
  16866. }
  16867. outline[i] = top[i];
  16868. outline[i + 1] = top[i + 1];
  16869. }
  16870. N = this.#getOutlineEnd(outline, N);
  16871. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  16872. for (let j = 0; j < 6; j += 2) {
  16873. if (isNaN(bottom[i + j])) {
  16874. outline[N] = outline[N + 1] = NaN;
  16875. N += 2;
  16876. continue;
  16877. }
  16878. outline[N] = bottom[i + j];
  16879. outline[N + 1] = bottom[i + j + 1];
  16880. N += 2;
  16881. }
  16882. }
  16883. this.#getOutlineStart(outline, N);
  16884. return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  16885. }
  16886. #getOutlineTwoPoints(points) {
  16887. const last = this.#last;
  16888. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16889. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16890. const outline = new Float32Array(36);
  16891. 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);
  16892. return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  16893. }
  16894. #getOutlineStart(outline, pos) {
  16895. const bottom = this.#bottom;
  16896. outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos);
  16897. return pos += 6;
  16898. }
  16899. #getOutlineEnd(outline, pos) {
  16900. const lastTop = this.#last.subarray(4, 6);
  16901. const lastBottom = this.#last.subarray(16, 18);
  16902. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  16903. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  16904. 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);
  16905. return pos += 24;
  16906. }
  16907. }
  16908. class FreeDrawOutline extends Outline {
  16909. #box;
  16910. #bbox = new Float32Array(4);
  16911. #innerMargin;
  16912. #isLTR;
  16913. #points;
  16914. #scaleFactor;
  16915. #outline;
  16916. constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
  16917. super();
  16918. this.#outline = outline;
  16919. this.#points = points;
  16920. this.#box = box;
  16921. this.#scaleFactor = scaleFactor;
  16922. this.#innerMargin = innerMargin;
  16923. this.#isLTR = isLTR;
  16924. this.lastPoint = [NaN, NaN];
  16925. this.#computeMinMax(isLTR);
  16926. const [x, y, width, height] = this.#bbox;
  16927. for (let i = 0, ii = outline.length; i < ii; i += 2) {
  16928. outline[i] = (outline[i] - x) / width;
  16929. outline[i + 1] = (outline[i + 1] - y) / height;
  16930. }
  16931. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16932. points[i] = (points[i] - x) / width;
  16933. points[i + 1] = (points[i + 1] - y) / height;
  16934. }
  16935. }
  16936. toSVGPath() {
  16937. const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
  16938. for (let i = 6, ii = this.#outline.length; i < ii; i += 6) {
  16939. if (isNaN(this.#outline[i])) {
  16940. buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
  16941. continue;
  16942. }
  16943. 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]}`);
  16944. }
  16945. buffer.push("Z");
  16946. return buffer.join(" ");
  16947. }
  16948. serialize([blX, blY, trX, trY], rotation) {
  16949. const width = trX - blX;
  16950. const height = trY - blY;
  16951. let outline;
  16952. let points;
  16953. switch (rotation) {
  16954. case 0:
  16955. outline = Outline._rescale(this.#outline, blX, trY, width, -height);
  16956. points = Outline._rescale(this.#points, blX, trY, width, -height);
  16957. break;
  16958. case 90:
  16959. outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height);
  16960. points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height);
  16961. break;
  16962. case 180:
  16963. outline = Outline._rescale(this.#outline, trX, blY, -width, height);
  16964. points = Outline._rescale(this.#points, trX, blY, -width, height);
  16965. break;
  16966. case 270:
  16967. outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height);
  16968. points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height);
  16969. break;
  16970. }
  16971. return {
  16972. outline: Array.from(outline),
  16973. points: [Array.from(points)]
  16974. };
  16975. }
  16976. #computeMinMax(isLTR) {
  16977. const outline = this.#outline;
  16978. let lastX = outline[4];
  16979. let lastY = outline[5];
  16980. let minX = lastX;
  16981. let minY = lastY;
  16982. let maxX = lastX;
  16983. let maxY = lastY;
  16984. let lastPointX = lastX;
  16985. let lastPointY = lastY;
  16986. const ltrCallback = isLTR ? Math.max : Math.min;
  16987. for (let i = 6, ii = outline.length; i < ii; i += 6) {
  16988. if (isNaN(outline[i])) {
  16989. minX = Math.min(minX, outline[i + 4]);
  16990. minY = Math.min(minY, outline[i + 5]);
  16991. maxX = Math.max(maxX, outline[i + 4]);
  16992. maxY = Math.max(maxY, outline[i + 5]);
  16993. if (lastPointY < outline[i + 5]) {
  16994. lastPointX = outline[i + 4];
  16995. lastPointY = outline[i + 5];
  16996. } else if (lastPointY === outline[i + 5]) {
  16997. lastPointX = ltrCallback(lastPointX, outline[i + 4]);
  16998. }
  16999. } else {
  17000. const bbox = Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6));
  17001. minX = Math.min(minX, bbox[0]);
  17002. minY = Math.min(minY, bbox[1]);
  17003. maxX = Math.max(maxX, bbox[2]);
  17004. maxY = Math.max(maxY, bbox[3]);
  17005. if (lastPointY < bbox[3]) {
  17006. lastPointX = bbox[2];
  17007. lastPointY = bbox[3];
  17008. } else if (lastPointY === bbox[3]) {
  17009. lastPointX = ltrCallback(lastPointX, bbox[2]);
  17010. }
  17011. }
  17012. lastX = outline[i + 4];
  17013. lastY = outline[i + 5];
  17014. }
  17015. const bbox = this.#bbox;
  17016. bbox[0] = minX - this.#innerMargin;
  17017. bbox[1] = minY - this.#innerMargin;
  17018. bbox[2] = maxX - minX + 2 * this.#innerMargin;
  17019. bbox[3] = maxY - minY + 2 * this.#innerMargin;
  17020. this.lastPoint = [lastPointX, lastPointY];
  17021. }
  17022. get box() {
  17023. return this.#bbox;
  17024. }
  17025. newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  17026. return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  17027. }
  17028. getNewOutline(thickness, innerMargin) {
  17029. const [x, y, width, height] = this.#bbox;
  17030. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  17031. const sx = width * layerWidth;
  17032. const sy = height * layerHeight;
  17033. const tx = x * layerWidth + layerX;
  17034. const ty = y * layerHeight + layerY;
  17035. const outliner = this.newOutliner({
  17036. x: this.#points[0] * sx + tx,
  17037. y: this.#points[1] * sy + ty
  17038. }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
  17039. for (let i = 2; i < this.#points.length; i += 2) {
  17040. outliner.add({
  17041. x: this.#points[i] * sx + tx,
  17042. y: this.#points[i + 1] * sy + ty
  17043. });
  17044. }
  17045. return outliner.getOutlines();
  17046. }
  17047. }
  17048. ;// ./src/display/editor/drawers/highlight.js
  17049. class HighlightOutliner {
  17050. #box;
  17051. #lastPoint;
  17052. #verticalEdges = [];
  17053. #intervals = [];
  17054. constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
  17055. let minX = Infinity;
  17056. let maxX = -Infinity;
  17057. let minY = Infinity;
  17058. let maxY = -Infinity;
  17059. const NUMBER_OF_DIGITS = 4;
  17060. const EPSILON = 10 ** -NUMBER_OF_DIGITS;
  17061. for (const {
  17062. x,
  17063. y,
  17064. width,
  17065. height
  17066. } of boxes) {
  17067. const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON;
  17068. const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON;
  17069. const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON;
  17070. const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON;
  17071. const left = [x1, y1, y2, true];
  17072. const right = [x2, y1, y2, false];
  17073. this.#verticalEdges.push(left, right);
  17074. minX = Math.min(minX, x1);
  17075. maxX = Math.max(maxX, x2);
  17076. minY = Math.min(minY, y1);
  17077. maxY = Math.max(maxY, y2);
  17078. }
  17079. const bboxWidth = maxX - minX + 2 * innerMargin;
  17080. const bboxHeight = maxY - minY + 2 * innerMargin;
  17081. const shiftedMinX = minX - innerMargin;
  17082. const shiftedMinY = minY - innerMargin;
  17083. const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
  17084. const lastPoint = [lastEdge[0], lastEdge[2]];
  17085. for (const edge of this.#verticalEdges) {
  17086. const [x, y1, y2] = edge;
  17087. edge[0] = (x - shiftedMinX) / bboxWidth;
  17088. edge[1] = (y1 - shiftedMinY) / bboxHeight;
  17089. edge[2] = (y2 - shiftedMinY) / bboxHeight;
  17090. }
  17091. this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]);
  17092. this.#lastPoint = lastPoint;
  17093. }
  17094. getOutlines() {
  17095. this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
  17096. const outlineVerticalEdges = [];
  17097. for (const edge of this.#verticalEdges) {
  17098. if (edge[3]) {
  17099. outlineVerticalEdges.push(...this.#breakEdge(edge));
  17100. this.#insert(edge);
  17101. } else {
  17102. this.#remove(edge);
  17103. outlineVerticalEdges.push(...this.#breakEdge(edge));
  17104. }
  17105. }
  17106. return this.#getOutlines(outlineVerticalEdges);
  17107. }
  17108. #getOutlines(outlineVerticalEdges) {
  17109. const edges = [];
  17110. const allEdges = new Set();
  17111. for (const edge of outlineVerticalEdges) {
  17112. const [x, y1, y2] = edge;
  17113. edges.push([x, y1, edge], [x, y2, edge]);
  17114. }
  17115. edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
  17116. for (let i = 0, ii = edges.length; i < ii; i += 2) {
  17117. const edge1 = edges[i][2];
  17118. const edge2 = edges[i + 1][2];
  17119. edge1.push(edge2);
  17120. edge2.push(edge1);
  17121. allEdges.add(edge1);
  17122. allEdges.add(edge2);
  17123. }
  17124. const outlines = [];
  17125. let outline;
  17126. while (allEdges.size > 0) {
  17127. const edge = allEdges.values().next().value;
  17128. let [x, y1, y2, edge1, edge2] = edge;
  17129. allEdges.delete(edge);
  17130. let lastPointX = x;
  17131. let lastPointY = y1;
  17132. outline = [x, y2];
  17133. outlines.push(outline);
  17134. while (true) {
  17135. let e;
  17136. if (allEdges.has(edge1)) {
  17137. e = edge1;
  17138. } else if (allEdges.has(edge2)) {
  17139. e = edge2;
  17140. } else {
  17141. break;
  17142. }
  17143. allEdges.delete(e);
  17144. [x, y1, y2, edge1, edge2] = e;
  17145. if (lastPointX !== x) {
  17146. outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2);
  17147. lastPointX = x;
  17148. }
  17149. lastPointY = lastPointY === y1 ? y2 : y1;
  17150. }
  17151. outline.push(lastPointX, lastPointY);
  17152. }
  17153. return new HighlightOutline(outlines, this.#box, this.#lastPoint);
  17154. }
  17155. #binarySearch(y) {
  17156. const array = this.#intervals;
  17157. let start = 0;
  17158. let end = array.length - 1;
  17159. while (start <= end) {
  17160. const middle = start + end >> 1;
  17161. const y1 = array[middle][0];
  17162. if (y1 === y) {
  17163. return middle;
  17164. }
  17165. if (y1 < y) {
  17166. start = middle + 1;
  17167. } else {
  17168. end = middle - 1;
  17169. }
  17170. }
  17171. return end + 1;
  17172. }
  17173. #insert([, y1, y2]) {
  17174. const index = this.#binarySearch(y1);
  17175. this.#intervals.splice(index, 0, [y1, y2]);
  17176. }
  17177. #remove([, y1, y2]) {
  17178. const index = this.#binarySearch(y1);
  17179. for (let i = index; i < this.#intervals.length; i++) {
  17180. const [start, end] = this.#intervals[i];
  17181. if (start !== y1) {
  17182. break;
  17183. }
  17184. if (start === y1 && end === y2) {
  17185. this.#intervals.splice(i, 1);
  17186. return;
  17187. }
  17188. }
  17189. for (let i = index - 1; i >= 0; i--) {
  17190. const [start, end] = this.#intervals[i];
  17191. if (start !== y1) {
  17192. break;
  17193. }
  17194. if (start === y1 && end === y2) {
  17195. this.#intervals.splice(i, 1);
  17196. return;
  17197. }
  17198. }
  17199. }
  17200. #breakEdge(edge) {
  17201. const [x, y1, y2] = edge;
  17202. const results = [[x, y1, y2]];
  17203. const index = this.#binarySearch(y2);
  17204. for (let i = 0; i < index; i++) {
  17205. const [start, end] = this.#intervals[i];
  17206. for (let j = 0, jj = results.length; j < jj; j++) {
  17207. const [, y3, y4] = results[j];
  17208. if (end <= y3 || y4 <= start) {
  17209. continue;
  17210. }
  17211. if (y3 >= start) {
  17212. if (y4 > end) {
  17213. results[j][1] = end;
  17214. } else {
  17215. if (jj === 1) {
  17216. return [];
  17217. }
  17218. results.splice(j, 1);
  17219. j--;
  17220. jj--;
  17221. }
  17222. continue;
  17223. }
  17224. results[j][2] = start;
  17225. if (y4 > end) {
  17226. results.push([x, end, y4]);
  17227. }
  17228. }
  17229. }
  17230. return results;
  17231. }
  17232. }
  17233. class HighlightOutline extends Outline {
  17234. #box;
  17235. #outlines;
  17236. constructor(outlines, box, lastPoint) {
  17237. super();
  17238. this.#outlines = outlines;
  17239. this.#box = box;
  17240. this.lastPoint = lastPoint;
  17241. }
  17242. toSVGPath() {
  17243. const buffer = [];
  17244. for (const polygon of this.#outlines) {
  17245. let [prevX, prevY] = polygon;
  17246. buffer.push(`M${prevX} ${prevY}`);
  17247. for (let i = 2; i < polygon.length; i += 2) {
  17248. const x = polygon[i];
  17249. const y = polygon[i + 1];
  17250. if (x === prevX) {
  17251. buffer.push(`V${y}`);
  17252. prevY = y;
  17253. } else if (y === prevY) {
  17254. buffer.push(`H${x}`);
  17255. prevX = x;
  17256. }
  17257. }
  17258. buffer.push("Z");
  17259. }
  17260. return buffer.join(" ");
  17261. }
  17262. serialize([blX, blY, trX, trY], _rotation) {
  17263. const outlines = [];
  17264. const width = trX - blX;
  17265. const height = trY - blY;
  17266. for (const outline of this.#outlines) {
  17267. const points = new Array(outline.length);
  17268. for (let i = 0; i < outline.length; i += 2) {
  17269. points[i] = blX + outline[i] * width;
  17270. points[i + 1] = trY - outline[i + 1] * height;
  17271. }
  17272. outlines.push(points);
  17273. }
  17274. return outlines;
  17275. }
  17276. get box() {
  17277. return this.#box;
  17278. }
  17279. get classNamesForOutlining() {
  17280. return ["highlightOutline"];
  17281. }
  17282. }
  17283. class FreeHighlightOutliner extends FreeDrawOutliner {
  17284. newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
  17285. return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  17286. }
  17287. }
  17288. class FreeHighlightOutline extends FreeDrawOutline {
  17289. newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  17290. return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  17291. }
  17292. }
  17293. ;// ./src/display/editor/color_picker.js
  17294. class ColorPicker {
  17295. #button = null;
  17296. #buttonSwatch = null;
  17297. #defaultColor;
  17298. #dropdown = null;
  17299. #dropdownWasFromKeyboard = false;
  17300. #isMainColorPicker = false;
  17301. #editor = null;
  17302. #eventBus;
  17303. #openDropdownAC = null;
  17304. #uiManager = null;
  17305. #type;
  17306. static #l10nColor = null;
  17307. static get _keyboardManager() {
  17308. 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]]));
  17309. }
  17310. constructor({
  17311. editor = null,
  17312. uiManager = null
  17313. }) {
  17314. if (editor) {
  17315. this.#isMainColorPicker = false;
  17316. this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR;
  17317. this.#editor = editor;
  17318. } else {
  17319. this.#isMainColorPicker = true;
  17320. this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR;
  17321. }
  17322. this.#uiManager = editor?._uiManager || uiManager;
  17323. this.#eventBus = this.#uiManager._eventBus;
  17324. this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
  17325. ColorPicker.#l10nColor ||= Object.freeze({
  17326. blue: "pdfjs-editor-colorpicker-blue",
  17327. green: "pdfjs-editor-colorpicker-green",
  17328. pink: "pdfjs-editor-colorpicker-pink",
  17329. red: "pdfjs-editor-colorpicker-red",
  17330. yellow: "pdfjs-editor-colorpicker-yellow"
  17331. });
  17332. }
  17333. renderButton() {
  17334. const button = this.#button = document.createElement("button");
  17335. button.className = "colorPicker";
  17336. button.tabIndex = "0";
  17337. button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
  17338. button.setAttribute("aria-haspopup", true);
  17339. const signal = this.#uiManager._signal;
  17340. button.addEventListener("click", this.#openDropdown.bind(this), {
  17341. signal
  17342. });
  17343. button.addEventListener("keydown", this.#keyDown.bind(this), {
  17344. signal
  17345. });
  17346. const swatch = this.#buttonSwatch = document.createElement("span");
  17347. swatch.className = "swatch";
  17348. swatch.setAttribute("aria-hidden", true);
  17349. swatch.style.backgroundColor = this.#defaultColor;
  17350. button.append(swatch);
  17351. return button;
  17352. }
  17353. renderMainDropdown() {
  17354. const dropdown = this.#dropdown = this.#getDropdownRoot();
  17355. dropdown.setAttribute("aria-orientation", "horizontal");
  17356. dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel");
  17357. return dropdown;
  17358. }
  17359. #getDropdownRoot() {
  17360. const div = document.createElement("div");
  17361. const signal = this.#uiManager._signal;
  17362. div.addEventListener("contextmenu", noContextMenu, {
  17363. signal
  17364. });
  17365. div.className = "dropdown";
  17366. div.role = "listbox";
  17367. div.setAttribute("aria-multiselectable", false);
  17368. div.setAttribute("aria-orientation", "vertical");
  17369. div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
  17370. for (const [name, color] of this.#uiManager.highlightColors) {
  17371. const button = document.createElement("button");
  17372. button.tabIndex = "0";
  17373. button.role = "option";
  17374. button.setAttribute("data-color", color);
  17375. button.title = name;
  17376. button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]);
  17377. const swatch = document.createElement("span");
  17378. button.append(swatch);
  17379. swatch.className = "swatch";
  17380. swatch.style.backgroundColor = color;
  17381. button.setAttribute("aria-selected", color === this.#defaultColor);
  17382. button.addEventListener("click", this.#colorSelect.bind(this, color), {
  17383. signal
  17384. });
  17385. div.append(button);
  17386. }
  17387. div.addEventListener("keydown", this.#keyDown.bind(this), {
  17388. signal
  17389. });
  17390. return div;
  17391. }
  17392. #colorSelect(color, event) {
  17393. event.stopPropagation();
  17394. this.#eventBus.dispatch("switchannotationeditorparams", {
  17395. source: this,
  17396. type: this.#type,
  17397. value: color
  17398. });
  17399. }
  17400. _colorSelectFromKeyboard(event) {
  17401. if (event.target === this.#button) {
  17402. this.#openDropdown(event);
  17403. return;
  17404. }
  17405. const color = event.target.getAttribute("data-color");
  17406. if (!color) {
  17407. return;
  17408. }
  17409. this.#colorSelect(color, event);
  17410. }
  17411. _moveToNext(event) {
  17412. if (!this.#isDropdownVisible) {
  17413. this.#openDropdown(event);
  17414. return;
  17415. }
  17416. if (event.target === this.#button) {
  17417. this.#dropdown.firstChild?.focus();
  17418. return;
  17419. }
  17420. event.target.nextSibling?.focus();
  17421. }
  17422. _moveToPrevious(event) {
  17423. if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
  17424. if (this.#isDropdownVisible) {
  17425. this._hideDropdownFromKeyboard();
  17426. }
  17427. return;
  17428. }
  17429. if (!this.#isDropdownVisible) {
  17430. this.#openDropdown(event);
  17431. }
  17432. event.target.previousSibling?.focus();
  17433. }
  17434. _moveToBeginning(event) {
  17435. if (!this.#isDropdownVisible) {
  17436. this.#openDropdown(event);
  17437. return;
  17438. }
  17439. this.#dropdown.firstChild?.focus();
  17440. }
  17441. _moveToEnd(event) {
  17442. if (!this.#isDropdownVisible) {
  17443. this.#openDropdown(event);
  17444. return;
  17445. }
  17446. this.#dropdown.lastChild?.focus();
  17447. }
  17448. #keyDown(event) {
  17449. ColorPicker._keyboardManager.exec(this, event);
  17450. }
  17451. #openDropdown(event) {
  17452. if (this.#isDropdownVisible) {
  17453. this.hideDropdown();
  17454. return;
  17455. }
  17456. this.#dropdownWasFromKeyboard = event.detail === 0;
  17457. if (!this.#openDropdownAC) {
  17458. this.#openDropdownAC = new AbortController();
  17459. window.addEventListener("pointerdown", this.#pointerDown.bind(this), {
  17460. signal: this.#uiManager.combinedSignal(this.#openDropdownAC)
  17461. });
  17462. }
  17463. if (this.#dropdown) {
  17464. this.#dropdown.classList.remove("hidden");
  17465. return;
  17466. }
  17467. const root = this.#dropdown = this.#getDropdownRoot();
  17468. this.#button.append(root);
  17469. }
  17470. #pointerDown(event) {
  17471. if (this.#dropdown?.contains(event.target)) {
  17472. return;
  17473. }
  17474. this.hideDropdown();
  17475. }
  17476. hideDropdown() {
  17477. this.#dropdown?.classList.add("hidden");
  17478. this.#openDropdownAC?.abort();
  17479. this.#openDropdownAC = null;
  17480. }
  17481. get #isDropdownVisible() {
  17482. return this.#dropdown && !this.#dropdown.classList.contains("hidden");
  17483. }
  17484. _hideDropdownFromKeyboard() {
  17485. if (this.#isMainColorPicker) {
  17486. return;
  17487. }
  17488. if (!this.#isDropdownVisible) {
  17489. this.#editor?.unselect();
  17490. return;
  17491. }
  17492. this.hideDropdown();
  17493. this.#button.focus({
  17494. preventScroll: true,
  17495. focusVisible: this.#dropdownWasFromKeyboard
  17496. });
  17497. }
  17498. updateColor(color) {
  17499. if (this.#buttonSwatch) {
  17500. this.#buttonSwatch.style.backgroundColor = color;
  17501. }
  17502. if (!this.#dropdown) {
  17503. return;
  17504. }
  17505. const i = this.#uiManager.highlightColors.values();
  17506. for (const child of this.#dropdown.children) {
  17507. child.setAttribute("aria-selected", i.next().value === color);
  17508. }
  17509. }
  17510. destroy() {
  17511. this.#button?.remove();
  17512. this.#button = null;
  17513. this.#buttonSwatch = null;
  17514. this.#dropdown?.remove();
  17515. this.#dropdown = null;
  17516. }
  17517. }
  17518. ;// ./src/display/editor/highlight.js
  17519. class HighlightEditor extends AnnotationEditor {
  17520. #anchorNode = null;
  17521. #anchorOffset = 0;
  17522. #boxes;
  17523. #clipPathId = null;
  17524. #colorPicker = null;
  17525. #focusOutlines = null;
  17526. #focusNode = null;
  17527. #focusOffset = 0;
  17528. #highlightDiv = null;
  17529. #highlightOutlines = null;
  17530. #id = null;
  17531. #isFreeHighlight = false;
  17532. #lastPoint = null;
  17533. #opacity;
  17534. #outlineId = null;
  17535. #text = "";
  17536. #thickness;
  17537. #methodOfCreation = "";
  17538. static _defaultColor = null;
  17539. static _defaultOpacity = 1;
  17540. static _defaultThickness = 12;
  17541. static _type = "highlight";
  17542. static _editorType = AnnotationEditorType.HIGHLIGHT;
  17543. static _freeHighlightId = -1;
  17544. static _freeHighlight = null;
  17545. static _freeHighlightClipId = "";
  17546. static get _keyboardManager() {
  17547. const proto = HighlightEditor.prototype;
  17548. return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
  17549. args: [0]
  17550. }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
  17551. args: [1]
  17552. }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
  17553. args: [2]
  17554. }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
  17555. args: [3]
  17556. }]]));
  17557. }
  17558. constructor(params) {
  17559. super({
  17560. ...params,
  17561. name: "highlightEditor"
  17562. });
  17563. this.color = params.color || HighlightEditor._defaultColor;
  17564. this.#thickness = params.thickness || HighlightEditor._defaultThickness;
  17565. this.#opacity = params.opacity || HighlightEditor._defaultOpacity;
  17566. this.#boxes = params.boxes || null;
  17567. this.#methodOfCreation = params.methodOfCreation || "";
  17568. this.#text = params.text || "";
  17569. this._isDraggable = false;
  17570. if (params.highlightId > -1) {
  17571. this.#isFreeHighlight = true;
  17572. this.#createFreeOutlines(params);
  17573. this.#addToDrawLayer();
  17574. } else if (this.#boxes) {
  17575. this.#anchorNode = params.anchorNode;
  17576. this.#anchorOffset = params.anchorOffset;
  17577. this.#focusNode = params.focusNode;
  17578. this.#focusOffset = params.focusOffset;
  17579. this.#createOutlines();
  17580. this.#addToDrawLayer();
  17581. this.rotate(this.rotation);
  17582. }
  17583. }
  17584. get telemetryInitialData() {
  17585. return {
  17586. action: "added",
  17587. type: this.#isFreeHighlight ? "free_highlight" : "highlight",
  17588. color: this._uiManager.highlightColorNames.get(this.color),
  17589. thickness: this.#thickness,
  17590. methodOfCreation: this.#methodOfCreation
  17591. };
  17592. }
  17593. get telemetryFinalData() {
  17594. return {
  17595. type: "highlight",
  17596. color: this._uiManager.highlightColorNames.get(this.color)
  17597. };
  17598. }
  17599. static computeTelemetryFinalData(data) {
  17600. return {
  17601. numberOfColors: data.get("color").size
  17602. };
  17603. }
  17604. #createOutlines() {
  17605. const outliner = new HighlightOutliner(this.#boxes, 0.001);
  17606. this.#highlightOutlines = outliner.getOutlines();
  17607. [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box;
  17608. const outlinerForOutline = new HighlightOutliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr");
  17609. this.#focusOutlines = outlinerForOutline.getOutlines();
  17610. const {
  17611. lastPoint
  17612. } = this.#focusOutlines;
  17613. this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
  17614. }
  17615. #createFreeOutlines({
  17616. highlightOutlines,
  17617. highlightId,
  17618. clipPathId
  17619. }) {
  17620. this.#highlightOutlines = highlightOutlines;
  17621. const extraThickness = 1.5;
  17622. this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025);
  17623. if (highlightId >= 0) {
  17624. this.#id = highlightId;
  17625. this.#clipPathId = clipPathId;
  17626. this.parent.drawLayer.finalizeDraw(highlightId, {
  17627. bbox: highlightOutlines.box,
  17628. path: {
  17629. d: highlightOutlines.toSVGPath()
  17630. }
  17631. });
  17632. this.#outlineId = this.parent.drawLayer.drawOutline({
  17633. rootClass: {
  17634. highlightOutline: true,
  17635. free: true
  17636. },
  17637. bbox: this.#focusOutlines.box,
  17638. path: {
  17639. d: this.#focusOutlines.toSVGPath()
  17640. }
  17641. }, true);
  17642. } else if (this.parent) {
  17643. const angle = this.parent.viewport.rotation;
  17644. this.parent.drawLayer.updateProperties(this.#id, {
  17645. bbox: HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360),
  17646. path: {
  17647. d: highlightOutlines.toSVGPath()
  17648. }
  17649. });
  17650. this.parent.drawLayer.updateProperties(this.#outlineId, {
  17651. bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
  17652. path: {
  17653. d: this.#focusOutlines.toSVGPath()
  17654. }
  17655. });
  17656. }
  17657. const [x, y, width, height] = highlightOutlines.box;
  17658. switch (this.rotation) {
  17659. case 0:
  17660. this.x = x;
  17661. this.y = y;
  17662. this.width = width;
  17663. this.height = height;
  17664. break;
  17665. case 90:
  17666. {
  17667. const [pageWidth, pageHeight] = this.parentDimensions;
  17668. this.x = y;
  17669. this.y = 1 - x;
  17670. this.width = width * pageHeight / pageWidth;
  17671. this.height = height * pageWidth / pageHeight;
  17672. break;
  17673. }
  17674. case 180:
  17675. this.x = 1 - x;
  17676. this.y = 1 - y;
  17677. this.width = width;
  17678. this.height = height;
  17679. break;
  17680. case 270:
  17681. {
  17682. const [pageWidth, pageHeight] = this.parentDimensions;
  17683. this.x = 1 - y;
  17684. this.y = x;
  17685. this.width = width * pageHeight / pageWidth;
  17686. this.height = height * pageWidth / pageHeight;
  17687. break;
  17688. }
  17689. }
  17690. const {
  17691. lastPoint
  17692. } = this.#focusOutlines;
  17693. this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height];
  17694. }
  17695. static initialize(l10n, uiManager) {
  17696. AnnotationEditor.initialize(l10n, uiManager);
  17697. HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
  17698. }
  17699. static updateDefaultParams(type, value) {
  17700. switch (type) {
  17701. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  17702. HighlightEditor._defaultColor = value;
  17703. break;
  17704. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  17705. HighlightEditor._defaultThickness = value;
  17706. break;
  17707. }
  17708. }
  17709. translateInPage(x, y) {}
  17710. get toolbarPosition() {
  17711. return this.#lastPoint;
  17712. }
  17713. updateParams(type, value) {
  17714. switch (type) {
  17715. case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
  17716. this.#updateColor(value);
  17717. break;
  17718. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  17719. this.#updateThickness(value);
  17720. break;
  17721. }
  17722. }
  17723. static get defaultPropertiesToUpdate() {
  17724. return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]];
  17725. }
  17726. get propertiesToUpdate() {
  17727. return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
  17728. }
  17729. #updateColor(color) {
  17730. const setColorAndOpacity = (col, opa) => {
  17731. this.color = col;
  17732. this.#opacity = opa;
  17733. this.parent?.drawLayer.updateProperties(this.#id, {
  17734. root: {
  17735. fill: col,
  17736. "fill-opacity": opa
  17737. }
  17738. });
  17739. this.#colorPicker?.updateColor(col);
  17740. };
  17741. const savedColor = this.color;
  17742. const savedOpacity = this.#opacity;
  17743. this.addCommands({
  17744. cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity),
  17745. undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),
  17746. post: this._uiManager.updateUI.bind(this._uiManager, this),
  17747. mustExec: true,
  17748. type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
  17749. overwriteIfSameType: true,
  17750. keepUndo: true
  17751. });
  17752. this._reportTelemetry({
  17753. action: "color_changed",
  17754. color: this._uiManager.highlightColorNames.get(color)
  17755. }, true);
  17756. }
  17757. #updateThickness(thickness) {
  17758. const savedThickness = this.#thickness;
  17759. const setThickness = th => {
  17760. this.#thickness = th;
  17761. this.#changeThickness(th);
  17762. };
  17763. this.addCommands({
  17764. cmd: setThickness.bind(this, thickness),
  17765. undo: setThickness.bind(this, savedThickness),
  17766. post: this._uiManager.updateUI.bind(this._uiManager, this),
  17767. mustExec: true,
  17768. type: AnnotationEditorParamsType.INK_THICKNESS,
  17769. overwriteIfSameType: true,
  17770. keepUndo: true
  17771. });
  17772. this._reportTelemetry({
  17773. action: "thickness_changed",
  17774. thickness
  17775. }, true);
  17776. }
  17777. async addEditToolbar() {
  17778. const toolbar = await super.addEditToolbar();
  17779. if (!toolbar) {
  17780. return null;
  17781. }
  17782. if (this._uiManager.highlightColors) {
  17783. this.#colorPicker = new ColorPicker({
  17784. editor: this
  17785. });
  17786. toolbar.addColorPicker(this.#colorPicker);
  17787. }
  17788. return toolbar;
  17789. }
  17790. disableEditing() {
  17791. super.disableEditing();
  17792. this.div.classList.toggle("disabled", true);
  17793. }
  17794. enableEditing() {
  17795. super.enableEditing();
  17796. this.div.classList.toggle("disabled", false);
  17797. }
  17798. fixAndSetPosition() {
  17799. return super.fixAndSetPosition(this.#getRotation());
  17800. }
  17801. getBaseTranslation() {
  17802. return [0, 0];
  17803. }
  17804. getRect(tx, ty) {
  17805. return super.getRect(tx, ty, this.#getRotation());
  17806. }
  17807. onceAdded(focus) {
  17808. if (!this.annotationElementId) {
  17809. this.parent.addUndoableEditor(this);
  17810. }
  17811. if (focus) {
  17812. this.div.focus();
  17813. }
  17814. }
  17815. remove() {
  17816. this.#cleanDrawLayer();
  17817. this._reportTelemetry({
  17818. action: "deleted"
  17819. });
  17820. super.remove();
  17821. }
  17822. rebuild() {
  17823. if (!this.parent) {
  17824. return;
  17825. }
  17826. super.rebuild();
  17827. if (this.div === null) {
  17828. return;
  17829. }
  17830. this.#addToDrawLayer();
  17831. if (!this.isAttachedToDOM) {
  17832. this.parent.add(this);
  17833. }
  17834. }
  17835. setParent(parent) {
  17836. let mustBeSelected = false;
  17837. if (this.parent && !parent) {
  17838. this.#cleanDrawLayer();
  17839. } else if (parent) {
  17840. this.#addToDrawLayer(parent);
  17841. mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
  17842. }
  17843. super.setParent(parent);
  17844. this.show(this._isVisible);
  17845. if (mustBeSelected) {
  17846. this.select();
  17847. }
  17848. }
  17849. #changeThickness(thickness) {
  17850. if (!this.#isFreeHighlight) {
  17851. return;
  17852. }
  17853. this.#createFreeOutlines({
  17854. highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
  17855. });
  17856. this.fixAndSetPosition();
  17857. const [parentWidth, parentHeight] = this.parentDimensions;
  17858. this.setDims(this.width * parentWidth, this.height * parentHeight);
  17859. }
  17860. #cleanDrawLayer() {
  17861. if (this.#id === null || !this.parent) {
  17862. return;
  17863. }
  17864. this.parent.drawLayer.remove(this.#id);
  17865. this.#id = null;
  17866. this.parent.drawLayer.remove(this.#outlineId);
  17867. this.#outlineId = null;
  17868. }
  17869. #addToDrawLayer(parent = this.parent) {
  17870. if (this.#id !== null) {
  17871. return;
  17872. }
  17873. ({
  17874. id: this.#id,
  17875. clipPathId: this.#clipPathId
  17876. } = parent.drawLayer.draw({
  17877. bbox: this.#highlightOutlines.box,
  17878. root: {
  17879. viewBox: "0 0 1 1",
  17880. fill: this.color,
  17881. "fill-opacity": this.#opacity
  17882. },
  17883. rootClass: {
  17884. highlight: true,
  17885. free: this.#isFreeHighlight
  17886. },
  17887. path: {
  17888. d: this.#highlightOutlines.toSVGPath()
  17889. }
  17890. }, false, true));
  17891. this.#outlineId = parent.drawLayer.drawOutline({
  17892. rootClass: {
  17893. highlightOutline: true,
  17894. free: this.#isFreeHighlight
  17895. },
  17896. bbox: this.#focusOutlines.box,
  17897. path: {
  17898. d: this.#focusOutlines.toSVGPath()
  17899. }
  17900. }, this.#isFreeHighlight);
  17901. if (this.#highlightDiv) {
  17902. this.#highlightDiv.style.clipPath = this.#clipPathId;
  17903. }
  17904. }
  17905. static #rotateBbox([x, y, width, height], angle) {
  17906. switch (angle) {
  17907. case 90:
  17908. return [1 - y - height, x, height, width];
  17909. case 180:
  17910. return [1 - x - width, 1 - y - height, width, height];
  17911. case 270:
  17912. return [y, 1 - x - width, height, width];
  17913. }
  17914. return [x, y, width, height];
  17915. }
  17916. rotate(angle) {
  17917. const {
  17918. drawLayer
  17919. } = this.parent;
  17920. let box;
  17921. if (this.#isFreeHighlight) {
  17922. angle = (angle - this.rotation + 360) % 360;
  17923. box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
  17924. } else {
  17925. box = HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle);
  17926. }
  17927. drawLayer.updateProperties(this.#id, {
  17928. bbox: box,
  17929. root: {
  17930. "data-main-rotation": angle
  17931. }
  17932. });
  17933. drawLayer.updateProperties(this.#outlineId, {
  17934. bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
  17935. root: {
  17936. "data-main-rotation": angle
  17937. }
  17938. });
  17939. }
  17940. render() {
  17941. if (this.div) {
  17942. return this.div;
  17943. }
  17944. const div = super.render();
  17945. if (this.#text) {
  17946. div.setAttribute("aria-label", this.#text);
  17947. div.setAttribute("role", "mark");
  17948. }
  17949. if (this.#isFreeHighlight) {
  17950. div.classList.add("free");
  17951. } else {
  17952. this.div.addEventListener("keydown", this.#keydown.bind(this), {
  17953. signal: this._uiManager._signal
  17954. });
  17955. }
  17956. const highlightDiv = this.#highlightDiv = document.createElement("div");
  17957. div.append(highlightDiv);
  17958. highlightDiv.setAttribute("aria-hidden", "true");
  17959. highlightDiv.className = "internal";
  17960. highlightDiv.style.clipPath = this.#clipPathId;
  17961. const [parentWidth, parentHeight] = this.parentDimensions;
  17962. this.setDims(this.width * parentWidth, this.height * parentHeight);
  17963. bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
  17964. this.enableEditing();
  17965. return div;
  17966. }
  17967. pointerover() {
  17968. if (!this.isSelected) {
  17969. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  17970. rootClass: {
  17971. hovered: true
  17972. }
  17973. });
  17974. }
  17975. }
  17976. pointerleave() {
  17977. if (!this.isSelected) {
  17978. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  17979. rootClass: {
  17980. hovered: false
  17981. }
  17982. });
  17983. }
  17984. }
  17985. #keydown(event) {
  17986. HighlightEditor._keyboardManager.exec(this, event);
  17987. }
  17988. _moveCaret(direction) {
  17989. this.parent.unselect(this);
  17990. switch (direction) {
  17991. case 0:
  17992. case 2:
  17993. this.#setCaret(true);
  17994. break;
  17995. case 1:
  17996. case 3:
  17997. this.#setCaret(false);
  17998. break;
  17999. }
  18000. }
  18001. #setCaret(start) {
  18002. if (!this.#anchorNode) {
  18003. return;
  18004. }
  18005. const selection = window.getSelection();
  18006. if (start) {
  18007. selection.setPosition(this.#anchorNode, this.#anchorOffset);
  18008. } else {
  18009. selection.setPosition(this.#focusNode, this.#focusOffset);
  18010. }
  18011. }
  18012. select() {
  18013. super.select();
  18014. if (!this.#outlineId) {
  18015. return;
  18016. }
  18017. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  18018. rootClass: {
  18019. hovered: false,
  18020. selected: true
  18021. }
  18022. });
  18023. }
  18024. unselect() {
  18025. super.unselect();
  18026. if (!this.#outlineId) {
  18027. return;
  18028. }
  18029. this.parent?.drawLayer.updateProperties(this.#outlineId, {
  18030. rootClass: {
  18031. selected: false
  18032. }
  18033. });
  18034. if (!this.#isFreeHighlight) {
  18035. this.#setCaret(false);
  18036. }
  18037. }
  18038. get _mustFixPosition() {
  18039. return !this.#isFreeHighlight;
  18040. }
  18041. show(visible = this._isVisible) {
  18042. super.show(visible);
  18043. if (this.parent) {
  18044. this.parent.drawLayer.updateProperties(this.#id, {
  18045. rootClass: {
  18046. hidden: !visible
  18047. }
  18048. });
  18049. this.parent.drawLayer.updateProperties(this.#outlineId, {
  18050. rootClass: {
  18051. hidden: !visible
  18052. }
  18053. });
  18054. }
  18055. }
  18056. #getRotation() {
  18057. return this.#isFreeHighlight ? this.rotation : 0;
  18058. }
  18059. #serializeBoxes() {
  18060. if (this.#isFreeHighlight) {
  18061. return null;
  18062. }
  18063. const [pageWidth, pageHeight] = this.pageDimensions;
  18064. const [pageX, pageY] = this.pageTranslation;
  18065. const boxes = this.#boxes;
  18066. const quadPoints = new Float32Array(boxes.length * 8);
  18067. let i = 0;
  18068. for (const {
  18069. x,
  18070. y,
  18071. width,
  18072. height
  18073. } of boxes) {
  18074. const sx = x * pageWidth + pageX;
  18075. const sy = (1 - y) * pageHeight + pageY;
  18076. quadPoints[i] = quadPoints[i + 4] = sx;
  18077. quadPoints[i + 1] = quadPoints[i + 3] = sy;
  18078. quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth;
  18079. quadPoints[i + 5] = quadPoints[i + 7] = sy - height * pageHeight;
  18080. i += 8;
  18081. }
  18082. return quadPoints;
  18083. }
  18084. #serializeOutlines(rect) {
  18085. return this.#highlightOutlines.serialize(rect, this.#getRotation());
  18086. }
  18087. static startHighlighting(parent, isLTR, {
  18088. target: textLayer,
  18089. x,
  18090. y
  18091. }) {
  18092. const {
  18093. x: layerX,
  18094. y: layerY,
  18095. width: parentWidth,
  18096. height: parentHeight
  18097. } = textLayer.getBoundingClientRect();
  18098. const ac = new AbortController();
  18099. const signal = parent.combinedSignal(ac);
  18100. const pointerUpCallback = e => {
  18101. ac.abort();
  18102. this.#endHighlight(parent, e);
  18103. };
  18104. window.addEventListener("blur", pointerUpCallback, {
  18105. signal
  18106. });
  18107. window.addEventListener("pointerup", pointerUpCallback, {
  18108. signal
  18109. });
  18110. window.addEventListener("pointerdown", stopEvent, {
  18111. capture: true,
  18112. passive: false,
  18113. signal
  18114. });
  18115. window.addEventListener("contextmenu", noContextMenu, {
  18116. signal
  18117. });
  18118. textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {
  18119. signal
  18120. });
  18121. this._freeHighlight = new FreeHighlightOutliner({
  18122. x,
  18123. y
  18124. }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001);
  18125. ({
  18126. id: this._freeHighlightId,
  18127. clipPathId: this._freeHighlightClipId
  18128. } = parent.drawLayer.draw({
  18129. bbox: [0, 0, 1, 1],
  18130. root: {
  18131. viewBox: "0 0 1 1",
  18132. fill: this._defaultColor,
  18133. "fill-opacity": this._defaultOpacity
  18134. },
  18135. rootClass: {
  18136. highlight: true,
  18137. free: true
  18138. },
  18139. path: {
  18140. d: this._freeHighlight.toSVGPath()
  18141. }
  18142. }, true, true));
  18143. }
  18144. static #highlightMove(parent, event) {
  18145. if (this._freeHighlight.add(event)) {
  18146. parent.drawLayer.updateProperties(this._freeHighlightId, {
  18147. path: {
  18148. d: this._freeHighlight.toSVGPath()
  18149. }
  18150. });
  18151. }
  18152. }
  18153. static #endHighlight(parent, event) {
  18154. if (!this._freeHighlight.isEmpty()) {
  18155. parent.createAndAddNewEditor(event, false, {
  18156. highlightId: this._freeHighlightId,
  18157. highlightOutlines: this._freeHighlight.getOutlines(),
  18158. clipPathId: this._freeHighlightClipId,
  18159. methodOfCreation: "main_toolbar"
  18160. });
  18161. } else {
  18162. parent.drawLayer.remove(this._freeHighlightId);
  18163. }
  18164. this._freeHighlightId = -1;
  18165. this._freeHighlight = null;
  18166. this._freeHighlightClipId = "";
  18167. }
  18168. static async deserialize(data, parent, uiManager) {
  18169. let initialData = null;
  18170. if (data instanceof HighlightAnnotationElement) {
  18171. const {
  18172. data: {
  18173. quadPoints,
  18174. rect,
  18175. rotation,
  18176. id,
  18177. color,
  18178. opacity,
  18179. popupRef
  18180. },
  18181. parent: {
  18182. page: {
  18183. pageNumber
  18184. }
  18185. }
  18186. } = data;
  18187. initialData = data = {
  18188. annotationType: AnnotationEditorType.HIGHLIGHT,
  18189. color: Array.from(color),
  18190. opacity,
  18191. quadPoints,
  18192. boxes: null,
  18193. pageIndex: pageNumber - 1,
  18194. rect: rect.slice(0),
  18195. rotation,
  18196. id,
  18197. deleted: false,
  18198. popupRef
  18199. };
  18200. } else if (data instanceof InkAnnotationElement) {
  18201. const {
  18202. data: {
  18203. inkLists,
  18204. rect,
  18205. rotation,
  18206. id,
  18207. color,
  18208. borderStyle: {
  18209. rawWidth: thickness
  18210. },
  18211. popupRef
  18212. },
  18213. parent: {
  18214. page: {
  18215. pageNumber
  18216. }
  18217. }
  18218. } = data;
  18219. initialData = data = {
  18220. annotationType: AnnotationEditorType.HIGHLIGHT,
  18221. color: Array.from(color),
  18222. thickness,
  18223. inkLists,
  18224. boxes: null,
  18225. pageIndex: pageNumber - 1,
  18226. rect: rect.slice(0),
  18227. rotation,
  18228. id,
  18229. deleted: false,
  18230. popupRef
  18231. };
  18232. }
  18233. const {
  18234. color,
  18235. quadPoints,
  18236. inkLists,
  18237. opacity
  18238. } = data;
  18239. const editor = await super.deserialize(data, parent, uiManager);
  18240. editor.color = Util.makeHexColor(...color);
  18241. editor.#opacity = opacity || 1;
  18242. if (inkLists) {
  18243. editor.#thickness = data.thickness;
  18244. }
  18245. editor.annotationElementId = data.id || null;
  18246. editor._initialData = initialData;
  18247. const [pageWidth, pageHeight] = editor.pageDimensions;
  18248. const [pageX, pageY] = editor.pageTranslation;
  18249. if (quadPoints) {
  18250. const boxes = editor.#boxes = [];
  18251. for (let i = 0; i < quadPoints.length; i += 8) {
  18252. boxes.push({
  18253. x: (quadPoints[i] - pageX) / pageWidth,
  18254. y: 1 - (quadPoints[i + 1] - pageY) / pageHeight,
  18255. width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth,
  18256. height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight
  18257. });
  18258. }
  18259. editor.#createOutlines();
  18260. editor.#addToDrawLayer();
  18261. editor.rotate(editor.rotation);
  18262. } else if (inkLists) {
  18263. editor.#isFreeHighlight = true;
  18264. const points = inkLists[0];
  18265. const point = {
  18266. x: points[0] - pageX,
  18267. y: pageHeight - (points[1] - pageY)
  18268. };
  18269. const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001);
  18270. for (let i = 0, ii = points.length; i < ii; i += 2) {
  18271. point.x = points[i] - pageX;
  18272. point.y = pageHeight - (points[i + 1] - pageY);
  18273. outliner.add(point);
  18274. }
  18275. const {
  18276. id,
  18277. clipPathId
  18278. } = parent.drawLayer.draw({
  18279. bbox: [0, 0, 1, 1],
  18280. root: {
  18281. viewBox: "0 0 1 1",
  18282. fill: editor.color,
  18283. "fill-opacity": editor._defaultOpacity
  18284. },
  18285. rootClass: {
  18286. highlight: true,
  18287. free: true
  18288. },
  18289. path: {
  18290. d: outliner.toSVGPath()
  18291. }
  18292. }, true, true);
  18293. editor.#createFreeOutlines({
  18294. highlightOutlines: outliner.getOutlines(),
  18295. highlightId: id,
  18296. clipPathId
  18297. });
  18298. editor.#addToDrawLayer();
  18299. }
  18300. return editor;
  18301. }
  18302. serialize(isForCopying = false) {
  18303. if (this.isEmpty() || isForCopying) {
  18304. return null;
  18305. }
  18306. if (this.deleted) {
  18307. return this.serializeDeleted();
  18308. }
  18309. const rect = this.getRect(0, 0);
  18310. const color = AnnotationEditor._colorManager.convert(this.color);
  18311. const serialized = {
  18312. annotationType: AnnotationEditorType.HIGHLIGHT,
  18313. color,
  18314. opacity: this.#opacity,
  18315. thickness: this.#thickness,
  18316. quadPoints: this.#serializeBoxes(),
  18317. outlines: this.#serializeOutlines(rect),
  18318. pageIndex: this.pageIndex,
  18319. rect,
  18320. rotation: this.#getRotation(),
  18321. structTreeParentId: this._structTreeParentId
  18322. };
  18323. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  18324. return null;
  18325. }
  18326. serialized.id = this.annotationElementId;
  18327. return serialized;
  18328. }
  18329. #hasElementChanged(serialized) {
  18330. const {
  18331. color
  18332. } = this._initialData;
  18333. return serialized.color.some((c, i) => c !== color[i]);
  18334. }
  18335. renderAnnotationElement(annotation) {
  18336. annotation.updateEdited({
  18337. rect: this.getRect(0, 0)
  18338. });
  18339. return null;
  18340. }
  18341. static canCreateNewEmptyEditor() {
  18342. return false;
  18343. }
  18344. }
  18345. ;// ./src/display/editor/draw.js
  18346. class DrawingOptions {
  18347. #svgProperties = Object.create(null);
  18348. updateProperty(name, value) {
  18349. this[name] = value;
  18350. this.updateSVGProperty(name, value);
  18351. }
  18352. updateProperties(properties) {
  18353. if (!properties) {
  18354. return;
  18355. }
  18356. for (const [name, value] of Object.entries(properties)) {
  18357. this.updateProperty(name, value);
  18358. }
  18359. }
  18360. updateSVGProperty(name, value) {
  18361. this.#svgProperties[name] = value;
  18362. }
  18363. toSVGProperties() {
  18364. const root = this.#svgProperties;
  18365. this.#svgProperties = Object.create(null);
  18366. return {
  18367. root
  18368. };
  18369. }
  18370. reset() {
  18371. this.#svgProperties = Object.create(null);
  18372. }
  18373. updateAll(options = this) {
  18374. this.updateProperties(options);
  18375. }
  18376. clone() {
  18377. unreachable("Not implemented");
  18378. }
  18379. }
  18380. class DrawingEditor extends AnnotationEditor {
  18381. #drawOutlines = null;
  18382. #mustBeCommitted;
  18383. _drawId = null;
  18384. static _currentDrawId = -1;
  18385. static _currentParent = null;
  18386. static #currentDraw = null;
  18387. static #currentDrawingAC = null;
  18388. static #currentDrawingOptions = null;
  18389. static #currentPointerId = NaN;
  18390. static #currentPointerType = null;
  18391. static #currentPointerIds = null;
  18392. static #currentMoveTimestamp = NaN;
  18393. static _INNER_MARGIN = 3;
  18394. constructor(params) {
  18395. super(params);
  18396. this.#mustBeCommitted = params.mustBeCommitted || false;
  18397. if (params.drawOutlines) {
  18398. this.#createDrawOutlines(params);
  18399. this.#addToDrawLayer();
  18400. }
  18401. }
  18402. #createDrawOutlines({
  18403. drawOutlines,
  18404. drawId,
  18405. drawingOptions
  18406. }) {
  18407. this.#drawOutlines = drawOutlines;
  18408. this._drawingOptions ||= drawingOptions;
  18409. if (drawId >= 0) {
  18410. this._drawId = drawId;
  18411. this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties);
  18412. } else {
  18413. this._drawId = this.#createDrawing(drawOutlines, this.parent);
  18414. }
  18415. this.#updateBbox(drawOutlines.box);
  18416. }
  18417. #createDrawing(drawOutlines, parent) {
  18418. const {
  18419. id
  18420. } = parent.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false);
  18421. return id;
  18422. }
  18423. static _mergeSVGProperties(p1, p2) {
  18424. const p1Keys = new Set(Object.keys(p1));
  18425. for (const [key, value] of Object.entries(p2)) {
  18426. if (p1Keys.has(key)) {
  18427. Object.assign(p1[key], value);
  18428. } else {
  18429. p1[key] = value;
  18430. }
  18431. }
  18432. return p1;
  18433. }
  18434. static getDefaultDrawingOptions(_options) {
  18435. unreachable("Not implemented");
  18436. }
  18437. static get typesMap() {
  18438. unreachable("Not implemented");
  18439. }
  18440. static get isDrawer() {
  18441. return true;
  18442. }
  18443. static get supportMultipleDrawings() {
  18444. return false;
  18445. }
  18446. static updateDefaultParams(type, value) {
  18447. const propertyName = this.typesMap.get(type);
  18448. if (propertyName) {
  18449. this._defaultDrawingOptions.updateProperty(propertyName, value);
  18450. }
  18451. if (this._currentParent) {
  18452. DrawingEditor.#currentDraw.updateProperty(propertyName, value);
  18453. this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
  18454. }
  18455. }
  18456. updateParams(type, value) {
  18457. const propertyName = this.constructor.typesMap.get(type);
  18458. if (propertyName) {
  18459. this._updateProperty(type, propertyName, value);
  18460. }
  18461. }
  18462. static get defaultPropertiesToUpdate() {
  18463. const properties = [];
  18464. const options = this._defaultDrawingOptions;
  18465. for (const [type, name] of this.typesMap) {
  18466. properties.push([type, options[name]]);
  18467. }
  18468. return properties;
  18469. }
  18470. get propertiesToUpdate() {
  18471. const properties = [];
  18472. const {
  18473. _drawingOptions
  18474. } = this;
  18475. for (const [type, name] of this.constructor.typesMap) {
  18476. properties.push([type, _drawingOptions[name]]);
  18477. }
  18478. return properties;
  18479. }
  18480. _updateProperty(type, name, value) {
  18481. const options = this._drawingOptions;
  18482. const savedValue = options[name];
  18483. const setter = val => {
  18484. options.updateProperty(name, val);
  18485. const bbox = this.#drawOutlines.updateProperty(name, val);
  18486. if (bbox) {
  18487. this.#updateBbox(bbox);
  18488. }
  18489. this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties());
  18490. };
  18491. this.addCommands({
  18492. cmd: setter.bind(this, value),
  18493. undo: setter.bind(this, savedValue),
  18494. post: this._uiManager.updateUI.bind(this._uiManager, this),
  18495. mustExec: true,
  18496. type,
  18497. overwriteIfSameType: true,
  18498. keepUndo: true
  18499. });
  18500. }
  18501. _onResizing() {
  18502. this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), {
  18503. bbox: this.#rotateBox()
  18504. }));
  18505. }
  18506. _onResized() {
  18507. this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), {
  18508. bbox: this.#rotateBox()
  18509. }));
  18510. }
  18511. _onTranslating(x, y) {
  18512. this.parent?.drawLayer.updateProperties(this._drawId, {
  18513. bbox: this.#rotateBox(x, y)
  18514. });
  18515. }
  18516. _onTranslated() {
  18517. this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), {
  18518. bbox: this.#rotateBox()
  18519. }));
  18520. }
  18521. _onStartDragging() {
  18522. this.parent?.drawLayer.updateProperties(this._drawId, {
  18523. rootClass: {
  18524. moving: true
  18525. }
  18526. });
  18527. }
  18528. _onStopDragging() {
  18529. this.parent?.drawLayer.updateProperties(this._drawId, {
  18530. rootClass: {
  18531. moving: false
  18532. }
  18533. });
  18534. }
  18535. commit() {
  18536. super.commit();
  18537. this.disableEditMode();
  18538. this.disableEditing();
  18539. }
  18540. disableEditing() {
  18541. super.disableEditing();
  18542. this.div.classList.toggle("disabled", true);
  18543. }
  18544. enableEditing() {
  18545. super.enableEditing();
  18546. this.div.classList.toggle("disabled", false);
  18547. }
  18548. getBaseTranslation() {
  18549. return [0, 0];
  18550. }
  18551. get isResizable() {
  18552. return true;
  18553. }
  18554. onceAdded(focus) {
  18555. if (!this.annotationElementId) {
  18556. this.parent.addUndoableEditor(this);
  18557. }
  18558. this._isDraggable = true;
  18559. if (this.#mustBeCommitted) {
  18560. this.#mustBeCommitted = false;
  18561. this.commit();
  18562. this.parent.setSelected(this);
  18563. if (focus && this.isOnScreen) {
  18564. this.div.focus();
  18565. }
  18566. }
  18567. }
  18568. remove() {
  18569. this.#cleanDrawLayer();
  18570. super.remove();
  18571. }
  18572. rebuild() {
  18573. if (!this.parent) {
  18574. return;
  18575. }
  18576. super.rebuild();
  18577. if (this.div === null) {
  18578. return;
  18579. }
  18580. this.#addToDrawLayer();
  18581. this.#updateBbox(this.#drawOutlines.box);
  18582. if (!this.isAttachedToDOM) {
  18583. this.parent.add(this);
  18584. }
  18585. }
  18586. setParent(parent) {
  18587. let mustBeSelected = false;
  18588. if (this.parent && !parent) {
  18589. this._uiManager.removeShouldRescale(this);
  18590. this.#cleanDrawLayer();
  18591. } else if (parent) {
  18592. this._uiManager.addShouldRescale(this);
  18593. this.#addToDrawLayer(parent);
  18594. mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
  18595. }
  18596. super.setParent(parent);
  18597. if (mustBeSelected) {
  18598. this.select();
  18599. }
  18600. }
  18601. #cleanDrawLayer() {
  18602. if (this._drawId === null || !this.parent) {
  18603. return;
  18604. }
  18605. this.parent.drawLayer.remove(this._drawId);
  18606. this._drawId = null;
  18607. this._drawingOptions.reset();
  18608. }
  18609. #addToDrawLayer(parent = this.parent) {
  18610. if (this._drawId !== null && this.parent === parent) {
  18611. return;
  18612. }
  18613. if (this._drawId !== null) {
  18614. this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer);
  18615. return;
  18616. }
  18617. this._drawingOptions.updateAll();
  18618. this._drawId = this.#createDrawing(this.#drawOutlines, parent);
  18619. }
  18620. #convertToParentSpace([x, y, width, height]) {
  18621. const {
  18622. parentDimensions: [pW, pH],
  18623. rotation
  18624. } = this;
  18625. switch (rotation) {
  18626. case 90:
  18627. return [y, 1 - x, width * (pH / pW), height * (pW / pH)];
  18628. case 180:
  18629. return [1 - x, 1 - y, width, height];
  18630. case 270:
  18631. return [1 - y, x, width * (pH / pW), height * (pW / pH)];
  18632. default:
  18633. return [x, y, width, height];
  18634. }
  18635. }
  18636. #convertToDrawSpace() {
  18637. const {
  18638. x,
  18639. y,
  18640. width,
  18641. height,
  18642. parentDimensions: [pW, pH],
  18643. rotation
  18644. } = this;
  18645. switch (rotation) {
  18646. case 90:
  18647. return [1 - y, x, width * (pW / pH), height * (pH / pW)];
  18648. case 180:
  18649. return [1 - x, 1 - y, width, height];
  18650. case 270:
  18651. return [y, 1 - x, width * (pW / pH), height * (pH / pW)];
  18652. default:
  18653. return [x, y, width, height];
  18654. }
  18655. }
  18656. #updateBbox(bbox) {
  18657. [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox);
  18658. if (this.div) {
  18659. this.fixAndSetPosition();
  18660. const [parentWidth, parentHeight] = this.parentDimensions;
  18661. this.setDims(this.width * parentWidth, this.height * parentHeight);
  18662. }
  18663. this._onResized();
  18664. }
  18665. #rotateBox() {
  18666. const {
  18667. x,
  18668. y,
  18669. width,
  18670. height,
  18671. rotation,
  18672. parentRotation,
  18673. parentDimensions: [pW, pH]
  18674. } = this;
  18675. switch ((rotation * 4 + parentRotation) / 90) {
  18676. case 1:
  18677. return [1 - y - height, x, height, width];
  18678. case 2:
  18679. return [1 - x - width, 1 - y - height, width, height];
  18680. case 3:
  18681. return [y, 1 - x - width, height, width];
  18682. case 4:
  18683. return [x, y - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
  18684. case 5:
  18685. return [1 - y, x, width * (pW / pH), height * (pH / pW)];
  18686. case 6:
  18687. return [1 - x - height * (pH / pW), 1 - y, height * (pH / pW), width * (pW / pH)];
  18688. case 7:
  18689. return [y - width * (pW / pH), 1 - x - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
  18690. case 8:
  18691. return [x - width, y - height, width, height];
  18692. case 9:
  18693. return [1 - y, x - width, height, width];
  18694. case 10:
  18695. return [1 - x, 1 - y, width, height];
  18696. case 11:
  18697. return [y - height, 1 - x, height, width];
  18698. case 12:
  18699. return [x - height * (pH / pW), y, height * (pH / pW), width * (pW / pH)];
  18700. case 13:
  18701. return [1 - y - width * (pW / pH), x - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
  18702. case 14:
  18703. return [1 - x, 1 - y - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
  18704. case 15:
  18705. return [y, 1 - x, width * (pW / pH), height * (pH / pW)];
  18706. default:
  18707. return [x, y, width, height];
  18708. }
  18709. }
  18710. rotate() {
  18711. if (!this.parent) {
  18712. return;
  18713. }
  18714. this.parent.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties({
  18715. bbox: this.#rotateBox()
  18716. }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360)));
  18717. }
  18718. onScaleChanging() {
  18719. if (!this.parent) {
  18720. return;
  18721. }
  18722. this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale));
  18723. }
  18724. static onScaleChangingWhenDrawing() {}
  18725. render() {
  18726. if (this.div) {
  18727. return this.div;
  18728. }
  18729. const div = super.render();
  18730. div.classList.add("draw");
  18731. const drawDiv = document.createElement("div");
  18732. div.append(drawDiv);
  18733. drawDiv.setAttribute("aria-hidden", "true");
  18734. drawDiv.className = "internal";
  18735. const [parentWidth, parentHeight] = this.parentDimensions;
  18736. this.setDims(this.width * parentWidth, this.height * parentHeight);
  18737. this._uiManager.addShouldRescale(this);
  18738. this.disableEditing();
  18739. return div;
  18740. }
  18741. static createDrawerInstance(_x, _y, _parentWidth, _parentHeight, _rotation) {
  18742. unreachable("Not implemented");
  18743. }
  18744. static startDrawing(parent, uiManager, _isLTR, event) {
  18745. const {
  18746. target,
  18747. offsetX: x,
  18748. offsetY: y,
  18749. pointerId,
  18750. pointerType
  18751. } = event;
  18752. if (DrawingEditor.#currentPointerType && DrawingEditor.#currentPointerType !== pointerType) {
  18753. return;
  18754. }
  18755. const {
  18756. viewport: {
  18757. rotation
  18758. }
  18759. } = parent;
  18760. const {
  18761. width: parentWidth,
  18762. height: parentHeight
  18763. } = target.getBoundingClientRect();
  18764. const ac = DrawingEditor.#currentDrawingAC = new AbortController();
  18765. const signal = parent.combinedSignal(ac);
  18766. DrawingEditor.#currentPointerId ||= pointerId;
  18767. DrawingEditor.#currentPointerType ??= pointerType;
  18768. window.addEventListener("pointerup", e => {
  18769. if (DrawingEditor.#currentPointerId === e.pointerId) {
  18770. this._endDraw(e);
  18771. } else {
  18772. DrawingEditor.#currentPointerIds?.delete(e.pointerId);
  18773. }
  18774. }, {
  18775. signal
  18776. });
  18777. window.addEventListener("pointercancel", e => {
  18778. if (DrawingEditor.#currentPointerId === e.pointerId) {
  18779. this._currentParent.endDrawingSession();
  18780. } else {
  18781. DrawingEditor.#currentPointerIds?.delete(e.pointerId);
  18782. }
  18783. }, {
  18784. signal
  18785. });
  18786. window.addEventListener("pointerdown", e => {
  18787. if (DrawingEditor.#currentPointerType !== e.pointerType) {
  18788. return;
  18789. }
  18790. (DrawingEditor.#currentPointerIds ||= new Set()).add(e.pointerId);
  18791. if (DrawingEditor.#currentDraw.isCancellable()) {
  18792. DrawingEditor.#currentDraw.removeLastElement();
  18793. if (DrawingEditor.#currentDraw.isEmpty()) {
  18794. this._currentParent.endDrawingSession(true);
  18795. } else {
  18796. this._endDraw(null);
  18797. }
  18798. }
  18799. }, {
  18800. capture: true,
  18801. passive: false,
  18802. signal
  18803. });
  18804. window.addEventListener("contextmenu", noContextMenu, {
  18805. signal
  18806. });
  18807. target.addEventListener("pointermove", this._drawMove.bind(this), {
  18808. signal
  18809. });
  18810. target.addEventListener("touchmove", e => {
  18811. if (e.timeStamp === DrawingEditor.#currentMoveTimestamp) {
  18812. stopEvent(e);
  18813. }
  18814. }, {
  18815. signal
  18816. });
  18817. parent.toggleDrawing();
  18818. uiManager._editorUndoBar?.hide();
  18819. if (DrawingEditor.#currentDraw) {
  18820. parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.startNew(x, y, parentWidth, parentHeight, rotation));
  18821. return;
  18822. }
  18823. uiManager.updateUIForDefaultProperties(this);
  18824. DrawingEditor.#currentDraw = this.createDrawerInstance(x, y, parentWidth, parentHeight, rotation);
  18825. DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions();
  18826. this._currentParent = parent;
  18827. ({
  18828. id: this._currentDrawId
  18829. } = parent.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#currentDrawingOptions.toSVGProperties(), DrawingEditor.#currentDraw.defaultSVGProperties), true, false));
  18830. }
  18831. static _drawMove(event) {
  18832. DrawingEditor.#currentMoveTimestamp = -1;
  18833. if (!DrawingEditor.#currentDraw) {
  18834. return;
  18835. }
  18836. const {
  18837. offsetX,
  18838. offsetY,
  18839. pointerId
  18840. } = event;
  18841. if (DrawingEditor.#currentPointerId !== pointerId) {
  18842. return;
  18843. }
  18844. if (DrawingEditor.#currentPointerIds?.size >= 1) {
  18845. this._endDraw(event);
  18846. return;
  18847. }
  18848. this._currentParent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.add(offsetX, offsetY));
  18849. DrawingEditor.#currentMoveTimestamp = event.timeStamp;
  18850. stopEvent(event);
  18851. }
  18852. static _cleanup(all) {
  18853. if (all) {
  18854. this._currentDrawId = -1;
  18855. this._currentParent = null;
  18856. DrawingEditor.#currentDraw = null;
  18857. DrawingEditor.#currentDrawingOptions = null;
  18858. DrawingEditor.#currentPointerType = null;
  18859. DrawingEditor.#currentMoveTimestamp = NaN;
  18860. }
  18861. if (DrawingEditor.#currentDrawingAC) {
  18862. DrawingEditor.#currentDrawingAC.abort();
  18863. DrawingEditor.#currentDrawingAC = null;
  18864. DrawingEditor.#currentPointerId = NaN;
  18865. DrawingEditor.#currentPointerIds = null;
  18866. }
  18867. }
  18868. static _endDraw(event) {
  18869. const parent = this._currentParent;
  18870. if (!parent) {
  18871. return;
  18872. }
  18873. parent.toggleDrawing(true);
  18874. this._cleanup(false);
  18875. if (event) {
  18876. parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY));
  18877. }
  18878. if (this.supportMultipleDrawings) {
  18879. const draw = DrawingEditor.#currentDraw;
  18880. const drawId = this._currentDrawId;
  18881. const lastElement = draw.getLastElement();
  18882. parent.addCommands({
  18883. cmd: () => {
  18884. parent.drawLayer.updateProperties(drawId, draw.setLastElement(lastElement));
  18885. },
  18886. undo: () => {
  18887. parent.drawLayer.updateProperties(drawId, draw.removeLastElement());
  18888. },
  18889. mustExec: false,
  18890. type: AnnotationEditorParamsType.DRAW_STEP
  18891. });
  18892. return;
  18893. }
  18894. this.endDrawing(false);
  18895. }
  18896. static endDrawing(isAborted) {
  18897. const parent = this._currentParent;
  18898. if (!parent) {
  18899. return null;
  18900. }
  18901. parent.toggleDrawing(true);
  18902. parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP);
  18903. if (!DrawingEditor.#currentDraw.isEmpty()) {
  18904. const {
  18905. pageDimensions: [pageWidth, pageHeight],
  18906. scale
  18907. } = parent;
  18908. const editor = parent.createAndAddNewEditor({
  18909. offsetX: 0,
  18910. offsetY: 0
  18911. }, false, {
  18912. drawId: this._currentDrawId,
  18913. drawOutlines: DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN),
  18914. drawingOptions: DrawingEditor.#currentDrawingOptions,
  18915. mustBeCommitted: !isAborted
  18916. });
  18917. this._cleanup(true);
  18918. return editor;
  18919. }
  18920. parent.drawLayer.remove(this._currentDrawId);
  18921. this._cleanup(true);
  18922. return null;
  18923. }
  18924. createDrawingOptions(_data) {}
  18925. static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) {
  18926. unreachable("Not implemented");
  18927. }
  18928. static async deserialize(data, parent, uiManager) {
  18929. const {
  18930. rawDims: {
  18931. pageWidth,
  18932. pageHeight,
  18933. pageX,
  18934. pageY
  18935. }
  18936. } = parent.viewport;
  18937. const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data);
  18938. const editor = await super.deserialize(data, parent, uiManager);
  18939. editor.createDrawingOptions(data);
  18940. editor.#createDrawOutlines({
  18941. drawOutlines
  18942. });
  18943. editor.#addToDrawLayer();
  18944. editor.onScaleChanging();
  18945. editor.rotate();
  18946. return editor;
  18947. }
  18948. serializeDraw(isForCopying) {
  18949. const [pageX, pageY] = this.pageTranslation;
  18950. const [pageWidth, pageHeight] = this.pageDimensions;
  18951. return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying);
  18952. }
  18953. renderAnnotationElement(annotation) {
  18954. annotation.updateEdited({
  18955. rect: this.getRect(0, 0)
  18956. });
  18957. return null;
  18958. }
  18959. static canCreateNewEmptyEditor() {
  18960. return false;
  18961. }
  18962. }
  18963. ;// ./src/display/editor/drawers/inkdraw.js
  18964. class InkDrawOutliner {
  18965. #last = new Float64Array(6);
  18966. #line;
  18967. #lines;
  18968. #rotation;
  18969. #thickness;
  18970. #points;
  18971. #lastSVGPath = "";
  18972. #lastIndex = 0;
  18973. #outlines = new InkDrawOutline();
  18974. #parentWidth;
  18975. #parentHeight;
  18976. constructor(x, y, parentWidth, parentHeight, rotation, thickness) {
  18977. this.#parentWidth = parentWidth;
  18978. this.#parentHeight = parentHeight;
  18979. this.#rotation = rotation;
  18980. this.#thickness = thickness;
  18981. [x, y] = this.#normalizePoint(x, y);
  18982. const line = this.#line = [NaN, NaN, NaN, NaN, x, y];
  18983. this.#points = [x, y];
  18984. this.#lines = [{
  18985. line,
  18986. points: this.#points
  18987. }];
  18988. this.#last.set(line, 0);
  18989. }
  18990. updateProperty(name, value) {
  18991. if (name === "stroke-width") {
  18992. this.#thickness = value;
  18993. }
  18994. }
  18995. #normalizePoint(x, y) {
  18996. return Outline._normalizePoint(x, y, this.#parentWidth, this.#parentHeight, this.#rotation);
  18997. }
  18998. isEmpty() {
  18999. return !this.#lines || this.#lines.length === 0;
  19000. }
  19001. isCancellable() {
  19002. return this.#points.length <= 10;
  19003. }
  19004. add(x, y) {
  19005. [x, y] = this.#normalizePoint(x, y);
  19006. const [x1, y1, x2, y2] = this.#last.subarray(2, 6);
  19007. const diffX = x - x2;
  19008. const diffY = y - y2;
  19009. const d = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY);
  19010. if (d <= 2) {
  19011. return null;
  19012. }
  19013. this.#points.push(x, y);
  19014. if (isNaN(x1)) {
  19015. this.#last.set([x2, y2, x, y], 2);
  19016. this.#line.push(NaN, NaN, NaN, NaN, x, y);
  19017. return {
  19018. path: {
  19019. d: this.toSVGPath()
  19020. }
  19021. };
  19022. }
  19023. if (isNaN(this.#last[0])) {
  19024. this.#line.splice(6, 6);
  19025. }
  19026. this.#last.set([x1, y1, x2, y2, x, y], 0);
  19027. this.#line.push(...Outline.createBezierPoints(x1, y1, x2, y2, x, y));
  19028. return {
  19029. path: {
  19030. d: this.toSVGPath()
  19031. }
  19032. };
  19033. }
  19034. end(x, y) {
  19035. const change = this.add(x, y);
  19036. if (change) {
  19037. return change;
  19038. }
  19039. if (this.#points.length === 2) {
  19040. return {
  19041. path: {
  19042. d: this.toSVGPath()
  19043. }
  19044. };
  19045. }
  19046. return null;
  19047. }
  19048. startNew(x, y, parentWidth, parentHeight, rotation) {
  19049. this.#parentWidth = parentWidth;
  19050. this.#parentHeight = parentHeight;
  19051. this.#rotation = rotation;
  19052. [x, y] = this.#normalizePoint(x, y);
  19053. const line = this.#line = [NaN, NaN, NaN, NaN, x, y];
  19054. this.#points = [x, y];
  19055. const last = this.#lines.at(-1);
  19056. if (last) {
  19057. last.line = new Float32Array(last.line);
  19058. last.points = new Float32Array(last.points);
  19059. }
  19060. this.#lines.push({
  19061. line,
  19062. points: this.#points
  19063. });
  19064. this.#last.set(line, 0);
  19065. this.#lastIndex = 0;
  19066. this.toSVGPath();
  19067. return null;
  19068. }
  19069. getLastElement() {
  19070. return this.#lines.at(-1);
  19071. }
  19072. setLastElement(element) {
  19073. if (!this.#lines) {
  19074. return this.#outlines.setLastElement(element);
  19075. }
  19076. this.#lines.push(element);
  19077. this.#line = element.line;
  19078. this.#points = element.points;
  19079. this.#lastIndex = 0;
  19080. return {
  19081. path: {
  19082. d: this.toSVGPath()
  19083. }
  19084. };
  19085. }
  19086. removeLastElement() {
  19087. if (!this.#lines) {
  19088. return this.#outlines.removeLastElement();
  19089. }
  19090. this.#lines.pop();
  19091. this.#lastSVGPath = "";
  19092. for (let i = 0, ii = this.#lines.length; i < ii; i++) {
  19093. const {
  19094. line,
  19095. points
  19096. } = this.#lines[i];
  19097. this.#line = line;
  19098. this.#points = points;
  19099. this.#lastIndex = 0;
  19100. this.toSVGPath();
  19101. }
  19102. return {
  19103. path: {
  19104. d: this.#lastSVGPath
  19105. }
  19106. };
  19107. }
  19108. toSVGPath() {
  19109. const firstX = Outline.svgRound(this.#line[4]);
  19110. const firstY = Outline.svgRound(this.#line[5]);
  19111. if (this.#points.length === 2) {
  19112. this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`;
  19113. return this.#lastSVGPath;
  19114. }
  19115. if (this.#points.length <= 6) {
  19116. const i = this.#lastSVGPath.lastIndexOf("M");
  19117. this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i)} M ${firstX} ${firstY}`;
  19118. this.#lastIndex = 6;
  19119. }
  19120. if (this.#points.length === 4) {
  19121. const secondX = Outline.svgRound(this.#line[10]);
  19122. const secondY = Outline.svgRound(this.#line[11]);
  19123. this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`;
  19124. this.#lastIndex = 12;
  19125. return this.#lastSVGPath;
  19126. }
  19127. const buffer = [];
  19128. if (this.#lastIndex === 0) {
  19129. buffer.push(`M ${firstX} ${firstY}`);
  19130. this.#lastIndex = 6;
  19131. }
  19132. for (let i = this.#lastIndex, ii = this.#line.length; i < ii; i += 6) {
  19133. const [c1x, c1y, c2x, c2y, x, y] = this.#line.slice(i, i + 6).map(Outline.svgRound);
  19134. buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`);
  19135. }
  19136. this.#lastSVGPath += buffer.join(" ");
  19137. this.#lastIndex = this.#line.length;
  19138. return this.#lastSVGPath;
  19139. }
  19140. getOutlines(parentWidth, parentHeight, scale, innerMargin) {
  19141. const last = this.#lines.at(-1);
  19142. last.line = new Float32Array(last.line);
  19143. last.points = new Float32Array(last.points);
  19144. this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin);
  19145. this.#last = null;
  19146. this.#line = null;
  19147. this.#lines = null;
  19148. this.#lastSVGPath = null;
  19149. return this.#outlines;
  19150. }
  19151. get defaultSVGProperties() {
  19152. return {
  19153. root: {
  19154. viewBox: "0 0 10000 10000"
  19155. },
  19156. rootClass: {
  19157. draw: true
  19158. },
  19159. bbox: [0, 0, 1, 1]
  19160. };
  19161. }
  19162. }
  19163. class InkDrawOutline extends Outline {
  19164. #bbox;
  19165. #currentRotation = 0;
  19166. #innerMargin;
  19167. #lines;
  19168. #parentWidth;
  19169. #parentHeight;
  19170. #parentScale;
  19171. #rotation;
  19172. #thickness;
  19173. build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) {
  19174. this.#parentWidth = parentWidth;
  19175. this.#parentHeight = parentHeight;
  19176. this.#parentScale = parentScale;
  19177. this.#rotation = rotation;
  19178. this.#thickness = thickness;
  19179. this.#innerMargin = innerMargin ?? 0;
  19180. this.#lines = lines;
  19181. this.#computeBbox();
  19182. }
  19183. setLastElement(element) {
  19184. this.#lines.push(element);
  19185. return {
  19186. path: {
  19187. d: this.toSVGPath()
  19188. }
  19189. };
  19190. }
  19191. removeLastElement() {
  19192. this.#lines.pop();
  19193. return {
  19194. path: {
  19195. d: this.toSVGPath()
  19196. }
  19197. };
  19198. }
  19199. toSVGPath() {
  19200. const buffer = [];
  19201. for (const {
  19202. line
  19203. } of this.#lines) {
  19204. buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`);
  19205. if (line.length === 6) {
  19206. buffer.push("Z");
  19207. continue;
  19208. }
  19209. if (line.length === 12) {
  19210. buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`);
  19211. continue;
  19212. }
  19213. for (let i = 6, ii = line.length; i < ii; i += 6) {
  19214. const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6).map(Outline.svgRound);
  19215. buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`);
  19216. }
  19217. }
  19218. return buffer.join("");
  19219. }
  19220. serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) {
  19221. const serializedLines = [];
  19222. const serializedPoints = [];
  19223. const [x, y, width, height] = this.#getBBoxWithNoMargin();
  19224. let tx, ty, sx, sy, x1, y1, x2, y2, rescaleFn;
  19225. switch (this.#rotation) {
  19226. case 0:
  19227. rescaleFn = Outline._rescale;
  19228. tx = pageX;
  19229. ty = pageY + pageHeight;
  19230. sx = pageWidth;
  19231. sy = -pageHeight;
  19232. x1 = pageX + x * pageWidth;
  19233. y1 = pageY + (1 - y - height) * pageHeight;
  19234. x2 = pageX + (x + width) * pageWidth;
  19235. y2 = pageY + (1 - y) * pageHeight;
  19236. break;
  19237. case 90:
  19238. rescaleFn = Outline._rescaleAndSwap;
  19239. tx = pageX;
  19240. ty = pageY;
  19241. sx = pageWidth;
  19242. sy = pageHeight;
  19243. x1 = pageX + y * pageWidth;
  19244. y1 = pageY + x * pageHeight;
  19245. x2 = pageX + (y + height) * pageWidth;
  19246. y2 = pageY + (x + width) * pageHeight;
  19247. break;
  19248. case 180:
  19249. rescaleFn = Outline._rescale;
  19250. tx = pageX + pageWidth;
  19251. ty = pageY;
  19252. sx = -pageWidth;
  19253. sy = pageHeight;
  19254. x1 = pageX + (1 - x - width) * pageWidth;
  19255. y1 = pageY + y * pageHeight;
  19256. x2 = pageX + (1 - x) * pageWidth;
  19257. y2 = pageY + (y + height) * pageHeight;
  19258. break;
  19259. case 270:
  19260. rescaleFn = Outline._rescaleAndSwap;
  19261. tx = pageX + pageWidth;
  19262. ty = pageY + pageHeight;
  19263. sx = -pageWidth;
  19264. sy = -pageHeight;
  19265. x1 = pageX + (1 - y - height) * pageWidth;
  19266. y1 = pageY + (1 - x - width) * pageHeight;
  19267. x2 = pageX + (1 - y) * pageWidth;
  19268. y2 = pageY + (1 - x) * pageHeight;
  19269. break;
  19270. }
  19271. for (const {
  19272. line,
  19273. points
  19274. } of this.#lines) {
  19275. serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null));
  19276. serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null));
  19277. }
  19278. return {
  19279. lines: serializedLines,
  19280. points: serializedPoints,
  19281. rect: [x1, y1, x2, y2]
  19282. };
  19283. }
  19284. static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, {
  19285. paths: {
  19286. lines,
  19287. points
  19288. },
  19289. rotation,
  19290. thickness
  19291. }) {
  19292. const newLines = [];
  19293. let tx, ty, sx, sy, rescaleFn;
  19294. switch (rotation) {
  19295. case 0:
  19296. rescaleFn = Outline._rescale;
  19297. tx = -pageX / pageWidth;
  19298. ty = pageY / pageHeight + 1;
  19299. sx = 1 / pageWidth;
  19300. sy = -1 / pageHeight;
  19301. break;
  19302. case 90:
  19303. rescaleFn = Outline._rescaleAndSwap;
  19304. tx = -pageY / pageHeight;
  19305. ty = -pageX / pageWidth;
  19306. sx = 1 / pageHeight;
  19307. sy = 1 / pageWidth;
  19308. break;
  19309. case 180:
  19310. rescaleFn = Outline._rescale;
  19311. tx = pageX / pageWidth + 1;
  19312. ty = -pageY / pageHeight;
  19313. sx = -1 / pageWidth;
  19314. sy = 1 / pageHeight;
  19315. break;
  19316. case 270:
  19317. rescaleFn = Outline._rescaleAndSwap;
  19318. tx = pageY / pageHeight + 1;
  19319. ty = pageX / pageWidth + 1;
  19320. sx = -1 / pageHeight;
  19321. sy = -1 / pageWidth;
  19322. break;
  19323. }
  19324. if (!lines) {
  19325. lines = [];
  19326. for (const point of points) {
  19327. const len = point.length;
  19328. if (len === 2) {
  19329. lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]]));
  19330. continue;
  19331. }
  19332. if (len === 4) {
  19333. lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]]));
  19334. continue;
  19335. }
  19336. const line = new Float32Array(3 * (len - 2));
  19337. lines.push(line);
  19338. let [x1, y1, x2, y2] = point.subarray(0, 4);
  19339. line.set([NaN, NaN, NaN, NaN, x1, y1], 0);
  19340. for (let i = 4; i < len; i += 2) {
  19341. const x = point[i];
  19342. const y = point[i + 1];
  19343. line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3);
  19344. [x1, y1, x2, y2] = [x2, y2, x, y];
  19345. }
  19346. }
  19347. }
  19348. for (let i = 0, ii = lines.length; i < ii; i++) {
  19349. newLines.push({
  19350. line: rescaleFn(lines[i].map(x => x ?? NaN), tx, ty, sx, sy),
  19351. points: rescaleFn(points[i].map(x => x ?? NaN), tx, ty, sx, sy)
  19352. });
  19353. }
  19354. const outlines = new InkDrawOutline();
  19355. outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin);
  19356. return outlines;
  19357. }
  19358. #getMarginComponents(thickness = this.#thickness) {
  19359. const margin = this.#innerMargin + thickness / 2 * this.#parentScale;
  19360. return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth];
  19361. }
  19362. #getBBoxWithNoMargin() {
  19363. const [x, y, width, height] = this.#bbox;
  19364. const [marginX, marginY] = this.#getMarginComponents(0);
  19365. return [x + marginX, y + marginY, width - 2 * marginX, height - 2 * marginY];
  19366. }
  19367. #computeBbox() {
  19368. const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
  19369. for (const {
  19370. line
  19371. } of this.#lines) {
  19372. if (line.length <= 12) {
  19373. for (let i = 4, ii = line.length; i < ii; i += 6) {
  19374. const [x, y] = line.subarray(i, i + 2);
  19375. bbox[0] = Math.min(bbox[0], x);
  19376. bbox[1] = Math.min(bbox[1], y);
  19377. bbox[2] = Math.max(bbox[2], x);
  19378. bbox[3] = Math.max(bbox[3], y);
  19379. }
  19380. continue;
  19381. }
  19382. let lastX = line[4],
  19383. lastY = line[5];
  19384. for (let i = 6, ii = line.length; i < ii; i += 6) {
  19385. const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6);
  19386. Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x, y, bbox);
  19387. lastX = x;
  19388. lastY = y;
  19389. }
  19390. }
  19391. const [marginX, marginY] = this.#getMarginComponents();
  19392. bbox[0] = Math.min(1, Math.max(0, bbox[0] - marginX));
  19393. bbox[1] = Math.min(1, Math.max(0, bbox[1] - marginY));
  19394. bbox[2] = Math.min(1, Math.max(0, bbox[2] + marginX));
  19395. bbox[3] = Math.min(1, Math.max(0, bbox[3] + marginY));
  19396. bbox[2] -= bbox[0];
  19397. bbox[3] -= bbox[1];
  19398. }
  19399. get box() {
  19400. return this.#bbox;
  19401. }
  19402. updateProperty(name, value) {
  19403. if (name === "stroke-width") {
  19404. return this.#updateThickness(value);
  19405. }
  19406. return null;
  19407. }
  19408. #updateThickness(thickness) {
  19409. const [oldMarginX, oldMarginY] = this.#getMarginComponents();
  19410. this.#thickness = thickness;
  19411. const [newMarginX, newMarginY] = this.#getMarginComponents();
  19412. const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY];
  19413. const bbox = this.#bbox;
  19414. bbox[0] -= diffMarginX;
  19415. bbox[1] -= diffMarginY;
  19416. bbox[2] += 2 * diffMarginX;
  19417. bbox[3] += 2 * diffMarginY;
  19418. return bbox;
  19419. }
  19420. updateParentDimensions([width, height], scale) {
  19421. const [oldMarginX, oldMarginY] = this.#getMarginComponents();
  19422. this.#parentWidth = width;
  19423. this.#parentHeight = height;
  19424. this.#parentScale = scale;
  19425. const [newMarginX, newMarginY] = this.#getMarginComponents();
  19426. const diffMarginX = newMarginX - oldMarginX;
  19427. const diffMarginY = newMarginY - oldMarginY;
  19428. const bbox = this.#bbox;
  19429. bbox[0] -= diffMarginX;
  19430. bbox[1] -= diffMarginY;
  19431. bbox[2] += 2 * diffMarginX;
  19432. bbox[3] += 2 * diffMarginY;
  19433. return bbox;
  19434. }
  19435. updateRotation(rotation) {
  19436. this.#currentRotation = rotation;
  19437. return {
  19438. path: {
  19439. transform: this.rotationTransform
  19440. }
  19441. };
  19442. }
  19443. get viewBox() {
  19444. return this.#bbox.map(Outline.svgRound).join(" ");
  19445. }
  19446. get defaultProperties() {
  19447. const [x, y] = this.#bbox;
  19448. return {
  19449. root: {
  19450. viewBox: this.viewBox
  19451. },
  19452. path: {
  19453. "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`
  19454. }
  19455. };
  19456. }
  19457. get rotationTransform() {
  19458. const [,, width, height] = this.#bbox;
  19459. let a = 0,
  19460. b = 0,
  19461. c = 0,
  19462. d = 0,
  19463. e = 0,
  19464. f = 0;
  19465. switch (this.#currentRotation) {
  19466. case 90:
  19467. b = height / width;
  19468. c = -width / height;
  19469. e = width;
  19470. break;
  19471. case 180:
  19472. a = -1;
  19473. d = -1;
  19474. e = width;
  19475. f = height;
  19476. break;
  19477. case 270:
  19478. b = -height / width;
  19479. c = width / height;
  19480. f = height;
  19481. break;
  19482. default:
  19483. return "";
  19484. }
  19485. return `matrix(${a} ${b} ${c} ${d} ${Outline.svgRound(e)} ${Outline.svgRound(f)})`;
  19486. }
  19487. getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) {
  19488. const [marginX, marginY] = this.#getMarginComponents();
  19489. const [x, y, width, height] = this.#bbox;
  19490. if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
  19491. const tx = newX + newWidth / 2 - (x + width / 2);
  19492. const ty = newY + newHeight / 2 - (y + height / 2);
  19493. return {
  19494. path: {
  19495. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
  19496. transform: `${this.rotationTransform} translate(${tx} ${ty})`
  19497. }
  19498. };
  19499. }
  19500. const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
  19501. const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
  19502. const s2x = width / newWidth;
  19503. const s2y = height / newHeight;
  19504. return {
  19505. path: {
  19506. "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`,
  19507. transform: `${this.rotationTransform} scale(${s2x} ${s2y}) ` + `translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) ` + `translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})`
  19508. }
  19509. };
  19510. }
  19511. getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) {
  19512. const [marginX, marginY] = this.#getMarginComponents();
  19513. const bbox = this.#bbox;
  19514. const [x, y, width, height] = bbox;
  19515. bbox[0] = newX;
  19516. bbox[1] = newY;
  19517. bbox[2] = newWidth;
  19518. bbox[3] = newHeight;
  19519. if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
  19520. const tx = newX + newWidth / 2 - (x + width / 2);
  19521. const ty = newY + newHeight / 2 - (y + height / 2);
  19522. for (const {
  19523. line,
  19524. points
  19525. } of this.#lines) {
  19526. Outline._translate(line, tx, ty, line);
  19527. Outline._translate(points, tx, ty, points);
  19528. }
  19529. return {
  19530. root: {
  19531. viewBox: this.viewBox
  19532. },
  19533. path: {
  19534. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
  19535. transform: this.rotationTransform || null,
  19536. d: this.toSVGPath()
  19537. }
  19538. };
  19539. }
  19540. const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
  19541. const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
  19542. const tx = -s1x * (x + marginX) + newX + marginX;
  19543. const ty = -s1y * (y + marginY) + newY + marginY;
  19544. if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) {
  19545. for (const {
  19546. line,
  19547. points
  19548. } of this.#lines) {
  19549. Outline._rescale(line, tx, ty, s1x, s1y, line);
  19550. Outline._rescale(points, tx, ty, s1x, s1y, points);
  19551. }
  19552. }
  19553. return {
  19554. root: {
  19555. viewBox: this.viewBox
  19556. },
  19557. path: {
  19558. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
  19559. transform: this.rotationTransform || null,
  19560. d: this.toSVGPath()
  19561. }
  19562. };
  19563. }
  19564. getPathTranslatedSVGProperties([newX, newY], parentDimensions) {
  19565. const [newParentWidth, newParentHeight] = parentDimensions;
  19566. const bbox = this.#bbox;
  19567. const tx = newX - bbox[0];
  19568. const ty = newY - bbox[1];
  19569. if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) {
  19570. for (const {
  19571. line,
  19572. points
  19573. } of this.#lines) {
  19574. Outline._translate(line, tx, ty, line);
  19575. Outline._translate(points, tx, ty, points);
  19576. }
  19577. } else {
  19578. const sx = this.#parentWidth / newParentWidth;
  19579. const sy = this.#parentHeight / newParentHeight;
  19580. this.#parentWidth = newParentWidth;
  19581. this.#parentHeight = newParentHeight;
  19582. for (const {
  19583. line,
  19584. points
  19585. } of this.#lines) {
  19586. Outline._rescale(line, tx, ty, sx, sy, line);
  19587. Outline._rescale(points, tx, ty, sx, sy, points);
  19588. }
  19589. bbox[2] *= sx;
  19590. bbox[3] *= sy;
  19591. }
  19592. bbox[0] = newX;
  19593. bbox[1] = newY;
  19594. return {
  19595. root: {
  19596. viewBox: this.viewBox
  19597. },
  19598. path: {
  19599. d: this.toSVGPath(),
  19600. "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`
  19601. }
  19602. };
  19603. }
  19604. get defaultSVGProperties() {
  19605. const bbox = this.#bbox;
  19606. return {
  19607. root: {
  19608. viewBox: this.viewBox
  19609. },
  19610. rootClass: {
  19611. draw: true
  19612. },
  19613. path: {
  19614. d: this.toSVGPath(),
  19615. "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`,
  19616. transform: this.rotationTransform || null
  19617. },
  19618. bbox
  19619. };
  19620. }
  19621. }
  19622. ;// ./src/display/editor/ink.js
  19623. class InkDrawingOptions extends DrawingOptions {
  19624. #viewParameters;
  19625. constructor(viewerParameters) {
  19626. super();
  19627. this.#viewParameters = viewerParameters;
  19628. super.updateProperties({
  19629. fill: "none",
  19630. stroke: AnnotationEditor._defaultLineColor,
  19631. "stroke-opacity": 1,
  19632. "stroke-width": 1,
  19633. "stroke-linecap": "round",
  19634. "stroke-linejoin": "round",
  19635. "stroke-miterlimit": 10
  19636. });
  19637. }
  19638. updateSVGProperty(name, value) {
  19639. if (name === "stroke-width") {
  19640. value ??= this["stroke-width"];
  19641. value *= this.#viewParameters.realScale;
  19642. }
  19643. super.updateSVGProperty(name, value);
  19644. }
  19645. clone() {
  19646. const clone = new InkDrawingOptions(this.#viewParameters);
  19647. clone.updateAll(this);
  19648. return clone;
  19649. }
  19650. }
  19651. class InkEditor extends DrawingEditor {
  19652. static _type = "ink";
  19653. static _editorType = AnnotationEditorType.INK;
  19654. static _defaultDrawingOptions = null;
  19655. constructor(params) {
  19656. super({
  19657. ...params,
  19658. name: "inkEditor"
  19659. });
  19660. this._willKeepAspectRatio = true;
  19661. }
  19662. static initialize(l10n, uiManager) {
  19663. AnnotationEditor.initialize(l10n, uiManager);
  19664. this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters);
  19665. }
  19666. static getDefaultDrawingOptions(options) {
  19667. const clone = this._defaultDrawingOptions.clone();
  19668. clone.updateProperties(options);
  19669. return clone;
  19670. }
  19671. static get supportMultipleDrawings() {
  19672. return true;
  19673. }
  19674. static get typesMap() {
  19675. return shadow(this, "typesMap", new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]]));
  19676. }
  19677. static createDrawerInstance(x, y, parentWidth, parentHeight, rotation) {
  19678. return new InkDrawOutliner(x, y, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]);
  19679. }
  19680. static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {
  19681. return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
  19682. }
  19683. static async deserialize(data, parent, uiManager) {
  19684. let initialData = null;
  19685. if (data instanceof InkAnnotationElement) {
  19686. const {
  19687. data: {
  19688. inkLists,
  19689. rect,
  19690. rotation,
  19691. id,
  19692. color,
  19693. opacity,
  19694. borderStyle: {
  19695. rawWidth: thickness
  19696. },
  19697. popupRef
  19698. },
  19699. parent: {
  19700. page: {
  19701. pageNumber
  19702. }
  19703. }
  19704. } = data;
  19705. initialData = data = {
  19706. annotationType: AnnotationEditorType.INK,
  19707. color: Array.from(color),
  19708. thickness,
  19709. opacity,
  19710. paths: {
  19711. points: inkLists
  19712. },
  19713. boxes: null,
  19714. pageIndex: pageNumber - 1,
  19715. rect: rect.slice(0),
  19716. rotation,
  19717. id,
  19718. deleted: false,
  19719. popupRef
  19720. };
  19721. }
  19722. const editor = await super.deserialize(data, parent, uiManager);
  19723. editor.annotationElementId = data.id || null;
  19724. editor._initialData = initialData;
  19725. return editor;
  19726. }
  19727. onScaleChanging() {
  19728. if (!this.parent) {
  19729. return;
  19730. }
  19731. super.onScaleChanging();
  19732. const {
  19733. _drawId,
  19734. _drawingOptions,
  19735. parent
  19736. } = this;
  19737. _drawingOptions.updateSVGProperty("stroke-width");
  19738. parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties());
  19739. }
  19740. static onScaleChangingWhenDrawing() {
  19741. const parent = this._currentParent;
  19742. if (!parent) {
  19743. return;
  19744. }
  19745. super.onScaleChangingWhenDrawing();
  19746. this._defaultDrawingOptions.updateSVGProperty("stroke-width");
  19747. parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
  19748. }
  19749. createDrawingOptions({
  19750. color,
  19751. thickness,
  19752. opacity
  19753. }) {
  19754. this._drawingOptions = InkEditor.getDefaultDrawingOptions({
  19755. stroke: Util.makeHexColor(...color),
  19756. "stroke-width": thickness,
  19757. "stroke-opacity": opacity
  19758. });
  19759. }
  19760. serialize(isForCopying = false) {
  19761. if (this.isEmpty()) {
  19762. return null;
  19763. }
  19764. if (this.deleted) {
  19765. return this.serializeDeleted();
  19766. }
  19767. const {
  19768. lines,
  19769. points,
  19770. rect
  19771. } = this.serializeDraw(isForCopying);
  19772. const {
  19773. _drawingOptions: {
  19774. stroke,
  19775. "stroke-opacity": opacity,
  19776. "stroke-width": thickness
  19777. }
  19778. } = this;
  19779. const serialized = {
  19780. annotationType: AnnotationEditorType.INK,
  19781. color: AnnotationEditor._colorManager.convert(stroke),
  19782. opacity,
  19783. thickness,
  19784. paths: {
  19785. lines,
  19786. points
  19787. },
  19788. pageIndex: this.pageIndex,
  19789. rect,
  19790. rotation: this.rotation,
  19791. structTreeParentId: this._structTreeParentId
  19792. };
  19793. if (isForCopying) {
  19794. return serialized;
  19795. }
  19796. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  19797. return null;
  19798. }
  19799. serialized.id = this.annotationElementId;
  19800. return serialized;
  19801. }
  19802. #hasElementChanged(serialized) {
  19803. const {
  19804. color,
  19805. thickness,
  19806. opacity,
  19807. pageIndex
  19808. } = this._initialData;
  19809. return this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c, i) => c !== color[i]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex;
  19810. }
  19811. renderAnnotationElement(annotation) {
  19812. const {
  19813. points,
  19814. rect
  19815. } = this.serializeDraw(false);
  19816. annotation.updateEdited({
  19817. rect,
  19818. thickness: this._drawingOptions["stroke-width"],
  19819. points
  19820. });
  19821. return null;
  19822. }
  19823. }
  19824. ;// ./src/display/editor/stamp.js
  19825. class StampEditor extends AnnotationEditor {
  19826. #bitmap = null;
  19827. #bitmapId = null;
  19828. #bitmapPromise = null;
  19829. #bitmapUrl = null;
  19830. #bitmapFile = null;
  19831. #bitmapFileName = "";
  19832. #canvas = null;
  19833. #resizeTimeoutId = null;
  19834. #isSvg = false;
  19835. #hasBeenAddedInUndoStack = false;
  19836. static _type = "stamp";
  19837. static _editorType = AnnotationEditorType.STAMP;
  19838. constructor(params) {
  19839. super({
  19840. ...params,
  19841. name: "stampEditor"
  19842. });
  19843. this.#bitmapUrl = params.bitmapUrl;
  19844. this.#bitmapFile = params.bitmapFile;
  19845. }
  19846. static initialize(l10n, uiManager) {
  19847. AnnotationEditor.initialize(l10n, uiManager);
  19848. }
  19849. static get supportedTypes() {
  19850. const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"];
  19851. return shadow(this, "supportedTypes", types.map(type => `image/${type}`));
  19852. }
  19853. static get supportedTypesStr() {
  19854. return shadow(this, "supportedTypesStr", this.supportedTypes.join(","));
  19855. }
  19856. static isHandlingMimeForPasting(mime) {
  19857. return this.supportedTypes.includes(mime);
  19858. }
  19859. static paste(item, parent) {
  19860. parent.pasteEditor(AnnotationEditorType.STAMP, {
  19861. bitmapFile: item.getAsFile()
  19862. });
  19863. }
  19864. altTextFinish() {
  19865. if (this._uiManager.useNewAltTextFlow) {
  19866. this.div.hidden = false;
  19867. }
  19868. super.altTextFinish();
  19869. }
  19870. get telemetryFinalData() {
  19871. return {
  19872. type: "stamp",
  19873. hasAltText: !!this.altTextData?.altText
  19874. };
  19875. }
  19876. static computeTelemetryFinalData(data) {
  19877. const hasAltTextStats = data.get("hasAltText");
  19878. return {
  19879. hasAltText: hasAltTextStats.get(true) ?? 0,
  19880. hasNoAltText: hasAltTextStats.get(false) ?? 0
  19881. };
  19882. }
  19883. #getBitmapFetched(data, fromId = false) {
  19884. if (!data) {
  19885. this.remove();
  19886. return;
  19887. }
  19888. this.#bitmap = data.bitmap;
  19889. if (!fromId) {
  19890. this.#bitmapId = data.id;
  19891. this.#isSvg = data.isSvg;
  19892. }
  19893. if (data.file) {
  19894. this.#bitmapFileName = data.file.name;
  19895. }
  19896. this.#createCanvas();
  19897. }
  19898. #getBitmapDone() {
  19899. this.#bitmapPromise = null;
  19900. this._uiManager.enableWaiting(false);
  19901. if (!this.#canvas) {
  19902. return;
  19903. }
  19904. if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  19905. this._editToolbar.hide();
  19906. this._uiManager.editAltText(this, true);
  19907. return;
  19908. }
  19909. if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  19910. this._reportTelemetry({
  19911. action: "pdfjs.image.image_added",
  19912. data: {
  19913. alt_text_modal: false,
  19914. alt_text_type: "empty"
  19915. }
  19916. });
  19917. try {
  19918. this.mlGuessAltText();
  19919. } catch {}
  19920. }
  19921. this.div.focus();
  19922. }
  19923. async mlGuessAltText(imageData = null, updateAltTextData = true) {
  19924. if (this.hasAltTextData()) {
  19925. return null;
  19926. }
  19927. const {
  19928. mlManager
  19929. } = this._uiManager;
  19930. if (!mlManager) {
  19931. throw new Error("No ML.");
  19932. }
  19933. if (!(await mlManager.isEnabledFor("altText"))) {
  19934. throw new Error("ML isn't enabled for alt text.");
  19935. }
  19936. const {
  19937. data,
  19938. width,
  19939. height
  19940. } = imageData || this.copyCanvas(null, null, true).imageData;
  19941. const response = await mlManager.guess({
  19942. name: "altText",
  19943. request: {
  19944. data,
  19945. width,
  19946. height,
  19947. channels: data.length / (width * height)
  19948. }
  19949. });
  19950. if (!response) {
  19951. throw new Error("No response from the AI service.");
  19952. }
  19953. if (response.error) {
  19954. throw new Error("Error from the AI service.");
  19955. }
  19956. if (response.cancel) {
  19957. return null;
  19958. }
  19959. if (!response.output) {
  19960. throw new Error("No valid response from the AI service.");
  19961. }
  19962. const altText = response.output;
  19963. await this.setGuessedAltText(altText);
  19964. if (updateAltTextData && !this.hasAltTextData()) {
  19965. this.altTextData = {
  19966. alt: altText,
  19967. decorative: false
  19968. };
  19969. }
  19970. return altText;
  19971. }
  19972. #getBitmap() {
  19973. if (this.#bitmapId) {
  19974. this._uiManager.enableWaiting(true);
  19975. this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
  19976. return;
  19977. }
  19978. if (this.#bitmapUrl) {
  19979. const url = this.#bitmapUrl;
  19980. this.#bitmapUrl = null;
  19981. this._uiManager.enableWaiting(true);
  19982. this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  19983. return;
  19984. }
  19985. if (this.#bitmapFile) {
  19986. const file = this.#bitmapFile;
  19987. this.#bitmapFile = null;
  19988. this._uiManager.enableWaiting(true);
  19989. this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  19990. return;
  19991. }
  19992. const input = document.createElement("input");
  19993. input.type = "file";
  19994. input.accept = StampEditor.supportedTypesStr;
  19995. const signal = this._uiManager._signal;
  19996. this.#bitmapPromise = new Promise(resolve => {
  19997. input.addEventListener("change", async () => {
  19998. if (!input.files || input.files.length === 0) {
  19999. this.remove();
  20000. } else {
  20001. this._uiManager.enableWaiting(true);
  20002. const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
  20003. this._reportTelemetry({
  20004. action: "pdfjs.image.image_selected",
  20005. data: {
  20006. alt_text_modal: this._uiManager.useNewAltTextFlow
  20007. }
  20008. });
  20009. this.#getBitmapFetched(data);
  20010. }
  20011. resolve();
  20012. }, {
  20013. signal
  20014. });
  20015. input.addEventListener("cancel", () => {
  20016. this.remove();
  20017. resolve();
  20018. }, {
  20019. signal
  20020. });
  20021. }).finally(() => this.#getBitmapDone());
  20022. input.click();
  20023. }
  20024. remove() {
  20025. if (this.#bitmapId) {
  20026. this.#bitmap = null;
  20027. this._uiManager.imageManager.deleteId(this.#bitmapId);
  20028. this.#canvas?.remove();
  20029. this.#canvas = null;
  20030. if (this.#resizeTimeoutId) {
  20031. clearTimeout(this.#resizeTimeoutId);
  20032. this.#resizeTimeoutId = null;
  20033. }
  20034. }
  20035. super.remove();
  20036. }
  20037. rebuild() {
  20038. if (!this.parent) {
  20039. if (this.#bitmapId) {
  20040. this.#getBitmap();
  20041. }
  20042. return;
  20043. }
  20044. super.rebuild();
  20045. if (this.div === null) {
  20046. return;
  20047. }
  20048. if (this.#bitmapId && this.#canvas === null) {
  20049. this.#getBitmap();
  20050. }
  20051. if (!this.isAttachedToDOM) {
  20052. this.parent.add(this);
  20053. }
  20054. }
  20055. onceAdded(focus) {
  20056. this._isDraggable = true;
  20057. if (focus) {
  20058. this.div.focus();
  20059. }
  20060. }
  20061. isEmpty() {
  20062. return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId);
  20063. }
  20064. get isResizable() {
  20065. return true;
  20066. }
  20067. render() {
  20068. if (this.div) {
  20069. return this.div;
  20070. }
  20071. let baseX, baseY;
  20072. if (this.width) {
  20073. baseX = this.x;
  20074. baseY = this.y;
  20075. }
  20076. super.render();
  20077. this.div.hidden = true;
  20078. this.div.setAttribute("role", "figure");
  20079. this.addAltTextButton();
  20080. if (this.#bitmap) {
  20081. this.#createCanvas();
  20082. } else {
  20083. this.#getBitmap();
  20084. }
  20085. if (this.width && !this.annotationElementId) {
  20086. const [parentWidth, parentHeight] = this.parentDimensions;
  20087. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  20088. }
  20089. this._uiManager.addShouldRescale(this);
  20090. return this.div;
  20091. }
  20092. _onResized() {
  20093. this.onScaleChanging();
  20094. }
  20095. onScaleChanging() {
  20096. if (!this.parent) {
  20097. return;
  20098. }
  20099. if (this.#resizeTimeoutId !== null) {
  20100. clearTimeout(this.#resizeTimeoutId);
  20101. }
  20102. const TIME_TO_WAIT = 200;
  20103. this.#resizeTimeoutId = setTimeout(() => {
  20104. this.#resizeTimeoutId = null;
  20105. this.#drawBitmap();
  20106. }, TIME_TO_WAIT);
  20107. }
  20108. #createCanvas() {
  20109. const {
  20110. div
  20111. } = this;
  20112. let {
  20113. width,
  20114. height
  20115. } = this.#bitmap;
  20116. const [pageWidth, pageHeight] = this.pageDimensions;
  20117. const MAX_RATIO = 0.75;
  20118. if (this.width) {
  20119. width = this.width * pageWidth;
  20120. height = this.height * pageHeight;
  20121. } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
  20122. const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
  20123. width *= factor;
  20124. height *= factor;
  20125. }
  20126. const [parentWidth, parentHeight] = this.parentDimensions;
  20127. this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight);
  20128. this._uiManager.enableWaiting(false);
  20129. const canvas = this.#canvas = document.createElement("canvas");
  20130. canvas.setAttribute("role", "img");
  20131. this.addContainer(canvas);
  20132. this.width = width / pageWidth;
  20133. this.height = height / pageHeight;
  20134. if (this._initialOptions?.isCentered) {
  20135. this.center();
  20136. } else {
  20137. this.fixAndSetPosition();
  20138. }
  20139. this._initialOptions = null;
  20140. if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {
  20141. div.hidden = false;
  20142. }
  20143. this.#drawBitmap();
  20144. if (!this.#hasBeenAddedInUndoStack) {
  20145. this.parent.addUndoableEditor(this);
  20146. this.#hasBeenAddedInUndoStack = true;
  20147. }
  20148. this._reportTelemetry({
  20149. action: "inserted_image"
  20150. });
  20151. if (this.#bitmapFileName) {
  20152. canvas.setAttribute("aria-label", this.#bitmapFileName);
  20153. }
  20154. }
  20155. copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {
  20156. if (!maxDataDimension) {
  20157. maxDataDimension = 224;
  20158. }
  20159. const {
  20160. width: bitmapWidth,
  20161. height: bitmapHeight
  20162. } = this.#bitmap;
  20163. const outputScale = new OutputScale();
  20164. let bitmap = this.#bitmap;
  20165. let width = bitmapWidth,
  20166. height = bitmapHeight;
  20167. let canvas = null;
  20168. if (maxPreviewDimension) {
  20169. if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {
  20170. const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);
  20171. width = Math.floor(bitmapWidth * ratio);
  20172. height = Math.floor(bitmapHeight * ratio);
  20173. }
  20174. canvas = document.createElement("canvas");
  20175. const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);
  20176. const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);
  20177. if (!this.#isSvg) {
  20178. bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);
  20179. }
  20180. const ctx = canvas.getContext("2d");
  20181. ctx.filter = this._uiManager.hcmFilter;
  20182. let white = "white",
  20183. black = "#cfcfd8";
  20184. if (this._uiManager.hcmFilter !== "none") {
  20185. black = "black";
  20186. } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
  20187. white = "#8f8f9d";
  20188. black = "#42414d";
  20189. }
  20190. const boxDim = 15;
  20191. const boxDimWidth = boxDim * outputScale.sx;
  20192. const boxDimHeight = boxDim * outputScale.sy;
  20193. const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);
  20194. const patternCtx = pattern.getContext("2d");
  20195. patternCtx.fillStyle = white;
  20196. patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);
  20197. patternCtx.fillStyle = black;
  20198. patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);
  20199. patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);
  20200. ctx.fillStyle = ctx.createPattern(pattern, "repeat");
  20201. ctx.fillRect(0, 0, scaledWidth, scaledHeight);
  20202. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  20203. }
  20204. let imageData = null;
  20205. if (createImageData) {
  20206. let dataWidth, dataHeight;
  20207. if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {
  20208. dataWidth = bitmap.width;
  20209. dataHeight = bitmap.height;
  20210. } else {
  20211. bitmap = this.#bitmap;
  20212. if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {
  20213. const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);
  20214. dataWidth = Math.floor(bitmapWidth * ratio);
  20215. dataHeight = Math.floor(bitmapHeight * ratio);
  20216. if (!this.#isSvg) {
  20217. bitmap = this.#scaleBitmap(dataWidth, dataHeight);
  20218. }
  20219. }
  20220. }
  20221. const offscreen = new OffscreenCanvas(dataWidth, dataHeight);
  20222. const offscreenCtx = offscreen.getContext("2d", {
  20223. willReadFrequently: true
  20224. });
  20225. offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);
  20226. imageData = {
  20227. width: dataWidth,
  20228. height: dataHeight,
  20229. data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data
  20230. };
  20231. }
  20232. return {
  20233. canvas,
  20234. width,
  20235. height,
  20236. imageData
  20237. };
  20238. }
  20239. #scaleBitmap(width, height) {
  20240. const {
  20241. width: bitmapWidth,
  20242. height: bitmapHeight
  20243. } = this.#bitmap;
  20244. let newWidth = bitmapWidth;
  20245. let newHeight = bitmapHeight;
  20246. let bitmap = this.#bitmap;
  20247. while (newWidth > 2 * width || newHeight > 2 * height) {
  20248. const prevWidth = newWidth;
  20249. const prevHeight = newHeight;
  20250. if (newWidth > 2 * width) {
  20251. newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
  20252. }
  20253. if (newHeight > 2 * height) {
  20254. newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
  20255. }
  20256. const offscreen = new OffscreenCanvas(newWidth, newHeight);
  20257. const ctx = offscreen.getContext("2d");
  20258. ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
  20259. bitmap = offscreen.transferToImageBitmap();
  20260. }
  20261. return bitmap;
  20262. }
  20263. #drawBitmap() {
  20264. const [parentWidth, parentHeight] = this.parentDimensions;
  20265. const {
  20266. width,
  20267. height
  20268. } = this;
  20269. const outputScale = new OutputScale();
  20270. const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx);
  20271. const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy);
  20272. const canvas = this.#canvas;
  20273. if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {
  20274. return;
  20275. }
  20276. canvas.width = scaledWidth;
  20277. canvas.height = scaledHeight;
  20278. const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);
  20279. const ctx = canvas.getContext("2d");
  20280. ctx.filter = this._uiManager.hcmFilter;
  20281. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  20282. }
  20283. getImageForAltText() {
  20284. return this.#canvas;
  20285. }
  20286. #serializeBitmap(toUrl) {
  20287. if (toUrl) {
  20288. if (this.#isSvg) {
  20289. const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
  20290. if (url) {
  20291. return url;
  20292. }
  20293. }
  20294. const canvas = document.createElement("canvas");
  20295. ({
  20296. width: canvas.width,
  20297. height: canvas.height
  20298. } = this.#bitmap);
  20299. const ctx = canvas.getContext("2d");
  20300. ctx.drawImage(this.#bitmap, 0, 0);
  20301. return canvas.toDataURL();
  20302. }
  20303. if (this.#isSvg) {
  20304. const [pageWidth, pageHeight] = this.pageDimensions;
  20305. const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
  20306. const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
  20307. const offscreen = new OffscreenCanvas(width, height);
  20308. const ctx = offscreen.getContext("2d");
  20309. ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
  20310. return offscreen.transferToImageBitmap();
  20311. }
  20312. return structuredClone(this.#bitmap);
  20313. }
  20314. static async deserialize(data, parent, uiManager) {
  20315. let initialData = null;
  20316. if (data instanceof StampAnnotationElement) {
  20317. const {
  20318. data: {
  20319. rect,
  20320. rotation,
  20321. id,
  20322. structParent,
  20323. popupRef
  20324. },
  20325. container,
  20326. parent: {
  20327. page: {
  20328. pageNumber
  20329. }
  20330. }
  20331. } = data;
  20332. const canvas = container.querySelector("canvas");
  20333. const imageData = uiManager.imageManager.getFromCanvas(container.id, canvas);
  20334. canvas.remove();
  20335. const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";
  20336. initialData = data = {
  20337. annotationType: AnnotationEditorType.STAMP,
  20338. bitmapId: imageData.id,
  20339. bitmap: imageData.bitmap,
  20340. pageIndex: pageNumber - 1,
  20341. rect: rect.slice(0),
  20342. rotation,
  20343. id,
  20344. deleted: false,
  20345. accessibilityData: {
  20346. decorative: false,
  20347. altText
  20348. },
  20349. isSvg: false,
  20350. structParent,
  20351. popupRef
  20352. };
  20353. }
  20354. const editor = await super.deserialize(data, parent, uiManager);
  20355. const {
  20356. rect,
  20357. bitmap,
  20358. bitmapUrl,
  20359. bitmapId,
  20360. isSvg,
  20361. accessibilityData
  20362. } = data;
  20363. if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
  20364. editor.#bitmapId = bitmapId;
  20365. if (bitmap) {
  20366. editor.#bitmap = bitmap;
  20367. }
  20368. } else {
  20369. editor.#bitmapUrl = bitmapUrl;
  20370. }
  20371. editor.#isSvg = isSvg;
  20372. const [parentWidth, parentHeight] = editor.pageDimensions;
  20373. editor.width = (rect[2] - rect[0]) / parentWidth;
  20374. editor.height = (rect[3] - rect[1]) / parentHeight;
  20375. editor.annotationElementId = data.id || null;
  20376. if (accessibilityData) {
  20377. editor.altTextData = accessibilityData;
  20378. }
  20379. editor._initialData = initialData;
  20380. editor.#hasBeenAddedInUndoStack = !!initialData;
  20381. return editor;
  20382. }
  20383. serialize(isForCopying = false, context = null) {
  20384. if (this.isEmpty()) {
  20385. return null;
  20386. }
  20387. if (this.deleted) {
  20388. return this.serializeDeleted();
  20389. }
  20390. const serialized = {
  20391. annotationType: AnnotationEditorType.STAMP,
  20392. bitmapId: this.#bitmapId,
  20393. pageIndex: this.pageIndex,
  20394. rect: this.getRect(0, 0),
  20395. rotation: this.rotation,
  20396. isSvg: this.#isSvg,
  20397. structTreeParentId: this._structTreeParentId
  20398. };
  20399. if (isForCopying) {
  20400. serialized.bitmapUrl = this.#serializeBitmap(true);
  20401. serialized.accessibilityData = this.serializeAltText(true);
  20402. return serialized;
  20403. }
  20404. const {
  20405. decorative,
  20406. altText
  20407. } = this.serializeAltText(false);
  20408. if (!decorative && altText) {
  20409. serialized.accessibilityData = {
  20410. type: "Figure",
  20411. alt: altText
  20412. };
  20413. }
  20414. if (this.annotationElementId) {
  20415. const changes = this.#hasElementChanged(serialized);
  20416. if (changes.isSame) {
  20417. return null;
  20418. }
  20419. if (changes.isSameAltText) {
  20420. delete serialized.accessibilityData;
  20421. } else {
  20422. serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;
  20423. }
  20424. }
  20425. serialized.id = this.annotationElementId;
  20426. if (context === null) {
  20427. return serialized;
  20428. }
  20429. context.stamps ||= new Map();
  20430. const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
  20431. if (!context.stamps.has(this.#bitmapId)) {
  20432. context.stamps.set(this.#bitmapId, {
  20433. area,
  20434. serialized
  20435. });
  20436. serialized.bitmap = this.#serializeBitmap(false);
  20437. } else if (this.#isSvg) {
  20438. const prevData = context.stamps.get(this.#bitmapId);
  20439. if (area > prevData.area) {
  20440. prevData.area = area;
  20441. prevData.serialized.bitmap.close();
  20442. prevData.serialized.bitmap = this.#serializeBitmap(false);
  20443. }
  20444. }
  20445. return serialized;
  20446. }
  20447. #hasElementChanged(serialized) {
  20448. const {
  20449. pageIndex,
  20450. accessibilityData: {
  20451. altText
  20452. }
  20453. } = this._initialData;
  20454. const isSamePageIndex = serialized.pageIndex === pageIndex;
  20455. const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;
  20456. return {
  20457. isSame: !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText,
  20458. isSameAltText
  20459. };
  20460. }
  20461. renderAnnotationElement(annotation) {
  20462. annotation.updateEdited({
  20463. rect: this.getRect(0, 0)
  20464. });
  20465. return null;
  20466. }
  20467. }
  20468. ;// ./src/display/editor/annotation_editor_layer.js
  20469. class AnnotationEditorLayer {
  20470. #accessibilityManager;
  20471. #allowClick = false;
  20472. #annotationLayer = null;
  20473. #clickAC = null;
  20474. #editorFocusTimeoutId = null;
  20475. #editors = new Map();
  20476. #hadPointerDown = false;
  20477. #isDisabling = false;
  20478. #isEnabling = false;
  20479. #drawingAC = null;
  20480. #focusedElement = null;
  20481. #textLayer = null;
  20482. #textSelectionAC = null;
  20483. #uiManager;
  20484. static _initialized = false;
  20485. static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor].map(type => [type._editorType, type]));
  20486. constructor({
  20487. uiManager,
  20488. pageIndex,
  20489. div,
  20490. structTreeLayer,
  20491. accessibilityManager,
  20492. annotationLayer,
  20493. drawLayer,
  20494. textLayer,
  20495. viewport,
  20496. l10n
  20497. }) {
  20498. const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()];
  20499. if (!AnnotationEditorLayer._initialized) {
  20500. AnnotationEditorLayer._initialized = true;
  20501. for (const editorType of editorTypes) {
  20502. editorType.initialize(l10n, uiManager);
  20503. }
  20504. }
  20505. uiManager.registerEditorTypes(editorTypes);
  20506. this.#uiManager = uiManager;
  20507. this.pageIndex = pageIndex;
  20508. this.div = div;
  20509. this.#accessibilityManager = accessibilityManager;
  20510. this.#annotationLayer = annotationLayer;
  20511. this.viewport = viewport;
  20512. this.#textLayer = textLayer;
  20513. this.drawLayer = drawLayer;
  20514. this._structTree = structTreeLayer;
  20515. this.#uiManager.addLayer(this);
  20516. }
  20517. get isEmpty() {
  20518. return this.#editors.size === 0;
  20519. }
  20520. get isInvisible() {
  20521. return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
  20522. }
  20523. updateToolbar(mode) {
  20524. this.#uiManager.updateToolbar(mode);
  20525. }
  20526. updateMode(mode = this.#uiManager.getMode()) {
  20527. this.#cleanup();
  20528. switch (mode) {
  20529. case AnnotationEditorType.NONE:
  20530. this.disableTextSelection();
  20531. this.togglePointerEvents(false);
  20532. this.toggleAnnotationLayerPointerEvents(true);
  20533. this.disableClick();
  20534. return;
  20535. case AnnotationEditorType.INK:
  20536. this.disableTextSelection();
  20537. this.togglePointerEvents(true);
  20538. this.enableClick();
  20539. break;
  20540. case AnnotationEditorType.HIGHLIGHT:
  20541. this.enableTextSelection();
  20542. this.togglePointerEvents(false);
  20543. this.disableClick();
  20544. break;
  20545. default:
  20546. this.disableTextSelection();
  20547. this.togglePointerEvents(true);
  20548. this.enableClick();
  20549. }
  20550. this.toggleAnnotationLayerPointerEvents(false);
  20551. const {
  20552. classList
  20553. } = this.div;
  20554. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  20555. classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
  20556. }
  20557. this.div.hidden = false;
  20558. }
  20559. hasTextLayer(textLayer) {
  20560. return textLayer === this.#textLayer?.div;
  20561. }
  20562. setEditingState(isEditing) {
  20563. this.#uiManager.setEditingState(isEditing);
  20564. }
  20565. addCommands(params) {
  20566. this.#uiManager.addCommands(params);
  20567. }
  20568. cleanUndoStack(type) {
  20569. this.#uiManager.cleanUndoStack(type);
  20570. }
  20571. toggleDrawing(enabled = false) {
  20572. this.div.classList.toggle("drawing", !enabled);
  20573. }
  20574. togglePointerEvents(enabled = false) {
  20575. this.div.classList.toggle("disabled", !enabled);
  20576. }
  20577. toggleAnnotationLayerPointerEvents(enabled = false) {
  20578. this.#annotationLayer?.div.classList.toggle("disabled", !enabled);
  20579. }
  20580. async enable() {
  20581. this.#isEnabling = true;
  20582. this.div.tabIndex = 0;
  20583. this.togglePointerEvents(true);
  20584. const annotationElementIds = new Set();
  20585. for (const editor of this.#editors.values()) {
  20586. editor.enableEditing();
  20587. editor.show(true);
  20588. if (editor.annotationElementId) {
  20589. this.#uiManager.removeChangedExistingAnnotation(editor);
  20590. annotationElementIds.add(editor.annotationElementId);
  20591. }
  20592. }
  20593. if (!this.#annotationLayer) {
  20594. this.#isEnabling = false;
  20595. return;
  20596. }
  20597. const editables = this.#annotationLayer.getEditableAnnotations();
  20598. for (const editable of editables) {
  20599. editable.hide();
  20600. if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
  20601. continue;
  20602. }
  20603. if (annotationElementIds.has(editable.data.id)) {
  20604. continue;
  20605. }
  20606. const editor = await this.deserialize(editable);
  20607. if (!editor) {
  20608. continue;
  20609. }
  20610. this.addOrRebuild(editor);
  20611. editor.enableEditing();
  20612. }
  20613. this.#isEnabling = false;
  20614. }
  20615. disable() {
  20616. this.#isDisabling = true;
  20617. this.div.tabIndex = -1;
  20618. this.togglePointerEvents(false);
  20619. const changedAnnotations = new Map();
  20620. const resetAnnotations = new Map();
  20621. for (const editor of this.#editors.values()) {
  20622. editor.disableEditing();
  20623. if (!editor.annotationElementId) {
  20624. continue;
  20625. }
  20626. if (editor.serialize() !== null) {
  20627. changedAnnotations.set(editor.annotationElementId, editor);
  20628. continue;
  20629. } else {
  20630. resetAnnotations.set(editor.annotationElementId, editor);
  20631. }
  20632. this.getEditableAnnotation(editor.annotationElementId)?.show();
  20633. editor.remove();
  20634. }
  20635. if (this.#annotationLayer) {
  20636. const editables = this.#annotationLayer.getEditableAnnotations();
  20637. for (const editable of editables) {
  20638. const {
  20639. id
  20640. } = editable.data;
  20641. if (this.#uiManager.isDeletedAnnotationElement(id)) {
  20642. continue;
  20643. }
  20644. let editor = resetAnnotations.get(id);
  20645. if (editor) {
  20646. editor.resetAnnotationElement(editable);
  20647. editor.show(false);
  20648. editable.show();
  20649. continue;
  20650. }
  20651. editor = changedAnnotations.get(id);
  20652. if (editor) {
  20653. this.#uiManager.addChangedExistingAnnotation(editor);
  20654. if (editor.renderAnnotationElement(editable)) {
  20655. editor.show(false);
  20656. }
  20657. }
  20658. editable.show();
  20659. }
  20660. }
  20661. this.#cleanup();
  20662. if (this.isEmpty) {
  20663. this.div.hidden = true;
  20664. }
  20665. const {
  20666. classList
  20667. } = this.div;
  20668. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  20669. classList.remove(`${editorType._type}Editing`);
  20670. }
  20671. this.disableTextSelection();
  20672. this.toggleAnnotationLayerPointerEvents(true);
  20673. this.#isDisabling = false;
  20674. }
  20675. getEditableAnnotation(id) {
  20676. return this.#annotationLayer?.getEditableAnnotation(id) || null;
  20677. }
  20678. setActiveEditor(editor) {
  20679. const currentActive = this.#uiManager.getActive();
  20680. if (currentActive === editor) {
  20681. return;
  20682. }
  20683. this.#uiManager.setActiveEditor(editor);
  20684. }
  20685. enableTextSelection() {
  20686. this.div.tabIndex = -1;
  20687. if (this.#textLayer?.div && !this.#textSelectionAC) {
  20688. this.#textSelectionAC = new AbortController();
  20689. const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);
  20690. this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {
  20691. signal
  20692. });
  20693. this.#textLayer.div.classList.add("highlighting");
  20694. }
  20695. }
  20696. disableTextSelection() {
  20697. this.div.tabIndex = 0;
  20698. if (this.#textLayer?.div && this.#textSelectionAC) {
  20699. this.#textSelectionAC.abort();
  20700. this.#textSelectionAC = null;
  20701. this.#textLayer.div.classList.remove("highlighting");
  20702. }
  20703. }
  20704. #textLayerPointerDown(event) {
  20705. this.#uiManager.unselectAll();
  20706. const {
  20707. target
  20708. } = event;
  20709. if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {
  20710. const {
  20711. isMac
  20712. } = util_FeatureTest.platform;
  20713. if (event.button !== 0 || event.ctrlKey && isMac) {
  20714. return;
  20715. }
  20716. this.#uiManager.showAllEditors("highlight", true, true);
  20717. this.#textLayer.div.classList.add("free");
  20718. this.toggleDrawing();
  20719. HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {
  20720. target: this.#textLayer.div,
  20721. x: event.x,
  20722. y: event.y
  20723. });
  20724. this.#textLayer.div.addEventListener("pointerup", () => {
  20725. this.#textLayer.div.classList.remove("free");
  20726. this.toggleDrawing(true);
  20727. }, {
  20728. once: true,
  20729. signal: this.#uiManager._signal
  20730. });
  20731. event.preventDefault();
  20732. }
  20733. }
  20734. enableClick() {
  20735. if (this.#clickAC) {
  20736. return;
  20737. }
  20738. this.#clickAC = new AbortController();
  20739. const signal = this.#uiManager.combinedSignal(this.#clickAC);
  20740. this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {
  20741. signal
  20742. });
  20743. const pointerup = this.pointerup.bind(this);
  20744. this.div.addEventListener("pointerup", pointerup, {
  20745. signal
  20746. });
  20747. this.div.addEventListener("pointercancel", pointerup, {
  20748. signal
  20749. });
  20750. }
  20751. disableClick() {
  20752. this.#clickAC?.abort();
  20753. this.#clickAC = null;
  20754. }
  20755. attach(editor) {
  20756. this.#editors.set(editor.id, editor);
  20757. const {
  20758. annotationElementId
  20759. } = editor;
  20760. if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
  20761. this.#uiManager.removeDeletedAnnotationElement(editor);
  20762. }
  20763. }
  20764. detach(editor) {
  20765. this.#editors.delete(editor.id);
  20766. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  20767. if (!this.#isDisabling && editor.annotationElementId) {
  20768. this.#uiManager.addDeletedAnnotationElement(editor);
  20769. }
  20770. }
  20771. remove(editor) {
  20772. this.detach(editor);
  20773. this.#uiManager.removeEditor(editor);
  20774. editor.div.remove();
  20775. editor.isAttachedToDOM = false;
  20776. }
  20777. changeParent(editor) {
  20778. if (editor.parent === this) {
  20779. return;
  20780. }
  20781. if (editor.parent && editor.annotationElementId) {
  20782. this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
  20783. AnnotationEditor.deleteAnnotationElement(editor);
  20784. editor.annotationElementId = null;
  20785. }
  20786. this.attach(editor);
  20787. editor.parent?.detach(editor);
  20788. editor.setParent(this);
  20789. if (editor.div && editor.isAttachedToDOM) {
  20790. editor.div.remove();
  20791. this.div.append(editor.div);
  20792. }
  20793. }
  20794. add(editor) {
  20795. if (editor.parent === this && editor.isAttachedToDOM) {
  20796. return;
  20797. }
  20798. this.changeParent(editor);
  20799. this.#uiManager.addEditor(editor);
  20800. this.attach(editor);
  20801. if (!editor.isAttachedToDOM) {
  20802. const div = editor.render();
  20803. this.div.append(div);
  20804. editor.isAttachedToDOM = true;
  20805. }
  20806. editor.fixAndSetPosition();
  20807. editor.onceAdded(!this.#isEnabling);
  20808. this.#uiManager.addToAnnotationStorage(editor);
  20809. editor._reportTelemetry(editor.telemetryInitialData);
  20810. }
  20811. moveEditorInDOM(editor) {
  20812. if (!editor.isAttachedToDOM) {
  20813. return;
  20814. }
  20815. const {
  20816. activeElement
  20817. } = document;
  20818. if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
  20819. editor._focusEventsAllowed = false;
  20820. this.#editorFocusTimeoutId = setTimeout(() => {
  20821. this.#editorFocusTimeoutId = null;
  20822. if (!editor.div.contains(document.activeElement)) {
  20823. editor.div.addEventListener("focusin", () => {
  20824. editor._focusEventsAllowed = true;
  20825. }, {
  20826. once: true,
  20827. signal: this.#uiManager._signal
  20828. });
  20829. activeElement.focus();
  20830. } else {
  20831. editor._focusEventsAllowed = true;
  20832. }
  20833. }, 0);
  20834. }
  20835. editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  20836. }
  20837. addOrRebuild(editor) {
  20838. if (editor.needsToBeRebuilt()) {
  20839. editor.parent ||= this;
  20840. editor.rebuild();
  20841. editor.show();
  20842. } else {
  20843. this.add(editor);
  20844. }
  20845. }
  20846. addUndoableEditor(editor) {
  20847. const cmd = () => editor._uiManager.rebuild(editor);
  20848. const undo = () => {
  20849. editor.remove();
  20850. };
  20851. this.addCommands({
  20852. cmd,
  20853. undo,
  20854. mustExec: false
  20855. });
  20856. }
  20857. getNextId() {
  20858. return this.#uiManager.getId();
  20859. }
  20860. get #currentEditorType() {
  20861. return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
  20862. }
  20863. combinedSignal(ac) {
  20864. return this.#uiManager.combinedSignal(ac);
  20865. }
  20866. #createNewEditor(params) {
  20867. const editorType = this.#currentEditorType;
  20868. return editorType ? new editorType.prototype.constructor(params) : null;
  20869. }
  20870. canCreateNewEmptyEditor() {
  20871. return this.#currentEditorType?.canCreateNewEmptyEditor();
  20872. }
  20873. pasteEditor(mode, params) {
  20874. this.#uiManager.updateToolbar(mode);
  20875. this.#uiManager.updateMode(mode);
  20876. const {
  20877. offsetX,
  20878. offsetY
  20879. } = this.#getCenterPoint();
  20880. const id = this.getNextId();
  20881. const editor = this.#createNewEditor({
  20882. parent: this,
  20883. id,
  20884. x: offsetX,
  20885. y: offsetY,
  20886. uiManager: this.#uiManager,
  20887. isCentered: true,
  20888. ...params
  20889. });
  20890. if (editor) {
  20891. this.add(editor);
  20892. }
  20893. }
  20894. async deserialize(data) {
  20895. return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null;
  20896. }
  20897. createAndAddNewEditor(event, isCentered, data = {}) {
  20898. const id = this.getNextId();
  20899. const editor = this.#createNewEditor({
  20900. parent: this,
  20901. id,
  20902. x: event.offsetX,
  20903. y: event.offsetY,
  20904. uiManager: this.#uiManager,
  20905. isCentered,
  20906. ...data
  20907. });
  20908. if (editor) {
  20909. this.add(editor);
  20910. }
  20911. return editor;
  20912. }
  20913. #getCenterPoint() {
  20914. const {
  20915. x,
  20916. y,
  20917. width,
  20918. height
  20919. } = this.div.getBoundingClientRect();
  20920. const tlX = Math.max(0, x);
  20921. const tlY = Math.max(0, y);
  20922. const brX = Math.min(window.innerWidth, x + width);
  20923. const brY = Math.min(window.innerHeight, y + height);
  20924. const centerX = (tlX + brX) / 2 - x;
  20925. const centerY = (tlY + brY) / 2 - y;
  20926. const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
  20927. return {
  20928. offsetX,
  20929. offsetY
  20930. };
  20931. }
  20932. addNewEditor() {
  20933. this.createAndAddNewEditor(this.#getCenterPoint(), true);
  20934. }
  20935. setSelected(editor) {
  20936. this.#uiManager.setSelected(editor);
  20937. }
  20938. toggleSelected(editor) {
  20939. this.#uiManager.toggleSelected(editor);
  20940. }
  20941. unselect(editor) {
  20942. this.#uiManager.unselect(editor);
  20943. }
  20944. pointerup(event) {
  20945. const {
  20946. isMac
  20947. } = util_FeatureTest.platform;
  20948. if (event.button !== 0 || event.ctrlKey && isMac) {
  20949. return;
  20950. }
  20951. if (event.target !== this.div) {
  20952. return;
  20953. }
  20954. if (!this.#hadPointerDown) {
  20955. return;
  20956. }
  20957. this.#hadPointerDown = false;
  20958. if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) {
  20959. return;
  20960. }
  20961. if (!this.#allowClick) {
  20962. this.#allowClick = true;
  20963. return;
  20964. }
  20965. if (this.#uiManager.getMode() === AnnotationEditorType.STAMP) {
  20966. this.#uiManager.unselectAll();
  20967. return;
  20968. }
  20969. this.createAndAddNewEditor(event, false);
  20970. }
  20971. pointerdown(event) {
  20972. if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
  20973. this.enableTextSelection();
  20974. }
  20975. if (this.#hadPointerDown) {
  20976. this.#hadPointerDown = false;
  20977. return;
  20978. }
  20979. const {
  20980. isMac
  20981. } = util_FeatureTest.platform;
  20982. if (event.button !== 0 || event.ctrlKey && isMac) {
  20983. return;
  20984. }
  20985. if (event.target !== this.div) {
  20986. return;
  20987. }
  20988. this.#hadPointerDown = true;
  20989. if (this.#currentEditorType?.isDrawer) {
  20990. this.startDrawingSession(event);
  20991. return;
  20992. }
  20993. const editor = this.#uiManager.getActive();
  20994. this.#allowClick = !editor || editor.isEmpty();
  20995. }
  20996. startDrawingSession(event) {
  20997. this.div.focus();
  20998. if (this.#drawingAC) {
  20999. this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
  21000. return;
  21001. }
  21002. this.#uiManager.setCurrentDrawingSession(this);
  21003. this.#drawingAC = new AbortController();
  21004. const signal = this.#uiManager.combinedSignal(this.#drawingAC);
  21005. this.div.addEventListener("blur", ({
  21006. relatedTarget
  21007. }) => {
  21008. if (relatedTarget && !this.div.contains(relatedTarget)) {
  21009. this.#focusedElement = null;
  21010. this.commitOrRemove();
  21011. }
  21012. }, {
  21013. signal
  21014. });
  21015. this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
  21016. }
  21017. pause(on) {
  21018. if (on) {
  21019. const {
  21020. activeElement
  21021. } = document;
  21022. if (this.div.contains(activeElement)) {
  21023. this.#focusedElement = activeElement;
  21024. }
  21025. return;
  21026. }
  21027. if (this.#focusedElement) {
  21028. setTimeout(() => {
  21029. this.#focusedElement?.focus();
  21030. this.#focusedElement = null;
  21031. }, 0);
  21032. }
  21033. }
  21034. endDrawingSession(isAborted = false) {
  21035. if (!this.#drawingAC) {
  21036. return null;
  21037. }
  21038. this.#uiManager.setCurrentDrawingSession(null);
  21039. this.#drawingAC.abort();
  21040. this.#drawingAC = null;
  21041. this.#focusedElement = null;
  21042. return this.#currentEditorType.endDrawing(isAborted);
  21043. }
  21044. findNewParent(editor, x, y) {
  21045. const layer = this.#uiManager.findParent(x, y);
  21046. if (layer === null || layer === this) {
  21047. return false;
  21048. }
  21049. layer.changeParent(editor);
  21050. return true;
  21051. }
  21052. commitOrRemove() {
  21053. if (this.#drawingAC) {
  21054. this.endDrawingSession();
  21055. return true;
  21056. }
  21057. return false;
  21058. }
  21059. onScaleChanging() {
  21060. if (!this.#drawingAC) {
  21061. return;
  21062. }
  21063. this.#currentEditorType.onScaleChangingWhenDrawing(this);
  21064. }
  21065. destroy() {
  21066. this.commitOrRemove();
  21067. if (this.#uiManager.getActive()?.parent === this) {
  21068. this.#uiManager.commitOrRemove();
  21069. this.#uiManager.setActiveEditor(null);
  21070. }
  21071. if (this.#editorFocusTimeoutId) {
  21072. clearTimeout(this.#editorFocusTimeoutId);
  21073. this.#editorFocusTimeoutId = null;
  21074. }
  21075. for (const editor of this.#editors.values()) {
  21076. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  21077. editor.setParent(null);
  21078. editor.isAttachedToDOM = false;
  21079. editor.div.remove();
  21080. }
  21081. this.div = null;
  21082. this.#editors.clear();
  21083. this.#uiManager.removeLayer(this);
  21084. }
  21085. #cleanup() {
  21086. for (const editor of this.#editors.values()) {
  21087. if (editor.isEmpty()) {
  21088. editor.remove();
  21089. }
  21090. }
  21091. }
  21092. render({
  21093. viewport
  21094. }) {
  21095. this.viewport = viewport;
  21096. setLayerDimensions(this.div, viewport);
  21097. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  21098. this.add(editor);
  21099. editor.rebuild();
  21100. }
  21101. this.updateMode();
  21102. }
  21103. update({
  21104. viewport
  21105. }) {
  21106. this.#uiManager.commitOrRemove();
  21107. this.#cleanup();
  21108. const oldRotation = this.viewport.rotation;
  21109. const rotation = viewport.rotation;
  21110. this.viewport = viewport;
  21111. setLayerDimensions(this.div, {
  21112. rotation
  21113. });
  21114. if (oldRotation !== rotation) {
  21115. for (const editor of this.#editors.values()) {
  21116. editor.rotate(rotation);
  21117. }
  21118. }
  21119. }
  21120. get pageDimensions() {
  21121. const {
  21122. pageWidth,
  21123. pageHeight
  21124. } = this.viewport.rawDims;
  21125. return [pageWidth, pageHeight];
  21126. }
  21127. get scale() {
  21128. return this.#uiManager.viewParameters.realScale;
  21129. }
  21130. }
  21131. ;// ./src/display/draw_layer.js
  21132. class DrawLayer {
  21133. #parent = null;
  21134. #id = 0;
  21135. #mapping = new Map();
  21136. #toUpdate = new Map();
  21137. constructor({
  21138. pageIndex
  21139. }) {
  21140. this.pageIndex = pageIndex;
  21141. }
  21142. setParent(parent) {
  21143. if (!this.#parent) {
  21144. this.#parent = parent;
  21145. return;
  21146. }
  21147. if (this.#parent !== parent) {
  21148. if (this.#mapping.size > 0) {
  21149. for (const root of this.#mapping.values()) {
  21150. root.remove();
  21151. parent.append(root);
  21152. }
  21153. }
  21154. this.#parent = parent;
  21155. }
  21156. }
  21157. static get _svgFactory() {
  21158. return shadow(this, "_svgFactory", new DOMSVGFactory());
  21159. }
  21160. static #setBox(element, [x, y, width, height]) {
  21161. const {
  21162. style
  21163. } = element;
  21164. style.top = `${100 * y}%`;
  21165. style.left = `${100 * x}%`;
  21166. style.width = `${100 * width}%`;
  21167. style.height = `${100 * height}%`;
  21168. }
  21169. #createSVG() {
  21170. const svg = DrawLayer._svgFactory.create(1, 1, true);
  21171. this.#parent.append(svg);
  21172. svg.setAttribute("aria-hidden", true);
  21173. return svg;
  21174. }
  21175. #createClipPath(defs, pathId) {
  21176. const clipPath = DrawLayer._svgFactory.createElement("clipPath");
  21177. defs.append(clipPath);
  21178. const clipPathId = `clip_${pathId}`;
  21179. clipPath.setAttribute("id", clipPathId);
  21180. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  21181. const clipPathUse = DrawLayer._svgFactory.createElement("use");
  21182. clipPath.append(clipPathUse);
  21183. clipPathUse.setAttribute("href", `#${pathId}`);
  21184. clipPathUse.classList.add("clip");
  21185. return clipPathId;
  21186. }
  21187. #updateProperties(element, properties) {
  21188. for (const [key, value] of Object.entries(properties)) {
  21189. if (value === null) {
  21190. element.removeAttribute(key);
  21191. } else {
  21192. element.setAttribute(key, value);
  21193. }
  21194. }
  21195. }
  21196. draw(properties, isPathUpdatable = false, hasClip = false) {
  21197. const id = this.#id++;
  21198. const root = this.#createSVG();
  21199. const defs = DrawLayer._svgFactory.createElement("defs");
  21200. root.append(defs);
  21201. const path = DrawLayer._svgFactory.createElement("path");
  21202. defs.append(path);
  21203. const pathId = `path_p${this.pageIndex}_${id}`;
  21204. path.setAttribute("id", pathId);
  21205. path.setAttribute("vector-effect", "non-scaling-stroke");
  21206. if (isPathUpdatable) {
  21207. this.#toUpdate.set(id, path);
  21208. }
  21209. const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null;
  21210. const use = DrawLayer._svgFactory.createElement("use");
  21211. root.append(use);
  21212. use.setAttribute("href", `#${pathId}`);
  21213. this.updateProperties(root, properties);
  21214. this.#mapping.set(id, root);
  21215. return {
  21216. id,
  21217. clipPathId: `url(#${clipPathId})`
  21218. };
  21219. }
  21220. drawOutline(properties, mustRemoveSelfIntersections) {
  21221. const id = this.#id++;
  21222. const root = this.#createSVG();
  21223. const defs = DrawLayer._svgFactory.createElement("defs");
  21224. root.append(defs);
  21225. const path = DrawLayer._svgFactory.createElement("path");
  21226. defs.append(path);
  21227. const pathId = `path_p${this.pageIndex}_${id}`;
  21228. path.setAttribute("id", pathId);
  21229. path.setAttribute("vector-effect", "non-scaling-stroke");
  21230. let maskId;
  21231. if (mustRemoveSelfIntersections) {
  21232. const mask = DrawLayer._svgFactory.createElement("mask");
  21233. defs.append(mask);
  21234. maskId = `mask_p${this.pageIndex}_${id}`;
  21235. mask.setAttribute("id", maskId);
  21236. mask.setAttribute("maskUnits", "objectBoundingBox");
  21237. const rect = DrawLayer._svgFactory.createElement("rect");
  21238. mask.append(rect);
  21239. rect.setAttribute("width", "1");
  21240. rect.setAttribute("height", "1");
  21241. rect.setAttribute("fill", "white");
  21242. const use = DrawLayer._svgFactory.createElement("use");
  21243. mask.append(use);
  21244. use.setAttribute("href", `#${pathId}`);
  21245. use.setAttribute("stroke", "none");
  21246. use.setAttribute("fill", "black");
  21247. use.setAttribute("fill-rule", "nonzero");
  21248. use.classList.add("mask");
  21249. }
  21250. const use1 = DrawLayer._svgFactory.createElement("use");
  21251. root.append(use1);
  21252. use1.setAttribute("href", `#${pathId}`);
  21253. if (maskId) {
  21254. use1.setAttribute("mask", `url(#${maskId})`);
  21255. }
  21256. const use2 = use1.cloneNode();
  21257. root.append(use2);
  21258. use1.classList.add("mainOutline");
  21259. use2.classList.add("secondaryOutline");
  21260. this.updateProperties(root, properties);
  21261. this.#mapping.set(id, root);
  21262. return id;
  21263. }
  21264. finalizeDraw(id, properties) {
  21265. this.#toUpdate.delete(id);
  21266. this.updateProperties(id, properties);
  21267. }
  21268. updateProperties(elementOrId, properties) {
  21269. if (!properties) {
  21270. return;
  21271. }
  21272. const {
  21273. root,
  21274. bbox,
  21275. rootClass,
  21276. path
  21277. } = properties;
  21278. const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId;
  21279. if (!element) {
  21280. return;
  21281. }
  21282. if (root) {
  21283. this.#updateProperties(element, root);
  21284. }
  21285. if (bbox) {
  21286. DrawLayer.#setBox(element, bbox);
  21287. }
  21288. if (rootClass) {
  21289. const {
  21290. classList
  21291. } = element;
  21292. for (const [className, value] of Object.entries(rootClass)) {
  21293. classList.toggle(className, value);
  21294. }
  21295. }
  21296. if (path) {
  21297. const defs = element.firstChild;
  21298. const pathElement = defs.firstChild;
  21299. this.#updateProperties(pathElement, path);
  21300. }
  21301. }
  21302. updateParent(id, layer) {
  21303. if (layer === this) {
  21304. return;
  21305. }
  21306. const root = this.#mapping.get(id);
  21307. if (!root) {
  21308. return;
  21309. }
  21310. layer.#parent.append(root);
  21311. this.#mapping.delete(id);
  21312. layer.#mapping.set(id, root);
  21313. }
  21314. remove(id) {
  21315. this.#toUpdate.delete(id);
  21316. if (this.#parent === null) {
  21317. return;
  21318. }
  21319. this.#mapping.get(id).remove();
  21320. this.#mapping.delete(id);
  21321. }
  21322. destroy() {
  21323. this.#parent = null;
  21324. for (const root of this.#mapping.values()) {
  21325. root.remove();
  21326. }
  21327. this.#mapping.clear();
  21328. this.#toUpdate.clear();
  21329. }
  21330. }
  21331. ;// ./src/pdf.js
  21332. const pdfjsVersion = "4.10.38";
  21333. const pdfjsBuild = "f9bea397f";
  21334. {
  21335. globalThis.pdfjsTestingUtils = {
  21336. HighlightOutliner: HighlightOutliner
  21337. };
  21338. }
  21339. var __webpack_exports__AbortException = __webpack_exports__.AbortException;
  21340. var __webpack_exports__AnnotationEditorLayer = __webpack_exports__.AnnotationEditorLayer;
  21341. var __webpack_exports__AnnotationEditorParamsType = __webpack_exports__.AnnotationEditorParamsType;
  21342. var __webpack_exports__AnnotationEditorType = __webpack_exports__.AnnotationEditorType;
  21343. var __webpack_exports__AnnotationEditorUIManager = __webpack_exports__.AnnotationEditorUIManager;
  21344. var __webpack_exports__AnnotationLayer = __webpack_exports__.AnnotationLayer;
  21345. var __webpack_exports__AnnotationMode = __webpack_exports__.AnnotationMode;
  21346. var __webpack_exports__ColorPicker = __webpack_exports__.ColorPicker;
  21347. var __webpack_exports__DOMSVGFactory = __webpack_exports__.DOMSVGFactory;
  21348. var __webpack_exports__DrawLayer = __webpack_exports__.DrawLayer;
  21349. var __webpack_exports__FeatureTest = __webpack_exports__.FeatureTest;
  21350. var __webpack_exports__GlobalWorkerOptions = __webpack_exports__.GlobalWorkerOptions;
  21351. var __webpack_exports__ImageKind = __webpack_exports__.ImageKind;
  21352. var __webpack_exports__InvalidPDFException = __webpack_exports__.InvalidPDFException;
  21353. var __webpack_exports__MissingPDFException = __webpack_exports__.MissingPDFException;
  21354. var __webpack_exports__OPS = __webpack_exports__.OPS;
  21355. var __webpack_exports__OutputScale = __webpack_exports__.OutputScale;
  21356. var __webpack_exports__PDFDataRangeTransport = __webpack_exports__.PDFDataRangeTransport;
  21357. var __webpack_exports__PDFDateString = __webpack_exports__.PDFDateString;
  21358. var __webpack_exports__PDFWorker = __webpack_exports__.PDFWorker;
  21359. var __webpack_exports__PasswordResponses = __webpack_exports__.PasswordResponses;
  21360. var __webpack_exports__PermissionFlag = __webpack_exports__.PermissionFlag;
  21361. var __webpack_exports__PixelsPerInch = __webpack_exports__.PixelsPerInch;
  21362. var __webpack_exports__RenderingCancelledException = __webpack_exports__.RenderingCancelledException;
  21363. var __webpack_exports__TextLayer = __webpack_exports__.TextLayer;
  21364. var __webpack_exports__TouchManager = __webpack_exports__.TouchManager;
  21365. var __webpack_exports__UnexpectedResponseException = __webpack_exports__.UnexpectedResponseException;
  21366. var __webpack_exports__Util = __webpack_exports__.Util;
  21367. var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel;
  21368. var __webpack_exports__XfaLayer = __webpack_exports__.XfaLayer;
  21369. var __webpack_exports__build = __webpack_exports__.build;
  21370. var __webpack_exports__createValidAbsoluteUrl = __webpack_exports__.createValidAbsoluteUrl;
  21371. var __webpack_exports__fetchData = __webpack_exports__.fetchData;
  21372. var __webpack_exports__getDocument = __webpack_exports__.getDocument;
  21373. var __webpack_exports__getFilenameFromUrl = __webpack_exports__.getFilenameFromUrl;
  21374. var __webpack_exports__getPdfFilenameFromUrl = __webpack_exports__.getPdfFilenameFromUrl;
  21375. var __webpack_exports__getXfaPageViewport = __webpack_exports__.getXfaPageViewport;
  21376. var __webpack_exports__isDataScheme = __webpack_exports__.isDataScheme;
  21377. var __webpack_exports__isPdfFile = __webpack_exports__.isPdfFile;
  21378. var __webpack_exports__noContextMenu = __webpack_exports__.noContextMenu;
  21379. var __webpack_exports__normalizeUnicode = __webpack_exports__.normalizeUnicode;
  21380. var __webpack_exports__setLayerDimensions = __webpack_exports__.setLayerDimensions;
  21381. var __webpack_exports__shadow = __webpack_exports__.shadow;
  21382. var __webpack_exports__stopEvent = __webpack_exports__.stopEvent;
  21383. var __webpack_exports__version = __webpack_exports__.version;
  21384. 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__TouchManager as TouchManager, __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__stopEvent as stopEvent, __webpack_exports__version as version };
  21385. //# sourceMappingURL=pdf.mjs.map