viewer.js 497 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2023 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. /******/ (() => {
  23. // webpackBootstrap
  24. /******/ 'use strict';
  25. /******/ var __webpack_modules__ = [
  26. ,
  27. /* 0 */ /* 1 */
  28. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  29. Object.defineProperty(exports, '__esModule', {
  30. value: true
  31. });
  32. exports.GenericCom = void 0;
  33. var _app = __webpack_require__(2);
  34. var _preferences = __webpack_require__(41);
  35. var _download_manager = __webpack_require__(42);
  36. var _genericl10n = __webpack_require__(43);
  37. var _generic_scripting = __webpack_require__(45);
  38. const GenericCom = {};
  39. exports.GenericCom = GenericCom;
  40. class GenericPreferences extends _preferences.BasePreferences {
  41. async _writeToStorage(prefObj) {
  42. localStorage.setItem('pdfjs.preferences', JSON.stringify(prefObj));
  43. }
  44. async _readFromStorage(prefObj) {
  45. return JSON.parse(localStorage.getItem('pdfjs.preferences'));
  46. }
  47. }
  48. class GenericExternalServices extends _app.DefaultExternalServices {
  49. static createDownloadManager() {
  50. return new _download_manager.DownloadManager();
  51. }
  52. static createPreferences() {
  53. return new GenericPreferences();
  54. }
  55. static createL10n({ locale = 'en-US' }) {
  56. return new _genericl10n.GenericL10n(locale);
  57. }
  58. static createScripting({ sandboxBundleSrc }) {
  59. return new _generic_scripting.GenericScripting(sandboxBundleSrc);
  60. }
  61. }
  62. _app.PDFViewerApplication.externalServices = GenericExternalServices;
  63. /***/
  64. },
  65. /* 2 */
  66. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  67. Object.defineProperty(exports, '__esModule', {
  68. value: true
  69. });
  70. exports.PDFViewerApplication = exports.PDFPrintServiceFactory = exports.DefaultExternalServices = void 0;
  71. var _ui_utils = __webpack_require__(3);
  72. var _pdfjsLib = __webpack_require__(4);
  73. var _app_options = __webpack_require__(5);
  74. var _event_utils = __webpack_require__(6);
  75. var _pdf_link_service = __webpack_require__(7);
  76. var _webAnnotation_editor_params = __webpack_require__(8);
  77. var _overlay_manager = __webpack_require__(9);
  78. var _password_prompt = __webpack_require__(10);
  79. var _webPdf_attachment_viewer = __webpack_require__(11);
  80. var _webPdf_cursor_tools = __webpack_require__(13);
  81. var _webPdf_document_properties = __webpack_require__(15);
  82. var _webPdf_find_bar = __webpack_require__(16);
  83. var _pdf_find_controller = __webpack_require__(17);
  84. var _pdf_history = __webpack_require__(19);
  85. var _webPdf_layer_viewer = __webpack_require__(20);
  86. var _webPdf_outline_viewer = __webpack_require__(21);
  87. var _webPdf_presentation_mode = __webpack_require__(22);
  88. var _pdf_rendering_queue = __webpack_require__(23);
  89. var _pdf_scripting_manager = __webpack_require__(24);
  90. var _webPdf_sidebar = __webpack_require__(25);
  91. var _webPdf_thumbnail_viewer = __webpack_require__(26);
  92. var _pdf_viewer = __webpack_require__(28);
  93. var _webSecondary_toolbar = __webpack_require__(38);
  94. var _webToolbar = __webpack_require__(39);
  95. var _view_history = __webpack_require__(40);
  96. const FORCE_PAGES_LOADED_TIMEOUT = 10000;
  97. const WHEEL_ZOOM_DISABLED_TIMEOUT = 1000;
  98. const ViewOnLoad = {
  99. UNKNOWN: -1,
  100. PREVIOUS: 0,
  101. INITIAL: 1
  102. };
  103. const ViewerCssTheme = {
  104. AUTOMATIC: 0,
  105. LIGHT: 1,
  106. DARK: 2
  107. };
  108. class DefaultExternalServices {
  109. constructor() {
  110. throw new Error('Cannot initialize DefaultExternalServices.');
  111. }
  112. static updateFindControlState(data) {}
  113. static updateFindMatchesCount(data) {}
  114. static initPassiveLoading(callbacks) {}
  115. static reportTelemetry(data) {}
  116. static createDownloadManager() {
  117. throw new Error('Not implemented: createDownloadManager');
  118. }
  119. static createPreferences() {
  120. throw new Error('Not implemented: createPreferences');
  121. }
  122. static createL10n(options) {
  123. throw new Error('Not implemented: createL10n');
  124. }
  125. static createScripting(options) {
  126. throw new Error('Not implemented: createScripting');
  127. }
  128. static get supportsPinchToZoom() {
  129. return (0, _pdfjsLib.shadow)(this, 'supportsPinchToZoom', true);
  130. }
  131. static get supportsIntegratedFind() {
  132. return (0, _pdfjsLib.shadow)(this, 'supportsIntegratedFind', false);
  133. }
  134. static get supportsDocumentFonts() {
  135. return (0, _pdfjsLib.shadow)(this, 'supportsDocumentFonts', true);
  136. }
  137. static get supportedMouseWheelZoomModifierKeys() {
  138. return (0, _pdfjsLib.shadow)(this, 'supportedMouseWheelZoomModifierKeys', {
  139. ctrlKey: true,
  140. metaKey: true
  141. });
  142. }
  143. static get isInAutomation() {
  144. return (0, _pdfjsLib.shadow)(this, 'isInAutomation', false);
  145. }
  146. static updateEditorStates(data) {
  147. throw new Error('Not implemented: updateEditorStates');
  148. }
  149. static get canvasMaxAreaInBytes() {
  150. return (0, _pdfjsLib.shadow)(this, 'canvasMaxAreaInBytes', -1);
  151. }
  152. static getNimbusExperimentData() {
  153. return (0, _pdfjsLib.shadow)(this, 'getNimbusExperimentData', Promise.resolve(null));
  154. }
  155. }
  156. exports.DefaultExternalServices = DefaultExternalServices;
  157. const PDFViewerApplication = {
  158. initialBookmark: document.location.hash.substring(1),
  159. _initializedCapability: new _pdfjsLib.PromiseCapability(),
  160. appConfig: null,
  161. pdfDocument: null,
  162. pdfLoadingTask: null,
  163. printService: null,
  164. pdfViewer: null,
  165. pdfThumbnailViewer: null,
  166. pdfRenderingQueue: null,
  167. pdfPresentationMode: null,
  168. pdfDocumentProperties: null,
  169. pdfLinkService: null,
  170. pdfHistory: null,
  171. pdfSidebar: null,
  172. pdfOutlineViewer: null,
  173. pdfAttachmentViewer: null,
  174. pdfLayerViewer: null,
  175. pdfCursorTools: null,
  176. pdfScriptingManager: null,
  177. store: null,
  178. downloadManager: null,
  179. overlayManager: null,
  180. preferences: null,
  181. toolbar: null,
  182. secondaryToolbar: null,
  183. eventBus: null,
  184. l10n: null,
  185. annotationEditorParams: null,
  186. isInitialViewSet: false,
  187. downloadComplete: false,
  188. isViewerEmbedded: window.parent !== window,
  189. url: '',
  190. baseUrl: '',
  191. _downloadUrl: '',
  192. externalServices: DefaultExternalServices,
  193. _boundEvents: Object.create(null),
  194. documentInfo: null,
  195. metadata: null,
  196. _contentDispositionFilename: null,
  197. _contentLength: null,
  198. _saveInProgress: false,
  199. _wheelUnusedTicks: 0,
  200. _wheelUnusedFactor: 1,
  201. _touchUnusedTicks: 0,
  202. _touchUnusedFactor: 1,
  203. _PDFBug: null,
  204. _hasAnnotationEditors: false,
  205. _title: document.title,
  206. _printAnnotationStoragePromise: null,
  207. _touchInfo: null,
  208. _isCtrlKeyDown: false,
  209. _nimbusDataPromise: null,
  210. async initialize(appConfig) {
  211. this.preferences = this.externalServices.createPreferences();
  212. this.appConfig = appConfig;
  213. await this._initializeOptions();
  214. this._forceCssTheme();
  215. await this._initializeL10n();
  216. if (this.isViewerEmbedded && _app_options.AppOptions.get('externalLinkTarget') === _pdf_link_service.LinkTarget.NONE) {
  217. _app_options.AppOptions.set('externalLinkTarget', _pdf_link_service.LinkTarget.TOP);
  218. }
  219. await this._initializeViewerComponents();
  220. this.bindEvents();
  221. this.bindWindowEvents();
  222. const appContainer = appConfig.appContainer || document.documentElement;
  223. this.l10n.translate(appContainer).then(() => {
  224. this.eventBus.dispatch('localized', {
  225. source: this
  226. });
  227. });
  228. this._initializedCapability.resolve();
  229. },
  230. async _initializeOptions() {
  231. if (_app_options.AppOptions.get('disablePreferences')) {
  232. if (_app_options.AppOptions.get('pdfBugEnabled')) {
  233. await this._parseHashParams();
  234. }
  235. return;
  236. }
  237. if (_app_options.AppOptions._hasUserOptions()) {
  238. console.warn(
  239. '_initializeOptions: The Preferences may override manually set AppOptions; ' +
  240. 'please use the "disablePreferences"-option in order to prevent that.'
  241. );
  242. }
  243. try {
  244. _app_options.AppOptions.setAll(await this.preferences.getAll());
  245. } catch (reason) {
  246. console.error(`_initializeOptions: "${reason.message}".`);
  247. }
  248. if (_app_options.AppOptions.get('pdfBugEnabled')) {
  249. await this._parseHashParams();
  250. }
  251. },
  252. async _parseHashParams() {
  253. const hash = document.location.hash.substring(1);
  254. if (!hash) {
  255. return;
  256. }
  257. const { mainContainer, viewerContainer } = this.appConfig,
  258. params = (0, _ui_utils.parseQueryString)(hash);
  259. if (params.get('disableworker') === 'true') {
  260. try {
  261. await loadFakeWorker();
  262. } catch (ex) {
  263. console.error(`_parseHashParams: "${ex.message}".`);
  264. }
  265. }
  266. if (params.has('disablerange')) {
  267. _app_options.AppOptions.set('disableRange', params.get('disablerange') === 'true');
  268. }
  269. if (params.has('disablestream')) {
  270. _app_options.AppOptions.set('disableStream', params.get('disablestream') === 'true');
  271. }
  272. if (params.has('disableautofetch')) {
  273. _app_options.AppOptions.set('disableAutoFetch', params.get('disableautofetch') === 'true');
  274. }
  275. if (params.has('disablefontface')) {
  276. _app_options.AppOptions.set('disableFontFace', params.get('disablefontface') === 'true');
  277. }
  278. if (params.has('disablehistory')) {
  279. _app_options.AppOptions.set('disableHistory', params.get('disablehistory') === 'true');
  280. }
  281. if (params.has('verbosity')) {
  282. _app_options.AppOptions.set('verbosity', params.get('verbosity') | 0);
  283. }
  284. if (params.has('textlayer')) {
  285. switch (params.get('textlayer')) {
  286. case 'off':
  287. _app_options.AppOptions.set('textLayerMode', _ui_utils.TextLayerMode.DISABLE);
  288. break;
  289. case 'visible':
  290. case 'shadow':
  291. case 'hover':
  292. viewerContainer.classList.add(`textLayer-${params.get('textlayer')}`);
  293. try {
  294. await loadPDFBug(this);
  295. this._PDFBug.loadCSS();
  296. } catch (ex) {
  297. console.error(`_parseHashParams: "${ex.message}".`);
  298. }
  299. break;
  300. }
  301. }
  302. if (params.has('pdfbug')) {
  303. _app_options.AppOptions.set('pdfBug', true);
  304. _app_options.AppOptions.set('fontExtraProperties', true);
  305. const enabled = params.get('pdfbug').split(',');
  306. try {
  307. await loadPDFBug(this);
  308. this._PDFBug.init(
  309. {
  310. OPS: _pdfjsLib.OPS
  311. },
  312. mainContainer,
  313. enabled
  314. );
  315. } catch (ex) {
  316. console.error(`_parseHashParams: "${ex.message}".`);
  317. }
  318. }
  319. if (params.has('locale')) {
  320. _app_options.AppOptions.set('locale', params.get('locale'));
  321. }
  322. },
  323. async _initializeL10n() {
  324. this.l10n = this.externalServices.createL10n({
  325. locale: _app_options.AppOptions.get('locale')
  326. });
  327. const dir = await this.l10n.getDirection();
  328. document.getElementsByTagName('html')[0].dir = dir;
  329. },
  330. _forceCssTheme() {
  331. const cssTheme = _app_options.AppOptions.get('viewerCssTheme');
  332. if (cssTheme === ViewerCssTheme.AUTOMATIC || !Object.values(ViewerCssTheme).includes(cssTheme)) {
  333. return;
  334. }
  335. try {
  336. const styleSheet = document.styleSheets[0];
  337. const cssRules = styleSheet?.cssRules || [];
  338. for (let i = 0, ii = cssRules.length; i < ii; i++) {
  339. const rule = cssRules[i];
  340. if (rule instanceof CSSMediaRule && rule.media?.[0] === '(prefers-color-scheme: dark)') {
  341. if (cssTheme === ViewerCssTheme.LIGHT) {
  342. styleSheet.deleteRule(i);
  343. return;
  344. }
  345. const darkRules = /^@media \(prefers-color-scheme: dark\) {\n\s*([\w\s-.,:;/\\{}()]+)\n}$/.exec(rule.cssText);
  346. if (darkRules?.[1]) {
  347. styleSheet.deleteRule(i);
  348. styleSheet.insertRule(darkRules[1], i);
  349. }
  350. return;
  351. }
  352. }
  353. } catch (reason) {
  354. console.error(`_forceCssTheme: "${reason?.message}".`);
  355. }
  356. },
  357. async _initializeViewerComponents() {
  358. const { appConfig, externalServices, l10n } = this;
  359. const eventBus = externalServices.isInAutomation ? new _event_utils.AutomationEventBus() : new _event_utils.EventBus();
  360. this.eventBus = eventBus;
  361. this.overlayManager = new _overlay_manager.OverlayManager();
  362. const pdfRenderingQueue = new _pdf_rendering_queue.PDFRenderingQueue();
  363. pdfRenderingQueue.onIdle = this._cleanup.bind(this);
  364. this.pdfRenderingQueue = pdfRenderingQueue;
  365. const pdfLinkService = new _pdf_link_service.PDFLinkService({
  366. eventBus,
  367. externalLinkTarget: _app_options.AppOptions.get('externalLinkTarget'),
  368. externalLinkRel: _app_options.AppOptions.get('externalLinkRel'),
  369. ignoreDestinationZoom: _app_options.AppOptions.get('ignoreDestinationZoom')
  370. });
  371. this.pdfLinkService = pdfLinkService;
  372. const downloadManager = externalServices.createDownloadManager();
  373. this.downloadManager = downloadManager;
  374. const findController = new _pdf_find_controller.PDFFindController({
  375. linkService: pdfLinkService,
  376. eventBus,
  377. updateMatchesCountOnProgress: true
  378. });
  379. this.findController = findController;
  380. const pdfScriptingManager = new _pdf_scripting_manager.PDFScriptingManager({
  381. eventBus,
  382. sandboxBundleSrc: _app_options.AppOptions.get('sandboxBundleSrc'),
  383. scriptingFactory: externalServices,
  384. docPropertiesLookup: this._scriptingDocProperties.bind(this)
  385. });
  386. this.pdfScriptingManager = pdfScriptingManager;
  387. const container = appConfig.mainContainer,
  388. viewer = appConfig.viewerContainer;
  389. const annotationEditorMode = _app_options.AppOptions.get('annotationEditorMode');
  390. const pageColors =
  391. _app_options.AppOptions.get('forcePageColors') || window.matchMedia('(forced-colors: active)').matches
  392. ? {
  393. background: _app_options.AppOptions.get('pageColorsBackground'),
  394. foreground: _app_options.AppOptions.get('pageColorsForeground')
  395. }
  396. : null;
  397. const pdfViewer = new _pdf_viewer.PDFViewer({
  398. container,
  399. viewer,
  400. eventBus,
  401. renderingQueue: pdfRenderingQueue,
  402. linkService: pdfLinkService,
  403. downloadManager,
  404. findController,
  405. scriptingManager: _app_options.AppOptions.get('enableScripting') && pdfScriptingManager,
  406. l10n,
  407. textLayerMode: _app_options.AppOptions.get('textLayerMode'),
  408. annotationMode: _app_options.AppOptions.get('annotationMode'),
  409. annotationEditorMode,
  410. imageResourcesPath: _app_options.AppOptions.get('imageResourcesPath'),
  411. enablePrintAutoRotate: _app_options.AppOptions.get('enablePrintAutoRotate'),
  412. useOnlyCssZoom: _app_options.AppOptions.get('useOnlyCssZoom'),
  413. isOffscreenCanvasSupported: _app_options.AppOptions.get('isOffscreenCanvasSupported'),
  414. maxCanvasPixels: _app_options.AppOptions.get('maxCanvasPixels'),
  415. enablePermissions: _app_options.AppOptions.get('enablePermissions'),
  416. pageColors
  417. });
  418. this.pdfViewer = pdfViewer;
  419. pdfRenderingQueue.setViewer(pdfViewer);
  420. pdfLinkService.setViewer(pdfViewer);
  421. pdfScriptingManager.setViewer(pdfViewer);
  422. if (appConfig.sidebar?.thumbnailView) {
  423. this.pdfThumbnailViewer = new _webPdf_thumbnail_viewer.PDFThumbnailViewer({
  424. container: appConfig.sidebar.thumbnailView,
  425. eventBus,
  426. renderingQueue: pdfRenderingQueue,
  427. linkService: pdfLinkService,
  428. l10n,
  429. pageColors
  430. });
  431. pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
  432. }
  433. if (!this.isViewerEmbedded && !_app_options.AppOptions.get('disableHistory')) {
  434. this.pdfHistory = new _pdf_history.PDFHistory({
  435. linkService: pdfLinkService,
  436. eventBus
  437. });
  438. pdfLinkService.setHistory(this.pdfHistory);
  439. }
  440. if (!this.supportsIntegratedFind && appConfig.findBar) {
  441. this.findBar = new _webPdf_find_bar.PDFFindBar(appConfig.findBar, eventBus, l10n);
  442. }
  443. if (appConfig.annotationEditorParams) {
  444. if (annotationEditorMode !== _pdfjsLib.AnnotationEditorType.DISABLE) {
  445. this.annotationEditorParams = new _webAnnotation_editor_params.AnnotationEditorParams(appConfig.annotationEditorParams, eventBus);
  446. } else {
  447. for (const id of ['editorModeButtons', 'editorModeSeparator']) {
  448. document.getElementById(id)?.classList.add('hidden');
  449. }
  450. }
  451. }
  452. if (appConfig.documentProperties) {
  453. this.pdfDocumentProperties = new _webPdf_document_properties.PDFDocumentProperties(
  454. appConfig.documentProperties,
  455. this.overlayManager,
  456. eventBus,
  457. l10n,
  458. () => this._docFilename
  459. );
  460. }
  461. if (appConfig.secondaryToolbar?.cursorHandToolButton) {
  462. this.pdfCursorTools = new _webPdf_cursor_tools.PDFCursorTools({
  463. container,
  464. eventBus,
  465. cursorToolOnLoad: _app_options.AppOptions.get('cursorToolOnLoad')
  466. });
  467. }
  468. if (appConfig.toolbar) {
  469. this.toolbar = new _webToolbar.Toolbar(appConfig.toolbar, eventBus, l10n);
  470. }
  471. if (appConfig.secondaryToolbar) {
  472. this.secondaryToolbar = new _webSecondary_toolbar.SecondaryToolbar(appConfig.secondaryToolbar, eventBus, externalServices);
  473. }
  474. if (this.supportsFullscreen && appConfig.secondaryToolbar?.presentationModeButton) {
  475. this.pdfPresentationMode = new _webPdf_presentation_mode.PDFPresentationMode({
  476. container,
  477. pdfViewer,
  478. eventBus
  479. });
  480. }
  481. if (appConfig.passwordOverlay) {
  482. this.passwordPrompt = new _password_prompt.PasswordPrompt(appConfig.passwordOverlay, this.overlayManager, l10n, this.isViewerEmbedded);
  483. }
  484. if (appConfig.sidebar?.outlineView) {
  485. this.pdfOutlineViewer = new _webPdf_outline_viewer.PDFOutlineViewer({
  486. container: appConfig.sidebar.outlineView,
  487. eventBus,
  488. linkService: pdfLinkService,
  489. downloadManager
  490. });
  491. }
  492. if (appConfig.sidebar?.attachmentsView) {
  493. this.pdfAttachmentViewer = new _webPdf_attachment_viewer.PDFAttachmentViewer({
  494. container: appConfig.sidebar.attachmentsView,
  495. eventBus,
  496. downloadManager
  497. });
  498. }
  499. if (appConfig.sidebar?.layersView) {
  500. this.pdfLayerViewer = new _webPdf_layer_viewer.PDFLayerViewer({
  501. container: appConfig.sidebar.layersView,
  502. eventBus,
  503. l10n
  504. });
  505. }
  506. if (appConfig.sidebar) {
  507. this.pdfSidebar = new _webPdf_sidebar.PDFSidebar({
  508. elements: appConfig.sidebar,
  509. eventBus,
  510. l10n
  511. });
  512. this.pdfSidebar.onToggled = this.forceRendering.bind(this);
  513. this.pdfSidebar.onUpdateThumbnails = () => {
  514. for (const pageView of pdfViewer.getCachedPageViews()) {
  515. if (pageView.renderingState === _ui_utils.RenderingStates.FINISHED) {
  516. this.pdfThumbnailViewer.getThumbnail(pageView.id - 1)?.setImage(pageView);
  517. }
  518. }
  519. this.pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber);
  520. };
  521. }
  522. },
  523. run(config) {
  524. this.initialize(config).then(webViewerInitialized);
  525. },
  526. get initialized() {
  527. return this._initializedCapability.settled;
  528. },
  529. get initializedPromise() {
  530. return this._initializedCapability.promise;
  531. },
  532. zoomIn(steps, scaleFactor) {
  533. if (this.pdfViewer.isInPresentationMode) {
  534. return;
  535. }
  536. this.pdfViewer.increaseScale({
  537. drawingDelay: _app_options.AppOptions.get('defaultZoomDelay'),
  538. steps,
  539. scaleFactor
  540. });
  541. },
  542. zoomOut(steps, scaleFactor) {
  543. if (this.pdfViewer.isInPresentationMode) {
  544. return;
  545. }
  546. this.pdfViewer.decreaseScale({
  547. drawingDelay: _app_options.AppOptions.get('defaultZoomDelay'),
  548. steps,
  549. scaleFactor
  550. });
  551. },
  552. zoomReset() {
  553. if (this.pdfViewer.isInPresentationMode) {
  554. return;
  555. }
  556. this.pdfViewer.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  557. },
  558. get pagesCount() {
  559. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  560. },
  561. get page() {
  562. return this.pdfViewer.currentPageNumber;
  563. },
  564. set page(val) {
  565. this.pdfViewer.currentPageNumber = val;
  566. },
  567. get supportsPrinting() {
  568. return PDFPrintServiceFactory.instance.supportsPrinting;
  569. },
  570. get supportsFullscreen() {
  571. return (0, _pdfjsLib.shadow)(this, 'supportsFullscreen', document.fullscreenEnabled);
  572. },
  573. get supportsPinchToZoom() {
  574. return this.externalServices.supportsPinchToZoom;
  575. },
  576. get supportsIntegratedFind() {
  577. return this.externalServices.supportsIntegratedFind;
  578. },
  579. get supportsDocumentFonts() {
  580. return this.externalServices.supportsDocumentFonts;
  581. },
  582. get loadingBar() {
  583. const barElement = document.getElementById('loadingBar');
  584. const bar = barElement ? new _ui_utils.ProgressBar(barElement) : null;
  585. return (0, _pdfjsLib.shadow)(this, 'loadingBar', bar);
  586. },
  587. get supportedMouseWheelZoomModifierKeys() {
  588. return this.externalServices.supportedMouseWheelZoomModifierKeys;
  589. },
  590. initPassiveLoading() {
  591. throw new Error('Not implemented: initPassiveLoading');
  592. },
  593. setTitleUsingUrl(url = '', downloadUrl = null) {
  594. this.url = url;
  595. this.baseUrl = url.split('#')[0];
  596. if (downloadUrl) {
  597. this._downloadUrl = downloadUrl === url ? this.baseUrl : downloadUrl.split('#')[0];
  598. }
  599. if ((0, _pdfjsLib.isDataScheme)(url)) {
  600. this._hideViewBookmark();
  601. }
  602. let title = (0, _pdfjsLib.getPdfFilenameFromUrl)(url, '');
  603. if (!title) {
  604. try {
  605. title = decodeURIComponent((0, _pdfjsLib.getFilenameFromUrl)(url)) || url;
  606. } catch (ex) {
  607. title = url;
  608. }
  609. }
  610. this.setTitle(title);
  611. },
  612. setTitle(title = this._title) {
  613. this._title = title;
  614. if (this.isViewerEmbedded) {
  615. return;
  616. }
  617. const editorIndicator = this._hasAnnotationEditors && !this.pdfRenderingQueue.printing;
  618. document.title = `${editorIndicator ? '* ' : ''}${title}`;
  619. },
  620. get _docFilename() {
  621. return this._contentDispositionFilename || (0, _pdfjsLib.getPdfFilenameFromUrl)(this.url);
  622. },
  623. _hideViewBookmark() {
  624. const { secondaryToolbar } = this.appConfig;
  625. secondaryToolbar?.viewBookmarkButton.classList.add('hidden');
  626. if (secondaryToolbar?.presentationModeButton.classList.contains('hidden')) {
  627. document.getElementById('viewBookmarkSeparator')?.classList.add('hidden');
  628. }
  629. },
  630. async close() {
  631. this._unblockDocumentLoadEvent();
  632. this._hideViewBookmark();
  633. if (!this.pdfLoadingTask) {
  634. return;
  635. }
  636. if (this.pdfDocument?.annotationStorage.size > 0 && this._annotationStorageModified) {
  637. try {
  638. await this.save();
  639. } catch (reason) {}
  640. }
  641. const promises = [];
  642. promises.push(this.pdfLoadingTask.destroy());
  643. this.pdfLoadingTask = null;
  644. if (this.pdfDocument) {
  645. this.pdfDocument = null;
  646. this.pdfThumbnailViewer?.setDocument(null);
  647. this.pdfViewer.setDocument(null);
  648. this.pdfLinkService.setDocument(null);
  649. this.pdfDocumentProperties?.setDocument(null);
  650. }
  651. this.pdfLinkService.externalLinkEnabled = true;
  652. this.store = null;
  653. this.isInitialViewSet = false;
  654. this.downloadComplete = false;
  655. this.url = '';
  656. this.baseUrl = '';
  657. this._downloadUrl = '';
  658. this.documentInfo = null;
  659. this.metadata = null;
  660. this._contentDispositionFilename = null;
  661. this._contentLength = null;
  662. this._saveInProgress = false;
  663. this._hasAnnotationEditors = false;
  664. promises.push(this.pdfScriptingManager.destroyPromise);
  665. this.setTitle();
  666. this.pdfSidebar?.reset();
  667. this.pdfOutlineViewer?.reset();
  668. this.pdfAttachmentViewer?.reset();
  669. this.pdfLayerViewer?.reset();
  670. this.pdfHistory?.reset();
  671. this.findBar?.reset();
  672. this.toolbar?.reset();
  673. this.secondaryToolbar?.reset();
  674. this._PDFBug?.cleanup();
  675. await Promise.all(promises);
  676. },
  677. async open(args) {
  678. let deprecatedArgs = false;
  679. if (typeof args === 'string') {
  680. args = {
  681. url: args
  682. };
  683. deprecatedArgs = true;
  684. } else if (args?.byteLength) {
  685. args = {
  686. data: args
  687. };
  688. deprecatedArgs = true;
  689. }
  690. if (deprecatedArgs) {
  691. console.error('The `PDFViewerApplication.open` signature was updated, please use an object instead.');
  692. }
  693. if (this.pdfLoadingTask) {
  694. await this.close();
  695. }
  696. const workerParams = _app_options.AppOptions.getAll(_app_options.OptionKind.WORKER);
  697. Object.assign(_pdfjsLib.GlobalWorkerOptions, workerParams);
  698. if (args.url) {
  699. this.setTitleUsingUrl(args.originalUrl || args.url, args.url);
  700. }
  701. const apiParams = _app_options.AppOptions.getAll(_app_options.OptionKind.API);
  702. const params = {
  703. canvasMaxAreaInBytes: this.externalServices.canvasMaxAreaInBytes,
  704. ...apiParams,
  705. ...args
  706. };
  707. const loadingTask = (0, _pdfjsLib.getDocument)(params);
  708. this.pdfLoadingTask = loadingTask;
  709. loadingTask.onPassword = (updateCallback, reason) => {
  710. if (this.isViewerEmbedded) {
  711. this._unblockDocumentLoadEvent();
  712. }
  713. this.pdfLinkService.externalLinkEnabled = false;
  714. this.passwordPrompt.setUpdateCallback(updateCallback, reason);
  715. this.passwordPrompt.open();
  716. };
  717. loadingTask.onProgress = ({ loaded, total }) => {
  718. this.progress(loaded / total);
  719. };
  720. return loadingTask.promise.then(
  721. (pdfDocument) => {
  722. this.load(pdfDocument);
  723. },
  724. (reason) => {
  725. if (loadingTask !== this.pdfLoadingTask) {
  726. return undefined;
  727. }
  728. let key = 'loading_error';
  729. if (reason instanceof _pdfjsLib.InvalidPDFException) {
  730. key = 'invalid_file_error';
  731. } else if (reason instanceof _pdfjsLib.MissingPDFException) {
  732. key = 'missing_file_error';
  733. } else if (reason instanceof _pdfjsLib.UnexpectedResponseException) {
  734. key = 'unexpected_response_error';
  735. }
  736. return this.l10n.get(key).then((msg) => {
  737. this._documentError(msg, {
  738. message: reason?.message
  739. });
  740. throw reason;
  741. });
  742. }
  743. );
  744. },
  745. _ensureDownloadComplete() {
  746. if (this.pdfDocument && this.downloadComplete) {
  747. return;
  748. }
  749. throw new Error('PDF document not downloaded.');
  750. },
  751. async download(options = {}) {
  752. const url = this._downloadUrl,
  753. filename = this._docFilename;
  754. try {
  755. this._ensureDownloadComplete();
  756. const data = await this.pdfDocument.getData();
  757. const blob = new Blob([data], {
  758. type: 'application/pdf'
  759. });
  760. await this.downloadManager.download(blob, url, filename, options);
  761. } catch (reason) {
  762. await this.downloadManager.downloadUrl(url, filename, options);
  763. }
  764. },
  765. async save(options = {}) {
  766. if (this._saveInProgress) {
  767. return;
  768. }
  769. this._saveInProgress = true;
  770. await this.pdfScriptingManager.dispatchWillSave();
  771. const url = this._downloadUrl,
  772. filename = this._docFilename;
  773. try {
  774. this._ensureDownloadComplete();
  775. const data = await this.pdfDocument.saveDocument();
  776. const blob = new Blob([data], {
  777. type: 'application/pdf'
  778. });
  779. await this.downloadManager.download(blob, url, filename, options);
  780. } catch (reason) {
  781. console.error(`Error when saving the document: ${reason.message}`);
  782. await this.download(options);
  783. } finally {
  784. await this.pdfScriptingManager.dispatchDidSave();
  785. this._saveInProgress = false;
  786. }
  787. if (this._hasAnnotationEditors) {
  788. this.externalServices.reportTelemetry({
  789. type: 'editing',
  790. data: {
  791. type: 'save'
  792. }
  793. });
  794. }
  795. },
  796. downloadOrSave(options = {}) {
  797. if (this.pdfDocument?.annotationStorage.size > 0) {
  798. this.save(options);
  799. } else {
  800. this.download(options);
  801. }
  802. },
  803. openInExternalApp() {
  804. this.downloadOrSave({
  805. openInExternalApp: true
  806. });
  807. },
  808. _documentError(message, moreInfo = null) {
  809. this._unblockDocumentLoadEvent();
  810. this._otherError(message, moreInfo);
  811. this.eventBus.dispatch('documenterror', {
  812. source: this,
  813. message,
  814. reason: moreInfo?.message ?? null
  815. });
  816. },
  817. _otherError(message, moreInfo = null) {
  818. const moreInfoText = [`PDF.js v${_pdfjsLib.version || '?'} (build: ${_pdfjsLib.build || '?'})`];
  819. if (moreInfo) {
  820. moreInfoText.push(`Message: ${moreInfo.message}`);
  821. if (moreInfo.stack) {
  822. moreInfoText.push(`Stack: ${moreInfo.stack}`);
  823. } else {
  824. if (moreInfo.filename) {
  825. moreInfoText.push(`File: ${moreInfo.filename}`);
  826. }
  827. if (moreInfo.lineNumber) {
  828. moreInfoText.push(`Line: ${moreInfo.lineNumber}`);
  829. }
  830. }
  831. }
  832. console.error(`${message}\n\n${moreInfoText.join('\n')}`);
  833. },
  834. progress(level) {
  835. if (!this.loadingBar || this.downloadComplete) {
  836. return;
  837. }
  838. const percent = Math.round(level * 100);
  839. if (percent <= this.loadingBar.percent) {
  840. return;
  841. }
  842. this.loadingBar.percent = percent;
  843. if (this.pdfDocument?.loadingParams.disableAutoFetch ?? _app_options.AppOptions.get('disableAutoFetch')) {
  844. this.loadingBar.setDisableAutoFetch();
  845. }
  846. },
  847. load(pdfDocument) {
  848. this.pdfDocument = pdfDocument;
  849. pdfDocument.getDownloadInfo().then(({ length }) => {
  850. this._contentLength = length;
  851. this.downloadComplete = true;
  852. this.loadingBar?.hide();
  853. firstPagePromise.then(() => {
  854. this.eventBus.dispatch('documentloaded', {
  855. source: this
  856. });
  857. });
  858. });
  859. const pageLayoutPromise = pdfDocument.getPageLayout().catch(function () {});
  860. const pageModePromise = pdfDocument.getPageMode().catch(function () {});
  861. const openActionPromise = pdfDocument.getOpenAction().catch(function () {});
  862. this.toolbar?.setPagesCount(pdfDocument.numPages, false);
  863. this.secondaryToolbar?.setPagesCount(pdfDocument.numPages);
  864. this.pdfLinkService.setDocument(pdfDocument);
  865. this.pdfDocumentProperties?.setDocument(pdfDocument);
  866. const pdfViewer = this.pdfViewer;
  867. pdfViewer.setDocument(pdfDocument);
  868. const { firstPagePromise, onePageRendered, pagesPromise } = pdfViewer;
  869. this.pdfThumbnailViewer?.setDocument(pdfDocument);
  870. const storedPromise = (this.store = new _view_history.ViewHistory(pdfDocument.fingerprints[0]))
  871. .getMultiple({
  872. page: null,
  873. zoom: _ui_utils.DEFAULT_SCALE_VALUE,
  874. scrollLeft: '0',
  875. scrollTop: '0',
  876. rotation: null,
  877. sidebarView: _ui_utils.SidebarView.UNKNOWN,
  878. scrollMode: _ui_utils.ScrollMode.UNKNOWN,
  879. spreadMode: _ui_utils.SpreadMode.UNKNOWN
  880. })
  881. .catch(() => {
  882. return Object.create(null);
  883. });
  884. firstPagePromise.then((pdfPage) => {
  885. this.loadingBar?.setWidth(this.appConfig.viewerContainer);
  886. this._initializeAnnotationStorageCallbacks(pdfDocument);
  887. Promise.all([_ui_utils.animationStarted, storedPromise, pageLayoutPromise, pageModePromise, openActionPromise])
  888. .then(async ([timeStamp, stored, pageLayout, pageMode, openAction]) => {
  889. const viewOnLoad = _app_options.AppOptions.get('viewOnLoad');
  890. this._initializePdfHistory({
  891. fingerprint: pdfDocument.fingerprints[0],
  892. viewOnLoad,
  893. initialDest: openAction?.dest
  894. });
  895. const initialBookmark = this.initialBookmark;
  896. const zoom = _app_options.AppOptions.get('defaultZoomValue');
  897. let hash = zoom ? `zoom=${zoom}` : null;
  898. let rotation = null;
  899. let sidebarView = _app_options.AppOptions.get('sidebarViewOnLoad');
  900. let scrollMode = _app_options.AppOptions.get('scrollModeOnLoad');
  901. let spreadMode = _app_options.AppOptions.get('spreadModeOnLoad');
  902. if (stored.page && viewOnLoad !== ViewOnLoad.INITIAL) {
  903. hash = `page=${stored.page}&zoom=${zoom || stored.zoom},` + `${stored.scrollLeft},${stored.scrollTop}`;
  904. rotation = parseInt(stored.rotation, 10);
  905. if (sidebarView === _ui_utils.SidebarView.UNKNOWN) {
  906. sidebarView = stored.sidebarView | 0;
  907. }
  908. if (scrollMode === _ui_utils.ScrollMode.UNKNOWN) {
  909. scrollMode = stored.scrollMode | 0;
  910. }
  911. if (spreadMode === _ui_utils.SpreadMode.UNKNOWN) {
  912. spreadMode = stored.spreadMode | 0;
  913. }
  914. }
  915. if (pageMode && sidebarView === _ui_utils.SidebarView.UNKNOWN) {
  916. sidebarView = (0, _ui_utils.apiPageModeToSidebarView)(pageMode);
  917. }
  918. if (pageLayout && scrollMode === _ui_utils.ScrollMode.UNKNOWN && spreadMode === _ui_utils.SpreadMode.UNKNOWN) {
  919. const modes = (0, _ui_utils.apiPageLayoutToViewerModes)(pageLayout);
  920. spreadMode = modes.spreadMode;
  921. }
  922. this.setInitialView(hash, {
  923. rotation,
  924. sidebarView,
  925. scrollMode,
  926. spreadMode
  927. });
  928. this.eventBus.dispatch('documentinit', {
  929. source: this
  930. });
  931. if (!this.isViewerEmbedded) {
  932. pdfViewer.focus();
  933. }
  934. await Promise.race([
  935. pagesPromise,
  936. new Promise((resolve) => {
  937. setTimeout(resolve, FORCE_PAGES_LOADED_TIMEOUT);
  938. })
  939. ]);
  940. if (!initialBookmark && !hash) {
  941. return;
  942. }
  943. if (pdfViewer.hasEqualPageSizes) {
  944. return;
  945. }
  946. this.initialBookmark = initialBookmark;
  947. pdfViewer.currentScaleValue = pdfViewer.currentScaleValue;
  948. this.setInitialView(hash);
  949. })
  950. .catch(() => {
  951. this.setInitialView();
  952. })
  953. .then(function () {
  954. pdfViewer.update();
  955. });
  956. });
  957. pagesPromise.then(
  958. () => {
  959. this._unblockDocumentLoadEvent();
  960. this._initializeAutoPrint(pdfDocument, openActionPromise);
  961. },
  962. (reason) => {
  963. this.l10n.get('loading_error').then((msg) => {
  964. this._documentError(msg, {
  965. message: reason?.message
  966. });
  967. });
  968. }
  969. );
  970. onePageRendered.then((data) => {
  971. this.externalServices.reportTelemetry({
  972. type: 'pageInfo',
  973. timestamp: data.timestamp
  974. });
  975. if (this.pdfOutlineViewer) {
  976. pdfDocument.getOutline().then((outline) => {
  977. if (pdfDocument !== this.pdfDocument) {
  978. return;
  979. }
  980. this.pdfOutlineViewer.render({
  981. outline,
  982. pdfDocument
  983. });
  984. });
  985. }
  986. if (this.pdfAttachmentViewer) {
  987. pdfDocument.getAttachments().then((attachments) => {
  988. if (pdfDocument !== this.pdfDocument) {
  989. return;
  990. }
  991. this.pdfAttachmentViewer.render({
  992. attachments
  993. });
  994. });
  995. }
  996. if (this.pdfLayerViewer) {
  997. pdfViewer.optionalContentConfigPromise.then((optionalContentConfig) => {
  998. if (pdfDocument !== this.pdfDocument) {
  999. return;
  1000. }
  1001. this.pdfLayerViewer.render({
  1002. optionalContentConfig,
  1003. pdfDocument
  1004. });
  1005. });
  1006. }
  1007. });
  1008. this._initializePageLabels(pdfDocument);
  1009. this._initializeMetadata(pdfDocument);
  1010. },
  1011. async _scriptingDocProperties(pdfDocument) {
  1012. if (!this.documentInfo) {
  1013. await new Promise((resolve) => {
  1014. this.eventBus._on('metadataloaded', resolve, {
  1015. once: true
  1016. });
  1017. });
  1018. if (pdfDocument !== this.pdfDocument) {
  1019. return null;
  1020. }
  1021. }
  1022. if (!this._contentLength) {
  1023. await new Promise((resolve) => {
  1024. this.eventBus._on('documentloaded', resolve, {
  1025. once: true
  1026. });
  1027. });
  1028. if (pdfDocument !== this.pdfDocument) {
  1029. return null;
  1030. }
  1031. }
  1032. return {
  1033. ...this.documentInfo,
  1034. baseURL: this.baseUrl,
  1035. filesize: this._contentLength,
  1036. filename: this._docFilename,
  1037. metadata: this.metadata?.getRaw(),
  1038. authors: this.metadata?.get('dc:creator'),
  1039. numPages: this.pagesCount,
  1040. URL: this.url
  1041. };
  1042. },
  1043. async _initializeAutoPrint(pdfDocument, openActionPromise) {
  1044. const [openAction, javaScript] = await Promise.all([
  1045. openActionPromise,
  1046. !this.pdfViewer.enableScripting ? pdfDocument.getJavaScript() : null
  1047. ]);
  1048. if (pdfDocument !== this.pdfDocument) {
  1049. return;
  1050. }
  1051. let triggerAutoPrint = false;
  1052. if (openAction?.action === 'Print') {
  1053. triggerAutoPrint = true;
  1054. }
  1055. if (javaScript) {
  1056. javaScript.some((js) => {
  1057. if (!js) {
  1058. return false;
  1059. }
  1060. console.warn('Warning: JavaScript support is not enabled');
  1061. return true;
  1062. });
  1063. if (!triggerAutoPrint) {
  1064. for (const js of javaScript) {
  1065. if (js && _ui_utils.AutoPrintRegExp.test(js)) {
  1066. triggerAutoPrint = true;
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. if (triggerAutoPrint) {
  1073. this.triggerPrinting();
  1074. }
  1075. },
  1076. async _initializeMetadata(pdfDocument) {
  1077. const { info, metadata, contentDispositionFilename, contentLength } = await pdfDocument.getMetadata();
  1078. if (pdfDocument !== this.pdfDocument) {
  1079. return;
  1080. }
  1081. this.documentInfo = info;
  1082. this.metadata = metadata;
  1083. this._contentDispositionFilename ??= contentDispositionFilename;
  1084. this._contentLength ??= contentLength;
  1085. console.log(
  1086. `PDF ${pdfDocument.fingerprints[0]} [${info.PDFFormatVersion} ` +
  1087. `${(info.Producer || '-').trim()} / ${(info.Creator || '-').trim()}] ` +
  1088. `(PDF.js: ${_pdfjsLib.version || '?'} [${_pdfjsLib.build || '?'}])`
  1089. );
  1090. let pdfTitle = info.Title;
  1091. const metadataTitle = metadata?.get('dc:title');
  1092. if (metadataTitle) {
  1093. if (metadataTitle !== 'Untitled' && !/[\uFFF0-\uFFFF]/g.test(metadataTitle)) {
  1094. pdfTitle = metadataTitle;
  1095. }
  1096. }
  1097. if (pdfTitle) {
  1098. this.setTitle(`${pdfTitle} - ${this._contentDispositionFilename || this._title}`);
  1099. } else if (this._contentDispositionFilename) {
  1100. this.setTitle(this._contentDispositionFilename);
  1101. }
  1102. if (info.IsXFAPresent && !info.IsAcroFormPresent && !pdfDocument.isPureXfa) {
  1103. if (pdfDocument.loadingParams.enableXfa) {
  1104. console.warn('Warning: XFA Foreground documents are not supported');
  1105. } else {
  1106. console.warn('Warning: XFA support is not enabled');
  1107. }
  1108. } else if ((info.IsAcroFormPresent || info.IsXFAPresent) && !this.pdfViewer.renderForms) {
  1109. console.warn('Warning: Interactive form support is not enabled');
  1110. }
  1111. if (info.IsSignaturesPresent) {
  1112. console.warn('Warning: Digital signatures validation is not supported');
  1113. }
  1114. this.eventBus.dispatch('metadataloaded', {
  1115. source: this
  1116. });
  1117. },
  1118. async _initializePageLabels(pdfDocument) {
  1119. const labels = await pdfDocument.getPageLabels();
  1120. if (pdfDocument !== this.pdfDocument) {
  1121. return;
  1122. }
  1123. if (!labels || _app_options.AppOptions.get('disablePageLabels')) {
  1124. return;
  1125. }
  1126. const numLabels = labels.length;
  1127. let standardLabels = 0,
  1128. emptyLabels = 0;
  1129. for (let i = 0; i < numLabels; i++) {
  1130. const label = labels[i];
  1131. if (label === (i + 1).toString()) {
  1132. standardLabels++;
  1133. } else if (label === '') {
  1134. emptyLabels++;
  1135. } else {
  1136. break;
  1137. }
  1138. }
  1139. if (standardLabels >= numLabels || emptyLabels >= numLabels) {
  1140. return;
  1141. }
  1142. const { pdfViewer, pdfThumbnailViewer, toolbar } = this;
  1143. pdfViewer.setPageLabels(labels);
  1144. pdfThumbnailViewer?.setPageLabels(labels);
  1145. toolbar?.setPagesCount(numLabels, true);
  1146. toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  1147. },
  1148. _initializePdfHistory({ fingerprint, viewOnLoad, initialDest = null }) {
  1149. if (!this.pdfHistory) {
  1150. return;
  1151. }
  1152. this.pdfHistory.initialize({
  1153. fingerprint,
  1154. resetHistory: viewOnLoad === ViewOnLoad.INITIAL,
  1155. updateUrl: _app_options.AppOptions.get('historyUpdateUrl')
  1156. });
  1157. if (this.pdfHistory.initialBookmark) {
  1158. this.initialBookmark = this.pdfHistory.initialBookmark;
  1159. this.initialRotation = this.pdfHistory.initialRotation;
  1160. }
  1161. if (initialDest && !this.initialBookmark && viewOnLoad === ViewOnLoad.UNKNOWN) {
  1162. this.initialBookmark = JSON.stringify(initialDest);
  1163. this.pdfHistory.push({
  1164. explicitDest: initialDest,
  1165. pageNumber: null
  1166. });
  1167. }
  1168. },
  1169. _initializeAnnotationStorageCallbacks(pdfDocument) {
  1170. if (pdfDocument !== this.pdfDocument) {
  1171. return;
  1172. }
  1173. const { annotationStorage } = pdfDocument;
  1174. annotationStorage.onSetModified = () => {
  1175. window.addEventListener('beforeunload', beforeUnload);
  1176. this._annotationStorageModified = true;
  1177. };
  1178. annotationStorage.onResetModified = () => {
  1179. window.removeEventListener('beforeunload', beforeUnload);
  1180. delete this._annotationStorageModified;
  1181. };
  1182. annotationStorage.onAnnotationEditor = (typeStr) => {
  1183. this._hasAnnotationEditors = !!typeStr;
  1184. this.setTitle();
  1185. if (typeStr) {
  1186. this.externalServices.reportTelemetry({
  1187. type: 'editing',
  1188. data: {
  1189. type: typeStr
  1190. }
  1191. });
  1192. }
  1193. };
  1194. },
  1195. setInitialView(storedHash, { rotation, sidebarView, scrollMode, spreadMode } = {}) {
  1196. const setRotation = (angle) => {
  1197. if ((0, _ui_utils.isValidRotation)(angle)) {
  1198. this.pdfViewer.pagesRotation = angle;
  1199. }
  1200. };
  1201. const setViewerModes = (scroll, spread) => {
  1202. if ((0, _ui_utils.isValidScrollMode)(scroll)) {
  1203. this.pdfViewer.scrollMode = scroll;
  1204. }
  1205. if ((0, _ui_utils.isValidSpreadMode)(spread)) {
  1206. this.pdfViewer.spreadMode = spread;
  1207. }
  1208. };
  1209. this.isInitialViewSet = true;
  1210. this.pdfSidebar?.setInitialView(sidebarView);
  1211. setViewerModes(scrollMode, spreadMode);
  1212. if (this.initialBookmark) {
  1213. setRotation(this.initialRotation);
  1214. delete this.initialRotation;
  1215. this.pdfLinkService.setHash(this.initialBookmark);
  1216. this.initialBookmark = null;
  1217. } else if (storedHash) {
  1218. setRotation(rotation);
  1219. this.pdfLinkService.setHash(storedHash);
  1220. }
  1221. this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber, this.pdfViewer.currentPageLabel);
  1222. this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber);
  1223. if (!this.pdfViewer.currentScaleValue) {
  1224. this.pdfViewer.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  1225. }
  1226. },
  1227. _cleanup() {
  1228. if (!this.pdfDocument) {
  1229. return;
  1230. }
  1231. this.pdfViewer.cleanup();
  1232. this.pdfThumbnailViewer?.cleanup();
  1233. this.pdfDocument.cleanup();
  1234. },
  1235. forceRendering() {
  1236. this.pdfRenderingQueue.printing = !!this.printService;
  1237. this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar?.visibleView === _ui_utils.SidebarView.THUMBS;
  1238. this.pdfRenderingQueue.renderHighestPriority();
  1239. },
  1240. beforePrint() {
  1241. this._printAnnotationStoragePromise = this.pdfScriptingManager
  1242. .dispatchWillPrint()
  1243. .catch(() => {})
  1244. .then(() => {
  1245. return this.pdfDocument?.annotationStorage.print;
  1246. });
  1247. if (this.printService) {
  1248. return;
  1249. }
  1250. if (!this.supportsPrinting) {
  1251. this.l10n.get('printing_not_supported').then((msg) => {
  1252. this._otherError(msg);
  1253. });
  1254. return;
  1255. }
  1256. if (!this.pdfViewer.pageViewsReady) {
  1257. this.l10n.get('printing_not_ready').then((msg) => {
  1258. window.alert(msg);
  1259. });
  1260. return;
  1261. }
  1262. const pagesOverview = this.pdfViewer.getPagesOverview();
  1263. const printContainer = this.appConfig.printContainer;
  1264. const printResolution = _app_options.AppOptions.get('printResolution');
  1265. const optionalContentConfigPromise = this.pdfViewer.optionalContentConfigPromise;
  1266. const printService = PDFPrintServiceFactory.instance.createPrintService(
  1267. this.pdfDocument,
  1268. pagesOverview,
  1269. printContainer,
  1270. printResolution,
  1271. optionalContentConfigPromise,
  1272. this._printAnnotationStoragePromise,
  1273. this.l10n
  1274. );
  1275. this.printService = printService;
  1276. this.forceRendering();
  1277. this.setTitle();
  1278. printService.layout();
  1279. if (this._hasAnnotationEditors) {
  1280. this.externalServices.reportTelemetry({
  1281. type: 'editing',
  1282. data: {
  1283. type: 'print'
  1284. }
  1285. });
  1286. }
  1287. },
  1288. afterPrint() {
  1289. if (this._printAnnotationStoragePromise) {
  1290. this._printAnnotationStoragePromise.then(() => {
  1291. this.pdfScriptingManager.dispatchDidPrint();
  1292. });
  1293. this._printAnnotationStoragePromise = null;
  1294. }
  1295. if (this.printService) {
  1296. this.printService.destroy();
  1297. this.printService = null;
  1298. this.pdfDocument?.annotationStorage.resetModified();
  1299. }
  1300. this.forceRendering();
  1301. this.setTitle();
  1302. },
  1303. rotatePages(delta) {
  1304. this.pdfViewer.pagesRotation += delta;
  1305. },
  1306. requestPresentationMode() {
  1307. this.pdfPresentationMode?.request();
  1308. },
  1309. triggerPrinting() {
  1310. if (!this.supportsPrinting) {
  1311. return;
  1312. }
  1313. window.print();
  1314. },
  1315. bindEvents() {
  1316. const { eventBus, _boundEvents } = this;
  1317. _boundEvents.beforePrint = this.beforePrint.bind(this);
  1318. _boundEvents.afterPrint = this.afterPrint.bind(this);
  1319. eventBus._on('resize', webViewerResize);
  1320. eventBus._on('hashchange', webViewerHashchange);
  1321. eventBus._on('beforeprint', _boundEvents.beforePrint);
  1322. eventBus._on('afterprint', _boundEvents.afterPrint);
  1323. eventBus._on('pagerender', webViewerPageRender);
  1324. eventBus._on('pagerendered', webViewerPageRendered);
  1325. eventBus._on('updateviewarea', webViewerUpdateViewarea);
  1326. eventBus._on('pagechanging', webViewerPageChanging);
  1327. eventBus._on('scalechanging', webViewerScaleChanging);
  1328. eventBus._on('rotationchanging', webViewerRotationChanging);
  1329. eventBus._on('sidebarviewchanged', webViewerSidebarViewChanged);
  1330. eventBus._on('pagemode', webViewerPageMode);
  1331. eventBus._on('namedaction', webViewerNamedAction);
  1332. eventBus._on('presentationmodechanged', webViewerPresentationModeChanged);
  1333. eventBus._on('presentationmode', webViewerPresentationMode);
  1334. eventBus._on('switchannotationeditormode', webViewerSwitchAnnotationEditorMode);
  1335. eventBus._on('switchannotationeditorparams', webViewerSwitchAnnotationEditorParams);
  1336. eventBus._on('print', webViewerPrint);
  1337. eventBus._on('download', webViewerDownload);
  1338. eventBus._on('openinexternalapp', webViewerOpenInExternalApp);
  1339. eventBus._on('firstpage', webViewerFirstPage);
  1340. eventBus._on('lastpage', webViewerLastPage);
  1341. eventBus._on('nextpage', webViewerNextPage);
  1342. eventBus._on('previouspage', webViewerPreviousPage);
  1343. eventBus._on('zoomin', webViewerZoomIn);
  1344. eventBus._on('zoomout', webViewerZoomOut);
  1345. eventBus._on('zoomreset', webViewerZoomReset);
  1346. eventBus._on('pagenumberchanged', webViewerPageNumberChanged);
  1347. eventBus._on('scalechanged', webViewerScaleChanged);
  1348. eventBus._on('rotatecw', webViewerRotateCw);
  1349. eventBus._on('rotateccw', webViewerRotateCcw);
  1350. eventBus._on('optionalcontentconfig', webViewerOptionalContentConfig);
  1351. eventBus._on('switchscrollmode', webViewerSwitchScrollMode);
  1352. eventBus._on('scrollmodechanged', webViewerScrollModeChanged);
  1353. eventBus._on('switchspreadmode', webViewerSwitchSpreadMode);
  1354. eventBus._on('spreadmodechanged', webViewerSpreadModeChanged);
  1355. eventBus._on('documentproperties', webViewerDocumentProperties);
  1356. eventBus._on('findfromurlhash', webViewerFindFromUrlHash);
  1357. eventBus._on('updatefindmatchescount', webViewerUpdateFindMatchesCount);
  1358. eventBus._on('updatefindcontrolstate', webViewerUpdateFindControlState);
  1359. if (_app_options.AppOptions.get('pdfBug')) {
  1360. _boundEvents.reportPageStatsPDFBug = reportPageStatsPDFBug;
  1361. eventBus._on('pagerendered', _boundEvents.reportPageStatsPDFBug);
  1362. eventBus._on('pagechanging', _boundEvents.reportPageStatsPDFBug);
  1363. }
  1364. eventBus._on('fileinputchange', webViewerFileInputChange);
  1365. eventBus._on('openfile', webViewerOpenFile);
  1366. },
  1367. bindWindowEvents() {
  1368. const { eventBus, _boundEvents } = this;
  1369. function addWindowResolutionChange(evt = null) {
  1370. if (evt) {
  1371. webViewerResolutionChange(evt);
  1372. }
  1373. const mediaQueryList = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`);
  1374. mediaQueryList.addEventListener('change', addWindowResolutionChange, {
  1375. once: true
  1376. });
  1377. _boundEvents.removeWindowResolutionChange ||= function () {
  1378. mediaQueryList.removeEventListener('change', addWindowResolutionChange);
  1379. _boundEvents.removeWindowResolutionChange = null;
  1380. };
  1381. }
  1382. addWindowResolutionChange();
  1383. _boundEvents.windowResize = () => {
  1384. eventBus.dispatch('resize', {
  1385. source: window
  1386. });
  1387. };
  1388. _boundEvents.windowHashChange = () => {
  1389. eventBus.dispatch('hashchange', {
  1390. source: window,
  1391. hash: document.location.hash.substring(1)
  1392. });
  1393. };
  1394. _boundEvents.windowBeforePrint = () => {
  1395. eventBus.dispatch('beforeprint', {
  1396. source: window
  1397. });
  1398. };
  1399. _boundEvents.windowAfterPrint = () => {
  1400. eventBus.dispatch('afterprint', {
  1401. source: window
  1402. });
  1403. };
  1404. _boundEvents.windowUpdateFromSandbox = (event) => {
  1405. eventBus.dispatch('updatefromsandbox', {
  1406. source: window,
  1407. detail: event.detail
  1408. });
  1409. };
  1410. window.addEventListener('visibilitychange', webViewerVisibilityChange);
  1411. window.addEventListener('wheel', webViewerWheel, {
  1412. passive: false
  1413. });
  1414. window.addEventListener('touchstart', webViewerTouchStart, {
  1415. passive: false
  1416. });
  1417. window.addEventListener('touchmove', webViewerTouchMove, {
  1418. passive: false
  1419. });
  1420. window.addEventListener('touchend', webViewerTouchEnd, {
  1421. passive: false
  1422. });
  1423. window.addEventListener('click', webViewerClick);
  1424. window.addEventListener('keydown', webViewerKeyDown);
  1425. window.addEventListener('keyup', webViewerKeyUp);
  1426. window.addEventListener('resize', _boundEvents.windowResize);
  1427. window.addEventListener('hashchange', _boundEvents.windowHashChange);
  1428. window.addEventListener('beforeprint', _boundEvents.windowBeforePrint);
  1429. window.addEventListener('afterprint', _boundEvents.windowAfterPrint);
  1430. window.addEventListener('updatefromsandbox', _boundEvents.windowUpdateFromSandbox);
  1431. },
  1432. unbindEvents() {
  1433. const { eventBus, _boundEvents } = this;
  1434. eventBus._off('resize', webViewerResize);
  1435. eventBus._off('hashchange', webViewerHashchange);
  1436. eventBus._off('beforeprint', _boundEvents.beforePrint);
  1437. eventBus._off('afterprint', _boundEvents.afterPrint);
  1438. eventBus._off('pagerender', webViewerPageRender);
  1439. eventBus._off('pagerendered', webViewerPageRendered);
  1440. eventBus._off('updateviewarea', webViewerUpdateViewarea);
  1441. eventBus._off('pagechanging', webViewerPageChanging);
  1442. eventBus._off('scalechanging', webViewerScaleChanging);
  1443. eventBus._off('rotationchanging', webViewerRotationChanging);
  1444. eventBus._off('sidebarviewchanged', webViewerSidebarViewChanged);
  1445. eventBus._off('pagemode', webViewerPageMode);
  1446. eventBus._off('namedaction', webViewerNamedAction);
  1447. eventBus._off('presentationmodechanged', webViewerPresentationModeChanged);
  1448. eventBus._off('presentationmode', webViewerPresentationMode);
  1449. eventBus._off('print', webViewerPrint);
  1450. eventBus._off('download', webViewerDownload);
  1451. eventBus._off('openinexternalapp', webViewerOpenInExternalApp);
  1452. eventBus._off('firstpage', webViewerFirstPage);
  1453. eventBus._off('lastpage', webViewerLastPage);
  1454. eventBus._off('nextpage', webViewerNextPage);
  1455. eventBus._off('previouspage', webViewerPreviousPage);
  1456. eventBus._off('zoomin', webViewerZoomIn);
  1457. eventBus._off('zoomout', webViewerZoomOut);
  1458. eventBus._off('zoomreset', webViewerZoomReset);
  1459. eventBus._off('pagenumberchanged', webViewerPageNumberChanged);
  1460. eventBus._off('scalechanged', webViewerScaleChanged);
  1461. eventBus._off('rotatecw', webViewerRotateCw);
  1462. eventBus._off('rotateccw', webViewerRotateCcw);
  1463. eventBus._off('optionalcontentconfig', webViewerOptionalContentConfig);
  1464. eventBus._off('switchscrollmode', webViewerSwitchScrollMode);
  1465. eventBus._off('scrollmodechanged', webViewerScrollModeChanged);
  1466. eventBus._off('switchspreadmode', webViewerSwitchSpreadMode);
  1467. eventBus._off('spreadmodechanged', webViewerSpreadModeChanged);
  1468. eventBus._off('documentproperties', webViewerDocumentProperties);
  1469. eventBus._off('findfromurlhash', webViewerFindFromUrlHash);
  1470. eventBus._off('updatefindmatchescount', webViewerUpdateFindMatchesCount);
  1471. eventBus._off('updatefindcontrolstate', webViewerUpdateFindControlState);
  1472. if (_boundEvents.reportPageStatsPDFBug) {
  1473. eventBus._off('pagerendered', _boundEvents.reportPageStatsPDFBug);
  1474. eventBus._off('pagechanging', _boundEvents.reportPageStatsPDFBug);
  1475. _boundEvents.reportPageStatsPDFBug = null;
  1476. }
  1477. eventBus._off('fileinputchange', webViewerFileInputChange);
  1478. eventBus._off('openfile', webViewerOpenFile);
  1479. _boundEvents.beforePrint = null;
  1480. _boundEvents.afterPrint = null;
  1481. },
  1482. unbindWindowEvents() {
  1483. const { _boundEvents } = this;
  1484. window.removeEventListener('visibilitychange', webViewerVisibilityChange);
  1485. window.removeEventListener('wheel', webViewerWheel, {
  1486. passive: false
  1487. });
  1488. window.removeEventListener('touchstart', webViewerTouchStart, {
  1489. passive: false
  1490. });
  1491. window.removeEventListener('touchmove', webViewerTouchMove, {
  1492. passive: false
  1493. });
  1494. window.removeEventListener('touchend', webViewerTouchEnd, {
  1495. passive: false
  1496. });
  1497. window.removeEventListener('click', webViewerClick);
  1498. window.removeEventListener('keydown', webViewerKeyDown);
  1499. window.removeEventListener('keyup', webViewerKeyUp);
  1500. window.removeEventListener('resize', _boundEvents.windowResize);
  1501. window.removeEventListener('hashchange', _boundEvents.windowHashChange);
  1502. window.removeEventListener('beforeprint', _boundEvents.windowBeforePrint);
  1503. window.removeEventListener('afterprint', _boundEvents.windowAfterPrint);
  1504. window.removeEventListener('updatefromsandbox', _boundEvents.windowUpdateFromSandbox);
  1505. _boundEvents.removeWindowResolutionChange?.();
  1506. _boundEvents.windowResize = null;
  1507. _boundEvents.windowHashChange = null;
  1508. _boundEvents.windowBeforePrint = null;
  1509. _boundEvents.windowAfterPrint = null;
  1510. _boundEvents.windowUpdateFromSandbox = null;
  1511. },
  1512. _accumulateTicks(ticks, prop) {
  1513. if ((this[prop] > 0 && ticks < 0) || (this[prop] < 0 && ticks > 0)) {
  1514. this[prop] = 0;
  1515. }
  1516. this[prop] += ticks;
  1517. const wholeTicks = Math.trunc(this[prop]);
  1518. this[prop] -= wholeTicks;
  1519. return wholeTicks;
  1520. },
  1521. _accumulateFactor(previousScale, factor, prop) {
  1522. if (factor === 1) {
  1523. return 1;
  1524. }
  1525. if ((this[prop] > 1 && factor < 1) || (this[prop] < 1 && factor > 1)) {
  1526. this[prop] = 1;
  1527. }
  1528. const newFactor = Math.floor(previousScale * factor * this[prop] * 100) / (100 * previousScale);
  1529. this[prop] = factor / newFactor;
  1530. return newFactor;
  1531. },
  1532. _centerAtPos(previousScale, x, y) {
  1533. const { pdfViewer } = this;
  1534. const scaleDiff = pdfViewer.currentScale / previousScale - 1;
  1535. if (scaleDiff !== 0) {
  1536. const [top, left] = pdfViewer.containerTopLeft;
  1537. pdfViewer.container.scrollLeft += (x - left) * scaleDiff;
  1538. pdfViewer.container.scrollTop += (y - top) * scaleDiff;
  1539. }
  1540. },
  1541. _unblockDocumentLoadEvent() {
  1542. document.blockUnblockOnload?.(false);
  1543. this._unblockDocumentLoadEvent = () => {};
  1544. },
  1545. get scriptingReady() {
  1546. return this.pdfScriptingManager.ready;
  1547. }
  1548. };
  1549. exports.PDFViewerApplication = PDFViewerApplication;
  1550. {
  1551. const HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];
  1552. var validateFileURL = function (file) {
  1553. if (!file) {
  1554. return;
  1555. }
  1556. try {
  1557. const viewerOrigin = new URL(window.location.href).origin || 'null';
  1558. if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) {
  1559. return;
  1560. }
  1561. const fileOrigin = new URL(file, window.location.href).origin;
  1562. if (fileOrigin !== viewerOrigin) {
  1563. throw new Error("file origin does not match viewer's");
  1564. }
  1565. } catch (ex) {
  1566. PDFViewerApplication.l10n.get('loading_error').then((msg) => {
  1567. PDFViewerApplication._documentError(msg, {
  1568. message: ex?.message
  1569. });
  1570. });
  1571. throw ex;
  1572. }
  1573. };
  1574. }
  1575. async function loadFakeWorker() {
  1576. _pdfjsLib.GlobalWorkerOptions.workerSrc ||= _app_options.AppOptions.get('workerSrc');
  1577. await (0, _pdfjsLib.loadScript)(_pdfjsLib.PDFWorker.workerSrc);
  1578. }
  1579. async function loadPDFBug(self) {
  1580. const { debuggerScriptPath } = self.appConfig;
  1581. const { PDFBug } = await import(debuggerScriptPath);
  1582. self._PDFBug = PDFBug;
  1583. }
  1584. function reportPageStatsPDFBug({ pageNumber }) {
  1585. if (!globalThis.Stats?.enabled) {
  1586. return;
  1587. }
  1588. const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1);
  1589. globalThis.Stats.add(pageNumber, pageView?.pdfPage?.stats);
  1590. }
  1591. function webViewerInitialized() {
  1592. const { appConfig, eventBus, l10n } = PDFViewerApplication;
  1593. let file;
  1594. const queryString = document.location.search.substring(1);
  1595. const params = (0, _ui_utils.parseQueryString)(queryString);
  1596. file = params.get('file') ?? _app_options.AppOptions.get('defaultUrl');
  1597. validateFileURL(file);
  1598. const fileInput = appConfig.openFileInput;
  1599. fileInput.value = null;
  1600. fileInput.addEventListener('change', function (evt) {
  1601. const { files } = evt.target;
  1602. if (!files || files.length === 0) {
  1603. return;
  1604. }
  1605. eventBus.dispatch('fileinputchange', {
  1606. source: this,
  1607. fileInput: evt.target
  1608. });
  1609. });
  1610. appConfig.mainContainer.addEventListener('dragover', function (evt) {
  1611. evt.preventDefault();
  1612. evt.dataTransfer.dropEffect = evt.dataTransfer.effectAllowed === 'copy' ? 'copy' : 'move';
  1613. });
  1614. appConfig.mainContainer.addEventListener('drop', function (evt) {
  1615. evt.preventDefault();
  1616. const { files } = evt.dataTransfer;
  1617. if (!files || files.length === 0) {
  1618. return;
  1619. }
  1620. eventBus.dispatch('fileinputchange', {
  1621. source: this,
  1622. fileInput: evt.dataTransfer
  1623. });
  1624. });
  1625. if (!PDFViewerApplication.supportsDocumentFonts) {
  1626. _app_options.AppOptions.set('disableFontFace', true);
  1627. l10n.get('web_fonts_disabled').then((msg) => {
  1628. console.warn(msg);
  1629. });
  1630. }
  1631. if (!PDFViewerApplication.supportsPrinting) {
  1632. appConfig.toolbar?.print?.classList.add('hidden');
  1633. appConfig.secondaryToolbar?.printButton.classList.add('hidden');
  1634. }
  1635. if (!PDFViewerApplication.supportsFullscreen) {
  1636. appConfig.secondaryToolbar?.presentationModeButton.classList.add('hidden');
  1637. }
  1638. if (PDFViewerApplication.supportsIntegratedFind) {
  1639. appConfig.toolbar?.viewFind?.classList.add('hidden');
  1640. }
  1641. appConfig.mainContainer.addEventListener(
  1642. 'transitionend',
  1643. function (evt) {
  1644. if (evt.target === this) {
  1645. eventBus.dispatch('resize', {
  1646. source: this
  1647. });
  1648. }
  1649. },
  1650. true
  1651. );
  1652. try {
  1653. if (file) {
  1654. PDFViewerApplication.open({
  1655. url: file
  1656. });
  1657. } else {
  1658. PDFViewerApplication._hideViewBookmark();
  1659. }
  1660. } catch (reason) {
  1661. l10n.get('loading_error').then((msg) => {
  1662. PDFViewerApplication._documentError(msg, reason);
  1663. });
  1664. }
  1665. }
  1666. function webViewerPageRender({ pageNumber }) {
  1667. if (pageNumber === PDFViewerApplication.page) {
  1668. PDFViewerApplication.toolbar?.updateLoadingIndicatorState(true);
  1669. }
  1670. }
  1671. function webViewerPageRendered({ pageNumber, error }) {
  1672. if (pageNumber === PDFViewerApplication.page) {
  1673. PDFViewerApplication.toolbar?.updateLoadingIndicatorState(false);
  1674. }
  1675. if (PDFViewerApplication.pdfSidebar?.visibleView === _ui_utils.SidebarView.THUMBS) {
  1676. const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1);
  1677. const thumbnailView = PDFViewerApplication.pdfThumbnailViewer?.getThumbnail(pageNumber - 1);
  1678. if (pageView) {
  1679. thumbnailView?.setImage(pageView);
  1680. }
  1681. }
  1682. if (error) {
  1683. PDFViewerApplication.l10n.get('rendering_error').then((msg) => {
  1684. PDFViewerApplication._otherError(msg, error);
  1685. });
  1686. }
  1687. }
  1688. function webViewerPageMode({ mode }) {
  1689. let view;
  1690. switch (mode) {
  1691. case 'thumbs':
  1692. view = _ui_utils.SidebarView.THUMBS;
  1693. break;
  1694. case 'bookmarks':
  1695. case 'outline':
  1696. view = _ui_utils.SidebarView.OUTLINE;
  1697. break;
  1698. case 'attachments':
  1699. view = _ui_utils.SidebarView.ATTACHMENTS;
  1700. break;
  1701. case 'layers':
  1702. view = _ui_utils.SidebarView.LAYERS;
  1703. break;
  1704. case 'none':
  1705. view = _ui_utils.SidebarView.NONE;
  1706. break;
  1707. default:
  1708. console.error('Invalid "pagemode" hash parameter: ' + mode);
  1709. return;
  1710. }
  1711. PDFViewerApplication.pdfSidebar?.switchView(view, true);
  1712. }
  1713. function webViewerNamedAction(evt) {
  1714. switch (evt.action) {
  1715. case 'GoToPage':
  1716. PDFViewerApplication.appConfig.toolbar?.pageNumber.select();
  1717. break;
  1718. case 'Find':
  1719. if (!PDFViewerApplication.supportsIntegratedFind) {
  1720. PDFViewerApplication?.findBar.toggle();
  1721. }
  1722. break;
  1723. case 'Print':
  1724. PDFViewerApplication.triggerPrinting();
  1725. break;
  1726. case 'SaveAs':
  1727. PDFViewerApplication.downloadOrSave();
  1728. break;
  1729. }
  1730. }
  1731. function webViewerPresentationModeChanged(evt) {
  1732. PDFViewerApplication.pdfViewer.presentationModeState = evt.state;
  1733. }
  1734. function webViewerSidebarViewChanged({ view }) {
  1735. PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = view === _ui_utils.SidebarView.THUMBS;
  1736. if (PDFViewerApplication.isInitialViewSet) {
  1737. PDFViewerApplication.store?.set('sidebarView', view).catch(() => {});
  1738. }
  1739. }
  1740. function webViewerUpdateViewarea({ location }) {
  1741. if (PDFViewerApplication.isInitialViewSet) {
  1742. PDFViewerApplication.store
  1743. ?.setMultiple({
  1744. page: location.pageNumber,
  1745. zoom: location.scale,
  1746. scrollLeft: location.left,
  1747. scrollTop: location.top,
  1748. rotation: location.rotation
  1749. })
  1750. .catch(() => {});
  1751. }
  1752. if (PDFViewerApplication.appConfig.secondaryToolbar) {
  1753. const href = PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
  1754. PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href;
  1755. }
  1756. }
  1757. function webViewerScrollModeChanged(evt) {
  1758. if (PDFViewerApplication.isInitialViewSet && !PDFViewerApplication.pdfViewer.isInPresentationMode) {
  1759. PDFViewerApplication.store?.set('scrollMode', evt.mode).catch(() => {});
  1760. }
  1761. }
  1762. function webViewerSpreadModeChanged(evt) {
  1763. if (PDFViewerApplication.isInitialViewSet && !PDFViewerApplication.pdfViewer.isInPresentationMode) {
  1764. PDFViewerApplication.store?.set('spreadMode', evt.mode).catch(() => {});
  1765. }
  1766. }
  1767. function webViewerResize() {
  1768. const { pdfDocument, pdfViewer, pdfRenderingQueue } = PDFViewerApplication;
  1769. if (pdfRenderingQueue.printing && window.matchMedia('print').matches) {
  1770. return;
  1771. }
  1772. if (!pdfDocument) {
  1773. return;
  1774. }
  1775. const currentScaleValue = pdfViewer.currentScaleValue;
  1776. if (currentScaleValue === 'auto' || currentScaleValue === 'page-fit' || currentScaleValue === 'page-width') {
  1777. pdfViewer.currentScaleValue = currentScaleValue;
  1778. }
  1779. pdfViewer.update();
  1780. }
  1781. function webViewerHashchange(evt) {
  1782. const hash = evt.hash;
  1783. if (!hash) {
  1784. return;
  1785. }
  1786. if (!PDFViewerApplication.isInitialViewSet) {
  1787. PDFViewerApplication.initialBookmark = hash;
  1788. } else if (!PDFViewerApplication.pdfHistory?.popStateInProgress) {
  1789. PDFViewerApplication.pdfLinkService.setHash(hash);
  1790. }
  1791. }
  1792. {
  1793. var webViewerFileInputChange = function (evt) {
  1794. if (PDFViewerApplication.pdfViewer?.isInPresentationMode) {
  1795. return;
  1796. }
  1797. const file = evt.fileInput.files[0];
  1798. PDFViewerApplication.open({
  1799. url: URL.createObjectURL(file),
  1800. originalUrl: file.name
  1801. });
  1802. };
  1803. var webViewerOpenFile = function (evt) {
  1804. const fileInput = PDFViewerApplication.appConfig.openFileInput;
  1805. fileInput.click();
  1806. };
  1807. }
  1808. function webViewerPresentationMode() {
  1809. PDFViewerApplication.requestPresentationMode();
  1810. }
  1811. function webViewerSwitchAnnotationEditorMode(evt) {
  1812. PDFViewerApplication.pdfViewer.annotationEditorMode = evt.mode;
  1813. }
  1814. function webViewerSwitchAnnotationEditorParams(evt) {
  1815. PDFViewerApplication.pdfViewer.annotationEditorParams = evt;
  1816. }
  1817. function webViewerPrint() {
  1818. PDFViewerApplication.triggerPrinting();
  1819. }
  1820. function webViewerDownload() {
  1821. PDFViewerApplication.downloadOrSave();
  1822. }
  1823. function webViewerOpenInExternalApp() {
  1824. PDFViewerApplication.openInExternalApp();
  1825. }
  1826. function webViewerFirstPage() {
  1827. PDFViewerApplication.page = 1;
  1828. }
  1829. function webViewerLastPage() {
  1830. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  1831. }
  1832. function webViewerNextPage() {
  1833. PDFViewerApplication.pdfViewer.nextPage();
  1834. }
  1835. function webViewerPreviousPage() {
  1836. PDFViewerApplication.pdfViewer.previousPage();
  1837. }
  1838. function webViewerZoomIn() {
  1839. PDFViewerApplication.zoomIn();
  1840. }
  1841. function webViewerZoomOut() {
  1842. PDFViewerApplication.zoomOut();
  1843. }
  1844. function webViewerZoomReset() {
  1845. PDFViewerApplication.zoomReset();
  1846. }
  1847. function webViewerPageNumberChanged(evt) {
  1848. const pdfViewer = PDFViewerApplication.pdfViewer;
  1849. if (evt.value !== '') {
  1850. PDFViewerApplication.pdfLinkService.goToPage(evt.value);
  1851. }
  1852. if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) {
  1853. PDFViewerApplication.toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  1854. }
  1855. }
  1856. function webViewerScaleChanged(evt) {
  1857. PDFViewerApplication.pdfViewer.currentScaleValue = evt.value;
  1858. }
  1859. function webViewerRotateCw() {
  1860. PDFViewerApplication.rotatePages(90);
  1861. }
  1862. function webViewerRotateCcw() {
  1863. PDFViewerApplication.rotatePages(-90);
  1864. }
  1865. function webViewerOptionalContentConfig(evt) {
  1866. PDFViewerApplication.pdfViewer.optionalContentConfigPromise = evt.promise;
  1867. }
  1868. function webViewerSwitchScrollMode(evt) {
  1869. PDFViewerApplication.pdfViewer.scrollMode = evt.mode;
  1870. }
  1871. function webViewerSwitchSpreadMode(evt) {
  1872. PDFViewerApplication.pdfViewer.spreadMode = evt.mode;
  1873. }
  1874. function webViewerDocumentProperties() {
  1875. PDFViewerApplication.pdfDocumentProperties?.open();
  1876. }
  1877. function webViewerFindFromUrlHash(evt) {
  1878. PDFViewerApplication.eventBus.dispatch('find', {
  1879. source: evt.source,
  1880. type: '',
  1881. query: evt.query,
  1882. caseSensitive: false,
  1883. entireWord: false,
  1884. highlightAll: true,
  1885. findPrevious: false,
  1886. matchDiacritics: true
  1887. });
  1888. }
  1889. function webViewerUpdateFindMatchesCount({ matchesCount }) {
  1890. if (PDFViewerApplication.supportsIntegratedFind) {
  1891. PDFViewerApplication.externalServices.updateFindMatchesCount(matchesCount);
  1892. } else {
  1893. PDFViewerApplication.findBar.updateResultsCount(matchesCount);
  1894. }
  1895. }
  1896. function webViewerUpdateFindControlState({ state, previous, matchesCount, rawQuery }) {
  1897. if (PDFViewerApplication.supportsIntegratedFind) {
  1898. PDFViewerApplication.externalServices.updateFindControlState({
  1899. result: state,
  1900. findPrevious: previous,
  1901. matchesCount,
  1902. rawQuery
  1903. });
  1904. } else {
  1905. PDFViewerApplication.findBar?.updateUIState(state, previous, matchesCount);
  1906. }
  1907. }
  1908. function webViewerScaleChanging(evt) {
  1909. PDFViewerApplication.toolbar?.setPageScale(evt.presetValue, evt.scale);
  1910. PDFViewerApplication.pdfViewer.update();
  1911. }
  1912. function webViewerRotationChanging(evt) {
  1913. if (PDFViewerApplication.pdfThumbnailViewer) {
  1914. PDFViewerApplication.pdfThumbnailViewer.pagesRotation = evt.pagesRotation;
  1915. }
  1916. PDFViewerApplication.forceRendering();
  1917. PDFViewerApplication.pdfViewer.currentPageNumber = evt.pageNumber;
  1918. }
  1919. function webViewerPageChanging({ pageNumber, pageLabel }) {
  1920. PDFViewerApplication.toolbar?.setPageNumber(pageNumber, pageLabel);
  1921. PDFViewerApplication.secondaryToolbar?.setPageNumber(pageNumber);
  1922. if (PDFViewerApplication.pdfSidebar?.visibleView === _ui_utils.SidebarView.THUMBS) {
  1923. PDFViewerApplication.pdfThumbnailViewer?.scrollThumbnailIntoView(pageNumber);
  1924. }
  1925. const currentPage = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1);
  1926. PDFViewerApplication.toolbar?.updateLoadingIndicatorState(currentPage?.renderingState === _ui_utils.RenderingStates.RUNNING);
  1927. }
  1928. function webViewerResolutionChange(evt) {
  1929. PDFViewerApplication.pdfViewer.refresh();
  1930. }
  1931. function webViewerVisibilityChange(evt) {
  1932. if (document.visibilityState === 'visible') {
  1933. setZoomDisabledTimeout();
  1934. }
  1935. }
  1936. let zoomDisabledTimeout = null;
  1937. function setZoomDisabledTimeout() {
  1938. if (zoomDisabledTimeout) {
  1939. clearTimeout(zoomDisabledTimeout);
  1940. }
  1941. zoomDisabledTimeout = setTimeout(function () {
  1942. zoomDisabledTimeout = null;
  1943. }, WHEEL_ZOOM_DISABLED_TIMEOUT);
  1944. }
  1945. function webViewerWheel(evt) {
  1946. const { pdfViewer, supportedMouseWheelZoomModifierKeys, supportsPinchToZoom } = PDFViewerApplication;
  1947. if (pdfViewer.isInPresentationMode) {
  1948. return;
  1949. }
  1950. const deltaMode = evt.deltaMode;
  1951. let scaleFactor = Math.exp(-evt.deltaY / 100);
  1952. const isBuiltInMac = false;
  1953. const isPinchToZoom =
  1954. evt.ctrlKey &&
  1955. !PDFViewerApplication._isCtrlKeyDown &&
  1956. deltaMode === WheelEvent.DOM_DELTA_PIXEL &&
  1957. evt.deltaX === 0 &&
  1958. (Math.abs(scaleFactor - 1) < 0.05 || isBuiltInMac) &&
  1959. evt.deltaZ === 0;
  1960. if (
  1961. isPinchToZoom ||
  1962. (evt.ctrlKey && supportedMouseWheelZoomModifierKeys.ctrlKey) ||
  1963. (evt.metaKey && supportedMouseWheelZoomModifierKeys.metaKey)
  1964. ) {
  1965. evt.preventDefault();
  1966. if (zoomDisabledTimeout || document.visibilityState === 'hidden') {
  1967. return;
  1968. }
  1969. const previousScale = pdfViewer.currentScale;
  1970. if (isPinchToZoom && supportsPinchToZoom) {
  1971. scaleFactor = PDFViewerApplication._accumulateFactor(previousScale, scaleFactor, '_wheelUnusedFactor');
  1972. if (scaleFactor < 1) {
  1973. PDFViewerApplication.zoomOut(null, scaleFactor);
  1974. } else if (scaleFactor > 1) {
  1975. PDFViewerApplication.zoomIn(null, scaleFactor);
  1976. } else {
  1977. return;
  1978. }
  1979. } else {
  1980. const delta = (0, _ui_utils.normalizeWheelEventDirection)(evt);
  1981. let ticks = 0;
  1982. if (deltaMode === WheelEvent.DOM_DELTA_LINE || deltaMode === WheelEvent.DOM_DELTA_PAGE) {
  1983. if (Math.abs(delta) >= 1) {
  1984. ticks = Math.sign(delta);
  1985. } else {
  1986. ticks = PDFViewerApplication._accumulateTicks(delta, '_wheelUnusedTicks');
  1987. }
  1988. } else {
  1989. const PIXELS_PER_LINE_SCALE = 30;
  1990. ticks = PDFViewerApplication._accumulateTicks(delta / PIXELS_PER_LINE_SCALE, '_wheelUnusedTicks');
  1991. }
  1992. if (ticks < 0) {
  1993. PDFViewerApplication.zoomOut(-ticks);
  1994. } else if (ticks > 0) {
  1995. PDFViewerApplication.zoomIn(ticks);
  1996. } else {
  1997. return;
  1998. }
  1999. }
  2000. PDFViewerApplication._centerAtPos(previousScale, evt.clientX, evt.clientY);
  2001. } else {
  2002. setZoomDisabledTimeout();
  2003. }
  2004. }
  2005. function webViewerTouchStart(evt) {
  2006. if (PDFViewerApplication.pdfViewer.isInPresentationMode || evt.touches.length < 2) {
  2007. return;
  2008. }
  2009. evt.preventDefault();
  2010. if (evt.touches.length !== 2) {
  2011. PDFViewerApplication._touchInfo = null;
  2012. return;
  2013. }
  2014. let [touch0, touch1] = evt.touches;
  2015. if (touch0.identifier > touch1.identifier) {
  2016. [touch0, touch1] = [touch1, touch0];
  2017. }
  2018. PDFViewerApplication._touchInfo = {
  2019. touch0X: touch0.pageX,
  2020. touch0Y: touch0.pageY,
  2021. touch1X: touch1.pageX,
  2022. touch1Y: touch1.pageY
  2023. };
  2024. }
  2025. function webViewerTouchMove(evt) {
  2026. if (!PDFViewerApplication._touchInfo || evt.touches.length !== 2) {
  2027. return;
  2028. }
  2029. const { pdfViewer, _touchInfo, supportsPinchToZoom } = PDFViewerApplication;
  2030. let [touch0, touch1] = evt.touches;
  2031. if (touch0.identifier > touch1.identifier) {
  2032. [touch0, touch1] = [touch1, touch0];
  2033. }
  2034. const { pageX: page0X, pageY: page0Y } = touch0;
  2035. const { pageX: page1X, pageY: page1Y } = touch1;
  2036. const { touch0X: pTouch0X, touch0Y: pTouch0Y, touch1X: pTouch1X, touch1Y: pTouch1Y } = _touchInfo;
  2037. if (
  2038. Math.abs(pTouch0X - page0X) <= 1 &&
  2039. Math.abs(pTouch0Y - page0Y) <= 1 &&
  2040. Math.abs(pTouch1X - page1X) <= 1 &&
  2041. Math.abs(pTouch1Y - page1Y) <= 1
  2042. ) {
  2043. return;
  2044. }
  2045. _touchInfo.touch0X = page0X;
  2046. _touchInfo.touch0Y = page0Y;
  2047. _touchInfo.touch1X = page1X;
  2048. _touchInfo.touch1Y = page1Y;
  2049. if (pTouch0X === page0X && pTouch0Y === page0Y) {
  2050. const v1X = pTouch1X - page0X;
  2051. const v1Y = pTouch1Y - page0Y;
  2052. const v2X = page1X - page0X;
  2053. const v2Y = page1Y - page0Y;
  2054. const det = v1X * v2Y - v1Y * v2X;
  2055. if (Math.abs(det) > 0.02 * Math.hypot(v1X, v1Y) * Math.hypot(v2X, v2Y)) {
  2056. return;
  2057. }
  2058. } else if (pTouch1X === page1X && pTouch1Y === page1Y) {
  2059. const v1X = pTouch0X - page1X;
  2060. const v1Y = pTouch0Y - page1Y;
  2061. const v2X = page0X - page1X;
  2062. const v2Y = page0Y - page1Y;
  2063. const det = v1X * v2Y - v1Y * v2X;
  2064. if (Math.abs(det) > 0.02 * Math.hypot(v1X, v1Y) * Math.hypot(v2X, v2Y)) {
  2065. return;
  2066. }
  2067. } else {
  2068. const diff0X = page0X - pTouch0X;
  2069. const diff1X = page1X - pTouch1X;
  2070. const diff0Y = page0Y - pTouch0Y;
  2071. const diff1Y = page1Y - pTouch1Y;
  2072. const dotProduct = diff0X * diff1X + diff0Y * diff1Y;
  2073. if (dotProduct >= 0) {
  2074. return;
  2075. }
  2076. }
  2077. evt.preventDefault();
  2078. const distance = Math.hypot(page0X - page1X, page0Y - page1Y) || 1;
  2079. const pDistance = Math.hypot(pTouch0X - pTouch1X, pTouch0Y - pTouch1Y) || 1;
  2080. const previousScale = pdfViewer.currentScale;
  2081. if (supportsPinchToZoom) {
  2082. const newScaleFactor = PDFViewerApplication._accumulateFactor(previousScale, distance / pDistance, '_touchUnusedFactor');
  2083. if (newScaleFactor < 1) {
  2084. PDFViewerApplication.zoomOut(null, newScaleFactor);
  2085. } else if (newScaleFactor > 1) {
  2086. PDFViewerApplication.zoomIn(null, newScaleFactor);
  2087. } else {
  2088. return;
  2089. }
  2090. } else {
  2091. const PIXELS_PER_LINE_SCALE = 30;
  2092. const ticks = PDFViewerApplication._accumulateTicks((distance - pDistance) / PIXELS_PER_LINE_SCALE, '_touchUnusedTicks');
  2093. if (ticks < 0) {
  2094. PDFViewerApplication.zoomOut(-ticks);
  2095. } else if (ticks > 0) {
  2096. PDFViewerApplication.zoomIn(ticks);
  2097. } else {
  2098. return;
  2099. }
  2100. }
  2101. PDFViewerApplication._centerAtPos(previousScale, (page0X + page1X) / 2, (page0Y + page1Y) / 2);
  2102. }
  2103. function webViewerTouchEnd(evt) {
  2104. if (!PDFViewerApplication._touchInfo) {
  2105. return;
  2106. }
  2107. evt.preventDefault();
  2108. PDFViewerApplication._touchInfo = null;
  2109. PDFViewerApplication._touchUnusedTicks = 0;
  2110. PDFViewerApplication._touchUnusedFactor = 1;
  2111. }
  2112. function webViewerClick(evt) {
  2113. if (!PDFViewerApplication.secondaryToolbar?.isOpen) {
  2114. return;
  2115. }
  2116. const appConfig = PDFViewerApplication.appConfig;
  2117. if (
  2118. PDFViewerApplication.pdfViewer.containsElement(evt.target) ||
  2119. (appConfig.toolbar?.container.contains(evt.target) && evt.target !== appConfig.secondaryToolbar?.toggleButton)
  2120. ) {
  2121. PDFViewerApplication.secondaryToolbar.close();
  2122. }
  2123. }
  2124. function webViewerKeyUp(evt) {
  2125. if (evt.key === 'Control') {
  2126. PDFViewerApplication._isCtrlKeyDown = false;
  2127. }
  2128. }
  2129. function webViewerKeyDown(evt) {
  2130. PDFViewerApplication._isCtrlKeyDown = evt.key === 'Control';
  2131. if (PDFViewerApplication.overlayManager.active) {
  2132. return;
  2133. }
  2134. const { eventBus, pdfViewer } = PDFViewerApplication;
  2135. const isViewerInPresentationMode = pdfViewer.isInPresentationMode;
  2136. let handled = false,
  2137. ensureViewerFocused = false;
  2138. const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0);
  2139. if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
  2140. switch (evt.keyCode) {
  2141. case 70:
  2142. if (!PDFViewerApplication.supportsIntegratedFind && !evt.shiftKey) {
  2143. PDFViewerApplication.findBar?.open();
  2144. handled = true;
  2145. }
  2146. break;
  2147. case 71:
  2148. if (!PDFViewerApplication.supportsIntegratedFind) {
  2149. const { state } = PDFViewerApplication.findController;
  2150. if (state) {
  2151. const newState = {
  2152. source: window,
  2153. type: 'again',
  2154. findPrevious: cmd === 5 || cmd === 12
  2155. };
  2156. eventBus.dispatch('find', {
  2157. ...state,
  2158. ...newState
  2159. });
  2160. }
  2161. handled = true;
  2162. }
  2163. break;
  2164. case 61:
  2165. case 107:
  2166. case 187:
  2167. case 171:
  2168. PDFViewerApplication.zoomIn();
  2169. handled = true;
  2170. break;
  2171. case 173:
  2172. case 109:
  2173. case 189:
  2174. PDFViewerApplication.zoomOut();
  2175. handled = true;
  2176. break;
  2177. case 48:
  2178. case 96:
  2179. if (!isViewerInPresentationMode) {
  2180. setTimeout(function () {
  2181. PDFViewerApplication.zoomReset();
  2182. });
  2183. handled = false;
  2184. }
  2185. break;
  2186. case 38:
  2187. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  2188. PDFViewerApplication.page = 1;
  2189. handled = true;
  2190. ensureViewerFocused = true;
  2191. }
  2192. break;
  2193. case 40:
  2194. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  2195. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  2196. handled = true;
  2197. ensureViewerFocused = true;
  2198. }
  2199. break;
  2200. }
  2201. }
  2202. if (cmd === 1 || cmd === 8) {
  2203. switch (evt.keyCode) {
  2204. case 83:
  2205. eventBus.dispatch('download', {
  2206. source: window
  2207. });
  2208. handled = true;
  2209. break;
  2210. case 79:
  2211. {
  2212. eventBus.dispatch('openfile', {
  2213. source: window
  2214. });
  2215. handled = true;
  2216. }
  2217. break;
  2218. }
  2219. }
  2220. if (cmd === 3 || cmd === 10) {
  2221. switch (evt.keyCode) {
  2222. case 80:
  2223. PDFViewerApplication.requestPresentationMode();
  2224. handled = true;
  2225. PDFViewerApplication.externalServices.reportTelemetry({
  2226. type: 'buttons',
  2227. data: {
  2228. id: 'presentationModeKeyboard'
  2229. }
  2230. });
  2231. break;
  2232. case 71:
  2233. if (PDFViewerApplication.appConfig.toolbar) {
  2234. PDFViewerApplication.appConfig.toolbar.pageNumber.select();
  2235. handled = true;
  2236. }
  2237. break;
  2238. }
  2239. }
  2240. if (handled) {
  2241. if (ensureViewerFocused && !isViewerInPresentationMode) {
  2242. pdfViewer.focus();
  2243. }
  2244. evt.preventDefault();
  2245. return;
  2246. }
  2247. const curElement = (0, _ui_utils.getActiveOrFocusedElement)();
  2248. const curElementTagName = curElement?.tagName.toUpperCase();
  2249. if (curElementTagName === 'INPUT' || curElementTagName === 'TEXTAREA' || curElementTagName === 'SELECT' || curElement?.isContentEditable) {
  2250. if (evt.keyCode !== 27) {
  2251. return;
  2252. }
  2253. }
  2254. if (cmd === 0) {
  2255. let turnPage = 0,
  2256. turnOnlyIfPageFit = false;
  2257. switch (evt.keyCode) {
  2258. case 38:
  2259. case 33:
  2260. if (pdfViewer.isVerticalScrollbarEnabled) {
  2261. turnOnlyIfPageFit = true;
  2262. }
  2263. turnPage = -1;
  2264. break;
  2265. case 8:
  2266. if (!isViewerInPresentationMode) {
  2267. turnOnlyIfPageFit = true;
  2268. }
  2269. turnPage = -1;
  2270. break;
  2271. case 37:
  2272. if (pdfViewer.isHorizontalScrollbarEnabled) {
  2273. turnOnlyIfPageFit = true;
  2274. }
  2275. case 75:
  2276. case 80:
  2277. turnPage = -1;
  2278. break;
  2279. case 27:
  2280. if (PDFViewerApplication.secondaryToolbar?.isOpen) {
  2281. PDFViewerApplication.secondaryToolbar.close();
  2282. handled = true;
  2283. }
  2284. if (!PDFViewerApplication.supportsIntegratedFind && PDFViewerApplication.findBar?.opened) {
  2285. PDFViewerApplication.findBar.close();
  2286. handled = true;
  2287. }
  2288. break;
  2289. case 40:
  2290. case 34:
  2291. if (pdfViewer.isVerticalScrollbarEnabled) {
  2292. turnOnlyIfPageFit = true;
  2293. }
  2294. turnPage = 1;
  2295. break;
  2296. case 13:
  2297. case 32:
  2298. if (!isViewerInPresentationMode) {
  2299. turnOnlyIfPageFit = true;
  2300. }
  2301. turnPage = 1;
  2302. break;
  2303. case 39:
  2304. if (pdfViewer.isHorizontalScrollbarEnabled) {
  2305. turnOnlyIfPageFit = true;
  2306. }
  2307. case 74:
  2308. case 78:
  2309. turnPage = 1;
  2310. break;
  2311. case 36:
  2312. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  2313. PDFViewerApplication.page = 1;
  2314. handled = true;
  2315. ensureViewerFocused = true;
  2316. }
  2317. break;
  2318. case 35:
  2319. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  2320. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  2321. handled = true;
  2322. ensureViewerFocused = true;
  2323. }
  2324. break;
  2325. case 83:
  2326. PDFViewerApplication.pdfCursorTools?.switchTool(_ui_utils.CursorTool.SELECT);
  2327. break;
  2328. case 72:
  2329. PDFViewerApplication.pdfCursorTools?.switchTool(_ui_utils.CursorTool.HAND);
  2330. break;
  2331. case 82:
  2332. PDFViewerApplication.rotatePages(90);
  2333. break;
  2334. case 115:
  2335. PDFViewerApplication.pdfSidebar?.toggle();
  2336. break;
  2337. }
  2338. if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === 'page-fit')) {
  2339. if (turnPage > 0) {
  2340. pdfViewer.nextPage();
  2341. } else {
  2342. pdfViewer.previousPage();
  2343. }
  2344. handled = true;
  2345. }
  2346. }
  2347. if (cmd === 4) {
  2348. switch (evt.keyCode) {
  2349. case 13:
  2350. case 32:
  2351. if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== 'page-fit') {
  2352. break;
  2353. }
  2354. pdfViewer.previousPage();
  2355. handled = true;
  2356. break;
  2357. case 82:
  2358. PDFViewerApplication.rotatePages(-90);
  2359. break;
  2360. }
  2361. }
  2362. if (!handled && !isViewerInPresentationMode) {
  2363. if ((evt.keyCode >= 33 && evt.keyCode <= 40) || (evt.keyCode === 32 && curElementTagName !== 'BUTTON')) {
  2364. ensureViewerFocused = true;
  2365. }
  2366. }
  2367. if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) {
  2368. pdfViewer.focus();
  2369. }
  2370. if (handled) {
  2371. evt.preventDefault();
  2372. }
  2373. }
  2374. function beforeUnload(evt) {
  2375. evt.preventDefault();
  2376. evt.returnValue = '';
  2377. return false;
  2378. }
  2379. function webViewerAnnotationEditorStatesChanged(data) {
  2380. PDFViewerApplication.externalServices.updateEditorStates(data);
  2381. }
  2382. const PDFPrintServiceFactory = {
  2383. instance: {
  2384. supportsPrinting: false,
  2385. createPrintService() {
  2386. throw new Error('Not implemented: createPrintService');
  2387. }
  2388. }
  2389. };
  2390. exports.PDFPrintServiceFactory = PDFPrintServiceFactory;
  2391. /***/
  2392. },
  2393. /* 3 */
  2394. /***/ (__unused_webpack_module, exports) => {
  2395. Object.defineProperty(exports, '__esModule', {
  2396. value: true
  2397. });
  2398. exports.animationStarted =
  2399. exports.VERTICAL_PADDING =
  2400. exports.UNKNOWN_SCALE =
  2401. exports.TextLayerMode =
  2402. exports.SpreadMode =
  2403. exports.SidebarView =
  2404. exports.ScrollMode =
  2405. exports.SCROLLBAR_PADDING =
  2406. exports.RenderingStates =
  2407. exports.ProgressBar =
  2408. exports.PresentationModeState =
  2409. exports.OutputScale =
  2410. exports.MIN_SCALE =
  2411. exports.MAX_SCALE =
  2412. exports.MAX_AUTO_SCALE =
  2413. exports.DEFAULT_SCALE_VALUE =
  2414. exports.DEFAULT_SCALE_DELTA =
  2415. exports.DEFAULT_SCALE =
  2416. exports.CursorTool =
  2417. exports.AutoPrintRegExp =
  2418. void 0;
  2419. exports.apiPageLayoutToViewerModes = apiPageLayoutToViewerModes;
  2420. exports.apiPageModeToSidebarView = apiPageModeToSidebarView;
  2421. exports.approximateFraction = approximateFraction;
  2422. exports.backtrackBeforeAllVisibleElements = backtrackBeforeAllVisibleElements;
  2423. exports.binarySearchFirstItem = binarySearchFirstItem;
  2424. exports.docStyle = void 0;
  2425. exports.getActiveOrFocusedElement = getActiveOrFocusedElement;
  2426. exports.getPageSizeInches = getPageSizeInches;
  2427. exports.getVisibleElements = getVisibleElements;
  2428. exports.isPortraitOrientation = isPortraitOrientation;
  2429. exports.isValidRotation = isValidRotation;
  2430. exports.isValidScrollMode = isValidScrollMode;
  2431. exports.isValidSpreadMode = isValidSpreadMode;
  2432. exports.noContextMenuHandler = noContextMenuHandler;
  2433. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  2434. exports.normalizeWheelEventDirection = normalizeWheelEventDirection;
  2435. exports.parseQueryString = parseQueryString;
  2436. exports.removeNullCharacters = removeNullCharacters;
  2437. exports.roundToDivide = roundToDivide;
  2438. exports.scrollIntoView = scrollIntoView;
  2439. exports.toggleCheckedBtn = toggleCheckedBtn;
  2440. exports.toggleExpandedBtn = toggleExpandedBtn;
  2441. exports.watchScroll = watchScroll;
  2442. const DEFAULT_SCALE_VALUE = 'auto';
  2443. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  2444. const DEFAULT_SCALE = 1.0;
  2445. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  2446. const DEFAULT_SCALE_DELTA = 1.1;
  2447. exports.DEFAULT_SCALE_DELTA = DEFAULT_SCALE_DELTA;
  2448. const MIN_SCALE = 0.1;
  2449. exports.MIN_SCALE = MIN_SCALE;
  2450. const MAX_SCALE = 10.0;
  2451. exports.MAX_SCALE = MAX_SCALE;
  2452. const UNKNOWN_SCALE = 0;
  2453. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  2454. const MAX_AUTO_SCALE = 1.25;
  2455. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  2456. const SCROLLBAR_PADDING = 40;
  2457. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  2458. const VERTICAL_PADDING = 5;
  2459. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  2460. const RenderingStates = {
  2461. INITIAL: 0,
  2462. RUNNING: 1,
  2463. PAUSED: 2,
  2464. FINISHED: 3
  2465. };
  2466. exports.RenderingStates = RenderingStates;
  2467. const PresentationModeState = {
  2468. UNKNOWN: 0,
  2469. NORMAL: 1,
  2470. CHANGING: 2,
  2471. FULLSCREEN: 3
  2472. };
  2473. exports.PresentationModeState = PresentationModeState;
  2474. const SidebarView = {
  2475. UNKNOWN: -1,
  2476. NONE: 0,
  2477. THUMBS: 1,
  2478. OUTLINE: 2,
  2479. ATTACHMENTS: 3,
  2480. LAYERS: 4
  2481. };
  2482. exports.SidebarView = SidebarView;
  2483. const TextLayerMode = {
  2484. DISABLE: 0,
  2485. ENABLE: 1,
  2486. ENABLE_PERMISSIONS: 2
  2487. };
  2488. exports.TextLayerMode = TextLayerMode;
  2489. const ScrollMode = {
  2490. UNKNOWN: -1,
  2491. VERTICAL: 0,
  2492. HORIZONTAL: 1,
  2493. WRAPPED: 2,
  2494. PAGE: 3
  2495. };
  2496. exports.ScrollMode = ScrollMode;
  2497. const SpreadMode = {
  2498. UNKNOWN: -1,
  2499. NONE: 0,
  2500. ODD: 1,
  2501. EVEN: 2
  2502. };
  2503. exports.SpreadMode = SpreadMode;
  2504. const CursorTool = {
  2505. SELECT: 0,
  2506. HAND: 1,
  2507. ZOOM: 2
  2508. };
  2509. exports.CursorTool = CursorTool;
  2510. const AutoPrintRegExp = /\bprint\s*\(/;
  2511. exports.AutoPrintRegExp = AutoPrintRegExp;
  2512. class OutputScale {
  2513. constructor() {
  2514. const pixelRatio = window.devicePixelRatio || 1;
  2515. this.sx = pixelRatio;
  2516. this.sy = pixelRatio;
  2517. }
  2518. get scaled() {
  2519. return this.sx !== 1 || this.sy !== 1;
  2520. }
  2521. }
  2522. exports.OutputScale = OutputScale;
  2523. function scrollIntoView(element, spot, scrollMatches = false) {
  2524. let parent = element.offsetParent;
  2525. if (!parent) {
  2526. console.error('offsetParent is not set -- cannot scroll');
  2527. return;
  2528. }
  2529. let offsetY = element.offsetTop + element.clientTop;
  2530. let offsetX = element.offsetLeft + element.clientLeft;
  2531. while (
  2532. (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth) ||
  2533. (scrollMatches && (parent.classList.contains('markedContent') || getComputedStyle(parent).overflow === 'hidden'))
  2534. ) {
  2535. offsetY += parent.offsetTop;
  2536. offsetX += parent.offsetLeft;
  2537. parent = parent.offsetParent;
  2538. if (!parent) {
  2539. return;
  2540. }
  2541. }
  2542. if (spot) {
  2543. if (spot.top !== undefined) {
  2544. offsetY += spot.top;
  2545. }
  2546. if (spot.left !== undefined) {
  2547. offsetX += spot.left;
  2548. parent.scrollLeft = offsetX;
  2549. }
  2550. }
  2551. parent.scrollTop = offsetY;
  2552. }
  2553. function watchScroll(viewAreaElement, callback) {
  2554. const debounceScroll = function (evt) {
  2555. if (rAF) {
  2556. return;
  2557. }
  2558. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  2559. rAF = null;
  2560. const currentX = viewAreaElement.scrollLeft;
  2561. const lastX = state.lastX;
  2562. if (currentX !== lastX) {
  2563. state.right = currentX > lastX;
  2564. }
  2565. state.lastX = currentX;
  2566. const currentY = viewAreaElement.scrollTop;
  2567. const lastY = state.lastY;
  2568. if (currentY !== lastY) {
  2569. state.down = currentY > lastY;
  2570. }
  2571. state.lastY = currentY;
  2572. callback(state);
  2573. });
  2574. };
  2575. const state = {
  2576. right: true,
  2577. down: true,
  2578. lastX: viewAreaElement.scrollLeft,
  2579. lastY: viewAreaElement.scrollTop,
  2580. _eventHandler: debounceScroll
  2581. };
  2582. let rAF = null;
  2583. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  2584. return state;
  2585. }
  2586. function parseQueryString(query) {
  2587. const params = new Map();
  2588. for (const [key, value] of new URLSearchParams(query)) {
  2589. params.set(key.toLowerCase(), value);
  2590. }
  2591. return params;
  2592. }
  2593. const InvisibleCharactersRegExp = /[\x01-\x1F]/g;
  2594. function removeNullCharacters(str, replaceInvisible = false) {
  2595. if (typeof str !== 'string') {
  2596. console.error(`The argument must be a string.`);
  2597. return str;
  2598. }
  2599. if (replaceInvisible) {
  2600. str = str.replaceAll(InvisibleCharactersRegExp, ' ');
  2601. }
  2602. return str.replaceAll('\x00', '');
  2603. }
  2604. function binarySearchFirstItem(items, condition, start = 0) {
  2605. let minIndex = start;
  2606. let maxIndex = items.length - 1;
  2607. if (maxIndex < 0 || !condition(items[maxIndex])) {
  2608. return items.length;
  2609. }
  2610. if (condition(items[minIndex])) {
  2611. return minIndex;
  2612. }
  2613. while (minIndex < maxIndex) {
  2614. const currentIndex = (minIndex + maxIndex) >> 1;
  2615. const currentItem = items[currentIndex];
  2616. if (condition(currentItem)) {
  2617. maxIndex = currentIndex;
  2618. } else {
  2619. minIndex = currentIndex + 1;
  2620. }
  2621. }
  2622. return minIndex;
  2623. }
  2624. function approximateFraction(x) {
  2625. if (Math.floor(x) === x) {
  2626. return [x, 1];
  2627. }
  2628. const xinv = 1 / x;
  2629. const limit = 8;
  2630. if (xinv > limit) {
  2631. return [1, limit];
  2632. } else if (Math.floor(xinv) === xinv) {
  2633. return [1, xinv];
  2634. }
  2635. const x_ = x > 1 ? xinv : x;
  2636. let a = 0,
  2637. b = 1,
  2638. c = 1,
  2639. d = 1;
  2640. while (true) {
  2641. const p = a + c,
  2642. q = b + d;
  2643. if (q > limit) {
  2644. break;
  2645. }
  2646. if (x_ <= p / q) {
  2647. c = p;
  2648. d = q;
  2649. } else {
  2650. a = p;
  2651. b = q;
  2652. }
  2653. }
  2654. let result;
  2655. if (x_ - a / b < c / d - x_) {
  2656. result = x_ === x ? [a, b] : [b, a];
  2657. } else {
  2658. result = x_ === x ? [c, d] : [d, c];
  2659. }
  2660. return result;
  2661. }
  2662. function roundToDivide(x, div) {
  2663. const r = x % div;
  2664. return r === 0 ? x : Math.round(x - r + div);
  2665. }
  2666. function getPageSizeInches({ view, userUnit, rotate }) {
  2667. const [x1, y1, x2, y2] = view;
  2668. const changeOrientation = rotate % 180 !== 0;
  2669. const width = ((x2 - x1) / 72) * userUnit;
  2670. const height = ((y2 - y1) / 72) * userUnit;
  2671. return {
  2672. width: changeOrientation ? height : width,
  2673. height: changeOrientation ? width : height
  2674. };
  2675. }
  2676. function backtrackBeforeAllVisibleElements(index, views, top) {
  2677. if (index < 2) {
  2678. return index;
  2679. }
  2680. let elt = views[index].div;
  2681. let pageTop = elt.offsetTop + elt.clientTop;
  2682. if (pageTop >= top) {
  2683. elt = views[index - 1].div;
  2684. pageTop = elt.offsetTop + elt.clientTop;
  2685. }
  2686. for (let i = index - 2; i >= 0; --i) {
  2687. elt = views[i].div;
  2688. if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) {
  2689. break;
  2690. }
  2691. index = i;
  2692. }
  2693. return index;
  2694. }
  2695. function getVisibleElements({ scrollEl, views, sortByVisibility = false, horizontal = false, rtl = false }) {
  2696. const top = scrollEl.scrollTop,
  2697. bottom = top + scrollEl.clientHeight;
  2698. const left = scrollEl.scrollLeft,
  2699. right = left + scrollEl.clientWidth;
  2700. function isElementBottomAfterViewTop(view) {
  2701. const element = view.div;
  2702. const elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  2703. return elementBottom > top;
  2704. }
  2705. function isElementNextAfterViewHorizontally(view) {
  2706. const element = view.div;
  2707. const elementLeft = element.offsetLeft + element.clientLeft;
  2708. const elementRight = elementLeft + element.clientWidth;
  2709. return rtl ? elementLeft < right : elementRight > left;
  2710. }
  2711. const visible = [],
  2712. ids = new Set(),
  2713. numViews = views.length;
  2714. let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop);
  2715. if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) {
  2716. firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top);
  2717. }
  2718. let lastEdge = horizontal ? right : -1;
  2719. for (let i = firstVisibleElementInd; i < numViews; i++) {
  2720. const view = views[i],
  2721. element = view.div;
  2722. const currentWidth = element.offsetLeft + element.clientLeft;
  2723. const currentHeight = element.offsetTop + element.clientTop;
  2724. const viewWidth = element.clientWidth,
  2725. viewHeight = element.clientHeight;
  2726. const viewRight = currentWidth + viewWidth;
  2727. const viewBottom = currentHeight + viewHeight;
  2728. if (lastEdge === -1) {
  2729. if (viewBottom >= bottom) {
  2730. lastEdge = viewBottom;
  2731. }
  2732. } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) {
  2733. break;
  2734. }
  2735. if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) {
  2736. continue;
  2737. }
  2738. const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom);
  2739. const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right);
  2740. const fractionHeight = (viewHeight - hiddenHeight) / viewHeight,
  2741. fractionWidth = (viewWidth - hiddenWidth) / viewWidth;
  2742. const percent = (fractionHeight * fractionWidth * 100) | 0;
  2743. visible.push({
  2744. id: view.id,
  2745. x: currentWidth,
  2746. y: currentHeight,
  2747. view,
  2748. percent,
  2749. widthPercent: (fractionWidth * 100) | 0
  2750. });
  2751. ids.add(view.id);
  2752. }
  2753. const first = visible[0],
  2754. last = visible.at(-1);
  2755. if (sortByVisibility) {
  2756. visible.sort(function (a, b) {
  2757. const pc = a.percent - b.percent;
  2758. if (Math.abs(pc) > 0.001) {
  2759. return -pc;
  2760. }
  2761. return a.id - b.id;
  2762. });
  2763. }
  2764. return {
  2765. first,
  2766. last,
  2767. views: visible,
  2768. ids
  2769. };
  2770. }
  2771. function noContextMenuHandler(evt) {
  2772. evt.preventDefault();
  2773. }
  2774. function normalizeWheelEventDirection(evt) {
  2775. let delta = Math.hypot(evt.deltaX, evt.deltaY);
  2776. const angle = Math.atan2(evt.deltaY, evt.deltaX);
  2777. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  2778. delta = -delta;
  2779. }
  2780. return delta;
  2781. }
  2782. function normalizeWheelEventDelta(evt) {
  2783. const deltaMode = evt.deltaMode;
  2784. let delta = normalizeWheelEventDirection(evt);
  2785. const MOUSE_PIXELS_PER_LINE = 30;
  2786. const MOUSE_LINES_PER_PAGE = 30;
  2787. if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
  2788. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  2789. } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) {
  2790. delta /= MOUSE_LINES_PER_PAGE;
  2791. }
  2792. return delta;
  2793. }
  2794. function isValidRotation(angle) {
  2795. return Number.isInteger(angle) && angle % 90 === 0;
  2796. }
  2797. function isValidScrollMode(mode) {
  2798. return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN;
  2799. }
  2800. function isValidSpreadMode(mode) {
  2801. return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN;
  2802. }
  2803. function isPortraitOrientation(size) {
  2804. return size.width <= size.height;
  2805. }
  2806. const animationStarted = new Promise(function (resolve) {
  2807. window.requestAnimationFrame(resolve);
  2808. });
  2809. exports.animationStarted = animationStarted;
  2810. const docStyle = document.documentElement.style;
  2811. exports.docStyle = docStyle;
  2812. function clamp(v, min, max) {
  2813. return Math.min(Math.max(v, min), max);
  2814. }
  2815. class ProgressBar {
  2816. #classList = null;
  2817. #disableAutoFetchTimeout = null;
  2818. #percent = 0;
  2819. #style = null;
  2820. #visible = true;
  2821. constructor(bar) {
  2822. this.#classList = bar.classList;
  2823. this.#style = bar.style;
  2824. }
  2825. get percent() {
  2826. return this.#percent;
  2827. }
  2828. set percent(val) {
  2829. this.#percent = clamp(val, 0, 100);
  2830. if (isNaN(val)) {
  2831. this.#classList.add('indeterminate');
  2832. return;
  2833. }
  2834. this.#classList.remove('indeterminate');
  2835. this.#style.setProperty('--progressBar-percent', `${this.#percent}%`);
  2836. }
  2837. setWidth(viewer) {
  2838. if (!viewer) {
  2839. return;
  2840. }
  2841. const container = viewer.parentNode;
  2842. const scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  2843. if (scrollbarWidth > 0) {
  2844. this.#style.setProperty('--progressBar-end-offset', `${scrollbarWidth}px`);
  2845. }
  2846. }
  2847. setDisableAutoFetch(delay = 5000) {
  2848. if (isNaN(this.#percent)) {
  2849. return;
  2850. }
  2851. if (this.#disableAutoFetchTimeout) {
  2852. clearTimeout(this.#disableAutoFetchTimeout);
  2853. }
  2854. this.show();
  2855. this.#disableAutoFetchTimeout = setTimeout(() => {
  2856. this.#disableAutoFetchTimeout = null;
  2857. this.hide();
  2858. }, delay);
  2859. }
  2860. hide() {
  2861. if (!this.#visible) {
  2862. return;
  2863. }
  2864. this.#visible = false;
  2865. this.#classList.add('hidden');
  2866. }
  2867. show() {
  2868. if (this.#visible) {
  2869. return;
  2870. }
  2871. this.#visible = true;
  2872. this.#classList.remove('hidden');
  2873. }
  2874. }
  2875. exports.ProgressBar = ProgressBar;
  2876. function getActiveOrFocusedElement() {
  2877. let curRoot = document;
  2878. let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(':focus');
  2879. while (curActiveOrFocused?.shadowRoot) {
  2880. curRoot = curActiveOrFocused.shadowRoot;
  2881. curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(':focus');
  2882. }
  2883. return curActiveOrFocused;
  2884. }
  2885. function apiPageLayoutToViewerModes(layout) {
  2886. let scrollMode = ScrollMode.VERTICAL,
  2887. spreadMode = SpreadMode.NONE;
  2888. switch (layout) {
  2889. case 'SinglePage':
  2890. scrollMode = ScrollMode.PAGE;
  2891. break;
  2892. case 'OneColumn':
  2893. break;
  2894. case 'TwoPageLeft':
  2895. scrollMode = ScrollMode.PAGE;
  2896. case 'TwoColumnLeft':
  2897. spreadMode = SpreadMode.ODD;
  2898. break;
  2899. case 'TwoPageRight':
  2900. scrollMode = ScrollMode.PAGE;
  2901. case 'TwoColumnRight':
  2902. spreadMode = SpreadMode.EVEN;
  2903. break;
  2904. }
  2905. return {
  2906. scrollMode,
  2907. spreadMode
  2908. };
  2909. }
  2910. function apiPageModeToSidebarView(mode) {
  2911. switch (mode) {
  2912. case 'UseNone':
  2913. return SidebarView.NONE;
  2914. case 'UseThumbs':
  2915. return SidebarView.THUMBS;
  2916. case 'UseOutlines':
  2917. return SidebarView.OUTLINE;
  2918. case 'UseAttachments':
  2919. return SidebarView.ATTACHMENTS;
  2920. case 'UseOC':
  2921. return SidebarView.LAYERS;
  2922. }
  2923. return SidebarView.NONE;
  2924. }
  2925. function toggleCheckedBtn(button, toggle, view = null) {
  2926. button.classList.toggle('toggled', toggle);
  2927. button.setAttribute('aria-checked', toggle);
  2928. view?.classList.toggle('hidden', !toggle);
  2929. }
  2930. function toggleExpandedBtn(button, toggle, view = null) {
  2931. button.classList.toggle('toggled', toggle);
  2932. button.setAttribute('aria-expanded', toggle);
  2933. view?.classList.toggle('hidden', !toggle);
  2934. }
  2935. /***/
  2936. },
  2937. /* 4 */
  2938. /***/ (module) => {
  2939. let pdfjsLib;
  2940. if (typeof window !== 'undefined' && window['pdfjs-dist/build/pdf']) {
  2941. pdfjsLib = window['pdfjs-dist/build/pdf'];
  2942. } else {
  2943. pdfjsLib = require('../build/pdf.js');
  2944. }
  2945. module.exports = pdfjsLib;
  2946. /***/
  2947. },
  2948. /* 5 */
  2949. /***/ (__unused_webpack_module, exports) => {
  2950. Object.defineProperty(exports, '__esModule', {
  2951. value: true
  2952. });
  2953. exports.compatibilityParams = exports.OptionKind = exports.AppOptions = void 0;
  2954. const compatibilityParams = Object.create(null);
  2955. exports.compatibilityParams = compatibilityParams;
  2956. {
  2957. const userAgent = navigator.userAgent || '';
  2958. const platform = navigator.platform || '';
  2959. const maxTouchPoints = navigator.maxTouchPoints || 1;
  2960. const isAndroid = /Android/.test(userAgent);
  2961. const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || (platform === 'MacIntel' && maxTouchPoints > 1);
  2962. (function checkCanvasSizeLimitation() {
  2963. if (isIOS || isAndroid) {
  2964. compatibilityParams.maxCanvasPixels = 5242880;
  2965. }
  2966. })();
  2967. }
  2968. const OptionKind = {
  2969. VIEWER: 0x02,
  2970. API: 0x04,
  2971. WORKER: 0x08,
  2972. PREFERENCE: 0x80
  2973. };
  2974. exports.OptionKind = OptionKind;
  2975. const defaultOptions = {
  2976. annotationEditorMode: {
  2977. value: 0,
  2978. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  2979. },
  2980. annotationMode: {
  2981. value: 2,
  2982. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  2983. },
  2984. cursorToolOnLoad: {
  2985. value: 0,
  2986. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  2987. },
  2988. defaultZoomDelay: {
  2989. value: 400,
  2990. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  2991. },
  2992. defaultZoomValue: {
  2993. value: '',
  2994. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  2995. },
  2996. disableHistory: {
  2997. value: false,
  2998. kind: OptionKind.VIEWER
  2999. },
  3000. disablePageLabels: {
  3001. value: false,
  3002. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3003. },
  3004. enableFloatingToolbar: {
  3005. value: false,
  3006. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3007. },
  3008. enablePermissions: {
  3009. value: false,
  3010. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3011. },
  3012. enablePrintAutoRotate: {
  3013. value: true,
  3014. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3015. },
  3016. enableScripting: {
  3017. value: true,
  3018. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3019. },
  3020. externalLinkRel: {
  3021. value: 'noopener noreferrer nofollow',
  3022. kind: OptionKind.VIEWER
  3023. },
  3024. externalLinkTarget: {
  3025. value: 0,
  3026. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3027. },
  3028. historyUpdateUrl: {
  3029. value: false,
  3030. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3031. },
  3032. ignoreDestinationZoom: {
  3033. value: false,
  3034. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3035. },
  3036. imageResourcesPath: {
  3037. value: './images/',
  3038. kind: OptionKind.VIEWER
  3039. },
  3040. maxCanvasPixels: {
  3041. value: 16777216,
  3042. kind: OptionKind.VIEWER
  3043. },
  3044. forcePageColors: {
  3045. value: false,
  3046. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3047. },
  3048. pageColorsBackground: {
  3049. value: 'Canvas',
  3050. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3051. },
  3052. pageColorsForeground: {
  3053. value: 'CanvasText',
  3054. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3055. },
  3056. pdfBugEnabled: {
  3057. value: false,
  3058. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3059. },
  3060. printResolution: {
  3061. value: 150,
  3062. kind: OptionKind.VIEWER
  3063. },
  3064. sidebarViewOnLoad: {
  3065. value: -1,
  3066. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3067. },
  3068. scrollModeOnLoad: {
  3069. value: -1,
  3070. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3071. },
  3072. spreadModeOnLoad: {
  3073. value: -1,
  3074. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3075. },
  3076. textLayerMode: {
  3077. value: 1,
  3078. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3079. },
  3080. useOnlyCssZoom: {
  3081. value: false,
  3082. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3083. },
  3084. viewerCssTheme: {
  3085. value: 0,
  3086. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3087. },
  3088. viewOnLoad: {
  3089. value: 0,
  3090. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  3091. },
  3092. cMapPacked: {
  3093. value: true,
  3094. kind: OptionKind.API
  3095. },
  3096. cMapUrl: {
  3097. value: '../web/cmaps/',
  3098. kind: OptionKind.API
  3099. },
  3100. disableAutoFetch: {
  3101. value: false,
  3102. kind: OptionKind.API + OptionKind.PREFERENCE
  3103. },
  3104. disableFontFace: {
  3105. value: false,
  3106. kind: OptionKind.API + OptionKind.PREFERENCE
  3107. },
  3108. disableRange: {
  3109. value: false,
  3110. kind: OptionKind.API + OptionKind.PREFERENCE
  3111. },
  3112. disableStream: {
  3113. value: false,
  3114. kind: OptionKind.API + OptionKind.PREFERENCE
  3115. },
  3116. docBaseUrl: {
  3117. value: '',
  3118. kind: OptionKind.API
  3119. },
  3120. enableXfa: {
  3121. value: true,
  3122. kind: OptionKind.API + OptionKind.PREFERENCE
  3123. },
  3124. fontExtraProperties: {
  3125. value: false,
  3126. kind: OptionKind.API
  3127. },
  3128. isEvalSupported: {
  3129. value: true,
  3130. kind: OptionKind.API
  3131. },
  3132. isOffscreenCanvasSupported: {
  3133. value: true,
  3134. kind: OptionKind.API
  3135. },
  3136. maxImageSize: {
  3137. value: -1,
  3138. kind: OptionKind.API
  3139. },
  3140. pdfBug: {
  3141. value: false,
  3142. kind: OptionKind.API
  3143. },
  3144. standardFontDataUrl: {
  3145. value: '../web/standard_fonts/',
  3146. kind: OptionKind.API
  3147. },
  3148. verbosity: {
  3149. value: 1,
  3150. kind: OptionKind.API
  3151. },
  3152. workerPort: {
  3153. value: null,
  3154. kind: OptionKind.WORKER
  3155. },
  3156. workerSrc: {
  3157. value: '../build/pdf.worker.js',
  3158. kind: OptionKind.WORKER
  3159. }
  3160. };
  3161. {
  3162. defaultOptions.defaultUrl = {
  3163. value: 'compressed.tracemonkey-pldi-09.pdf',
  3164. kind: OptionKind.VIEWER
  3165. };
  3166. defaultOptions.disablePreferences = {
  3167. value: false,
  3168. kind: OptionKind.VIEWER
  3169. };
  3170. defaultOptions.locale = {
  3171. value: navigator.language || 'en-US',
  3172. kind: OptionKind.VIEWER
  3173. };
  3174. defaultOptions.sandboxBundleSrc = {
  3175. value: '../build/pdf.sandbox.js',
  3176. kind: OptionKind.VIEWER
  3177. };
  3178. }
  3179. const userOptions = Object.create(null);
  3180. class AppOptions {
  3181. constructor() {
  3182. throw new Error('Cannot initialize AppOptions.');
  3183. }
  3184. static get(name) {
  3185. const userOption = userOptions[name];
  3186. if (userOption !== undefined) {
  3187. return userOption;
  3188. }
  3189. const defaultOption = defaultOptions[name];
  3190. if (defaultOption !== undefined) {
  3191. return compatibilityParams[name] ?? defaultOption.value;
  3192. }
  3193. return undefined;
  3194. }
  3195. static getAll(kind = null) {
  3196. const options = Object.create(null);
  3197. for (const name in defaultOptions) {
  3198. const defaultOption = defaultOptions[name];
  3199. if (kind) {
  3200. if ((kind & defaultOption.kind) === 0) {
  3201. continue;
  3202. }
  3203. if (kind === OptionKind.PREFERENCE) {
  3204. const value = defaultOption.value,
  3205. valueType = typeof value;
  3206. if (valueType === 'boolean' || valueType === 'string' || (valueType === 'number' && Number.isInteger(value))) {
  3207. options[name] = value;
  3208. continue;
  3209. }
  3210. throw new Error(`Invalid type for preference: ${name}`);
  3211. }
  3212. }
  3213. const userOption = userOptions[name];
  3214. options[name] = userOption !== undefined ? userOption : compatibilityParams[name] ?? defaultOption.value;
  3215. }
  3216. return options;
  3217. }
  3218. static set(name, value) {
  3219. userOptions[name] = value;
  3220. }
  3221. static setAll(options) {
  3222. for (const name in options) {
  3223. userOptions[name] = options[name];
  3224. }
  3225. }
  3226. static remove(name) {
  3227. delete userOptions[name];
  3228. }
  3229. }
  3230. exports.AppOptions = AppOptions;
  3231. {
  3232. AppOptions._hasUserOptions = function () {
  3233. return Object.keys(userOptions).length > 0;
  3234. };
  3235. }
  3236. /***/
  3237. },
  3238. /* 6 */
  3239. /***/ (__unused_webpack_module, exports) => {
  3240. Object.defineProperty(exports, '__esModule', {
  3241. value: true
  3242. });
  3243. exports.WaitOnType = exports.EventBus = exports.AutomationEventBus = void 0;
  3244. exports.waitOnEventOrTimeout = waitOnEventOrTimeout;
  3245. const WaitOnType = {
  3246. EVENT: 'event',
  3247. TIMEOUT: 'timeout'
  3248. };
  3249. exports.WaitOnType = WaitOnType;
  3250. function waitOnEventOrTimeout({ target, name, delay = 0 }) {
  3251. return new Promise(function (resolve, reject) {
  3252. if (typeof target !== 'object' || !(name && typeof name === 'string') || !(Number.isInteger(delay) && delay >= 0)) {
  3253. throw new Error('waitOnEventOrTimeout - invalid parameters.');
  3254. }
  3255. function handler(type) {
  3256. if (target instanceof EventBus) {
  3257. target._off(name, eventHandler);
  3258. } else {
  3259. target.removeEventListener(name, eventHandler);
  3260. }
  3261. if (timeout) {
  3262. clearTimeout(timeout);
  3263. }
  3264. resolve(type);
  3265. }
  3266. const eventHandler = handler.bind(null, WaitOnType.EVENT);
  3267. if (target instanceof EventBus) {
  3268. target._on(name, eventHandler);
  3269. } else {
  3270. target.addEventListener(name, eventHandler);
  3271. }
  3272. const timeoutHandler = handler.bind(null, WaitOnType.TIMEOUT);
  3273. const timeout = setTimeout(timeoutHandler, delay);
  3274. });
  3275. }
  3276. class EventBus {
  3277. #listeners = Object.create(null);
  3278. on(eventName, listener, options = null) {
  3279. this._on(eventName, listener, {
  3280. external: true,
  3281. once: options?.once
  3282. });
  3283. }
  3284. off(eventName, listener, options = null) {
  3285. this._off(eventName, listener, {
  3286. external: true,
  3287. once: options?.once
  3288. });
  3289. }
  3290. dispatch(eventName, data) {
  3291. const eventListeners = this.#listeners[eventName];
  3292. if (!eventListeners || eventListeners.length === 0) {
  3293. return;
  3294. }
  3295. let externalListeners;
  3296. for (const { listener, external, once } of eventListeners.slice(0)) {
  3297. if (once) {
  3298. this._off(eventName, listener);
  3299. }
  3300. if (external) {
  3301. (externalListeners ||= []).push(listener);
  3302. continue;
  3303. }
  3304. listener(data);
  3305. }
  3306. if (externalListeners) {
  3307. for (const listener of externalListeners) {
  3308. listener(data);
  3309. }
  3310. externalListeners = null;
  3311. }
  3312. }
  3313. _on(eventName, listener, options = null) {
  3314. const eventListeners = (this.#listeners[eventName] ||= []);
  3315. eventListeners.push({
  3316. listener,
  3317. external: options?.external === true,
  3318. once: options?.once === true
  3319. });
  3320. }
  3321. _off(eventName, listener, options = null) {
  3322. const eventListeners = this.#listeners[eventName];
  3323. if (!eventListeners) {
  3324. return;
  3325. }
  3326. for (let i = 0, ii = eventListeners.length; i < ii; i++) {
  3327. if (eventListeners[i].listener === listener) {
  3328. eventListeners.splice(i, 1);
  3329. return;
  3330. }
  3331. }
  3332. }
  3333. }
  3334. exports.EventBus = EventBus;
  3335. class AutomationEventBus extends EventBus {
  3336. dispatch(eventName, data) {
  3337. throw new Error('Not implemented: AutomationEventBus.dispatch');
  3338. }
  3339. }
  3340. exports.AutomationEventBus = AutomationEventBus;
  3341. /***/
  3342. },
  3343. /* 7 */
  3344. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  3345. Object.defineProperty(exports, '__esModule', {
  3346. value: true
  3347. });
  3348. exports.SimpleLinkService = exports.PDFLinkService = exports.LinkTarget = void 0;
  3349. var _ui_utils = __webpack_require__(3);
  3350. const DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
  3351. const LinkTarget = {
  3352. NONE: 0,
  3353. SELF: 1,
  3354. BLANK: 2,
  3355. PARENT: 3,
  3356. TOP: 4
  3357. };
  3358. exports.LinkTarget = LinkTarget;
  3359. function addLinkAttributes(link, { url, target, rel, enabled = true } = {}) {
  3360. if (!url || typeof url !== 'string') {
  3361. throw new Error('A valid "url" parameter must provided.');
  3362. }
  3363. const urlNullRemoved = (0, _ui_utils.removeNullCharacters)(url);
  3364. if (enabled) {
  3365. link.href = link.title = urlNullRemoved;
  3366. } else {
  3367. link.href = '';
  3368. link.title = `Disabled: ${urlNullRemoved}`;
  3369. link.onclick = () => {
  3370. return false;
  3371. };
  3372. }
  3373. let targetStr = '';
  3374. switch (target) {
  3375. case LinkTarget.NONE:
  3376. break;
  3377. case LinkTarget.SELF:
  3378. targetStr = '_self';
  3379. break;
  3380. case LinkTarget.BLANK:
  3381. targetStr = '_blank';
  3382. break;
  3383. case LinkTarget.PARENT:
  3384. targetStr = '_parent';
  3385. break;
  3386. case LinkTarget.TOP:
  3387. targetStr = '_top';
  3388. break;
  3389. }
  3390. link.target = targetStr;
  3391. link.rel = typeof rel === 'string' ? rel : DEFAULT_LINK_REL;
  3392. }
  3393. class PDFLinkService {
  3394. #pagesRefCache = new Map();
  3395. constructor({ eventBus, externalLinkTarget = null, externalLinkRel = null, ignoreDestinationZoom = false } = {}) {
  3396. this.eventBus = eventBus;
  3397. this.externalLinkTarget = externalLinkTarget;
  3398. this.externalLinkRel = externalLinkRel;
  3399. this.externalLinkEnabled = true;
  3400. this._ignoreDestinationZoom = ignoreDestinationZoom;
  3401. this.baseUrl = null;
  3402. this.pdfDocument = null;
  3403. this.pdfViewer = null;
  3404. this.pdfHistory = null;
  3405. }
  3406. setDocument(pdfDocument, baseUrl = null) {
  3407. this.baseUrl = baseUrl;
  3408. this.pdfDocument = pdfDocument;
  3409. this.#pagesRefCache.clear();
  3410. }
  3411. setViewer(pdfViewer) {
  3412. this.pdfViewer = pdfViewer;
  3413. }
  3414. setHistory(pdfHistory) {
  3415. this.pdfHistory = pdfHistory;
  3416. }
  3417. get pagesCount() {
  3418. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  3419. }
  3420. get page() {
  3421. return this.pdfViewer.currentPageNumber;
  3422. }
  3423. set page(value) {
  3424. this.pdfViewer.currentPageNumber = value;
  3425. }
  3426. get rotation() {
  3427. return this.pdfViewer.pagesRotation;
  3428. }
  3429. set rotation(value) {
  3430. this.pdfViewer.pagesRotation = value;
  3431. }
  3432. get isInPresentationMode() {
  3433. return this.pdfViewer.isInPresentationMode;
  3434. }
  3435. #goToDestinationHelper(rawDest, namedDest = null, explicitDest) {
  3436. const destRef = explicitDest[0];
  3437. let pageNumber;
  3438. if (typeof destRef === 'object' && destRef !== null) {
  3439. pageNumber = this._cachedPageNumber(destRef);
  3440. if (!pageNumber) {
  3441. this.pdfDocument
  3442. .getPageIndex(destRef)
  3443. .then((pageIndex) => {
  3444. this.cachePageRef(pageIndex + 1, destRef);
  3445. this.#goToDestinationHelper(rawDest, namedDest, explicitDest);
  3446. })
  3447. .catch(() => {
  3448. console.error(`PDFLinkService.#goToDestinationHelper: "${destRef}" is not ` + `a valid page reference, for dest="${rawDest}".`);
  3449. });
  3450. return;
  3451. }
  3452. } else if (Number.isInteger(destRef)) {
  3453. pageNumber = destRef + 1;
  3454. } else {
  3455. console.error(`PDFLinkService.#goToDestinationHelper: "${destRef}" is not ` + `a valid destination reference, for dest="${rawDest}".`);
  3456. return;
  3457. }
  3458. if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
  3459. console.error(`PDFLinkService.#goToDestinationHelper: "${pageNumber}" is not ` + `a valid page number, for dest="${rawDest}".`);
  3460. return;
  3461. }
  3462. if (this.pdfHistory) {
  3463. this.pdfHistory.pushCurrentPosition();
  3464. this.pdfHistory.push({
  3465. namedDest,
  3466. explicitDest,
  3467. pageNumber
  3468. });
  3469. }
  3470. this.pdfViewer.scrollPageIntoView({
  3471. pageNumber,
  3472. destArray: explicitDest,
  3473. ignoreDestinationZoom: this._ignoreDestinationZoom
  3474. });
  3475. }
  3476. async goToDestination(dest) {
  3477. if (!this.pdfDocument) {
  3478. return;
  3479. }
  3480. let namedDest, explicitDest;
  3481. if (typeof dest === 'string') {
  3482. namedDest = dest;
  3483. explicitDest = await this.pdfDocument.getDestination(dest);
  3484. } else {
  3485. namedDest = null;
  3486. explicitDest = await dest;
  3487. }
  3488. if (!Array.isArray(explicitDest)) {
  3489. console.error(`PDFLinkService.goToDestination: "${explicitDest}" is not ` + `a valid destination array, for dest="${dest}".`);
  3490. return;
  3491. }
  3492. this.#goToDestinationHelper(dest, namedDest, explicitDest);
  3493. }
  3494. goToPage(val) {
  3495. if (!this.pdfDocument) {
  3496. return;
  3497. }
  3498. const pageNumber = (typeof val === 'string' && this.pdfViewer.pageLabelToPageNumber(val)) || val | 0;
  3499. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  3500. console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`);
  3501. return;
  3502. }
  3503. if (this.pdfHistory) {
  3504. this.pdfHistory.pushCurrentPosition();
  3505. this.pdfHistory.pushPage(pageNumber);
  3506. }
  3507. this.pdfViewer.scrollPageIntoView({
  3508. pageNumber
  3509. });
  3510. }
  3511. addLinkAttributes(link, url, newWindow = false) {
  3512. addLinkAttributes(link, {
  3513. url,
  3514. target: newWindow ? LinkTarget.BLANK : this.externalLinkTarget,
  3515. rel: this.externalLinkRel,
  3516. enabled: this.externalLinkEnabled
  3517. });
  3518. }
  3519. getDestinationHash(dest) {
  3520. if (typeof dest === 'string') {
  3521. if (dest.length > 0) {
  3522. return this.getAnchorUrl('#' + escape(dest));
  3523. }
  3524. } else if (Array.isArray(dest)) {
  3525. const str = JSON.stringify(dest);
  3526. if (str.length > 0) {
  3527. return this.getAnchorUrl('#' + escape(str));
  3528. }
  3529. }
  3530. return this.getAnchorUrl('');
  3531. }
  3532. getAnchorUrl(anchor) {
  3533. return this.baseUrl ? this.baseUrl + anchor : anchor;
  3534. }
  3535. setHash(hash) {
  3536. if (!this.pdfDocument) {
  3537. return;
  3538. }
  3539. let pageNumber, dest;
  3540. if (hash.includes('=')) {
  3541. const params = (0, _ui_utils.parseQueryString)(hash);
  3542. if (params.has('search')) {
  3543. const query = params.get('search').replaceAll('"', ''),
  3544. phrase = params.get('phrase') === 'true';
  3545. this.eventBus.dispatch('findfromurlhash', {
  3546. source: this,
  3547. query: phrase ? query : query.match(/\S+/g)
  3548. });
  3549. }
  3550. if (params.has('page')) {
  3551. pageNumber = params.get('page') | 0 || 1;
  3552. }
  3553. if (params.has('zoom')) {
  3554. const zoomArgs = params.get('zoom').split(',');
  3555. const zoomArg = zoomArgs[0];
  3556. const zoomArgNumber = parseFloat(zoomArg);
  3557. if (!zoomArg.includes('Fit')) {
  3558. dest = [
  3559. null,
  3560. {
  3561. name: 'XYZ'
  3562. },
  3563. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,
  3564. zoomArgs.length > 2 ? zoomArgs[2] | 0 : null,
  3565. zoomArgNumber ? zoomArgNumber / 100 : zoomArg
  3566. ];
  3567. } else {
  3568. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  3569. dest = [
  3570. null,
  3571. {
  3572. name: zoomArg
  3573. }
  3574. ];
  3575. } else if (zoomArg === 'FitH' || zoomArg === 'FitBH' || zoomArg === 'FitV' || zoomArg === 'FitBV') {
  3576. dest = [
  3577. null,
  3578. {
  3579. name: zoomArg
  3580. },
  3581. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null
  3582. ];
  3583. } else if (zoomArg === 'FitR') {
  3584. if (zoomArgs.length !== 5) {
  3585. console.error('PDFLinkService.setHash: Not enough parameters for "FitR".');
  3586. } else {
  3587. dest = [
  3588. null,
  3589. {
  3590. name: zoomArg
  3591. },
  3592. zoomArgs[1] | 0,
  3593. zoomArgs[2] | 0,
  3594. zoomArgs[3] | 0,
  3595. zoomArgs[4] | 0
  3596. ];
  3597. }
  3598. } else {
  3599. console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`);
  3600. }
  3601. }
  3602. }
  3603. if (dest) {
  3604. this.pdfViewer.scrollPageIntoView({
  3605. pageNumber: pageNumber || this.page,
  3606. destArray: dest,
  3607. allowNegativeOffset: true
  3608. });
  3609. } else if (pageNumber) {
  3610. this.page = pageNumber;
  3611. }
  3612. if (params.has('pagemode')) {
  3613. this.eventBus.dispatch('pagemode', {
  3614. source: this,
  3615. mode: params.get('pagemode')
  3616. });
  3617. }
  3618. if (params.has('nameddest')) {
  3619. this.goToDestination(params.get('nameddest'));
  3620. }
  3621. } else {
  3622. dest = unescape(hash);
  3623. try {
  3624. dest = JSON.parse(dest);
  3625. if (!Array.isArray(dest)) {
  3626. dest = dest.toString();
  3627. }
  3628. } catch (ex) {}
  3629. if (typeof dest === 'string' || PDFLinkService.#isValidExplicitDestination(dest)) {
  3630. this.goToDestination(dest);
  3631. return;
  3632. }
  3633. console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`);
  3634. }
  3635. }
  3636. executeNamedAction(action) {
  3637. switch (action) {
  3638. case 'GoBack':
  3639. this.pdfHistory?.back();
  3640. break;
  3641. case 'GoForward':
  3642. this.pdfHistory?.forward();
  3643. break;
  3644. case 'NextPage':
  3645. this.pdfViewer.nextPage();
  3646. break;
  3647. case 'PrevPage':
  3648. this.pdfViewer.previousPage();
  3649. break;
  3650. case 'LastPage':
  3651. this.page = this.pagesCount;
  3652. break;
  3653. case 'FirstPage':
  3654. this.page = 1;
  3655. break;
  3656. default:
  3657. break;
  3658. }
  3659. this.eventBus.dispatch('namedaction', {
  3660. source: this,
  3661. action
  3662. });
  3663. }
  3664. async executeSetOCGState(action) {
  3665. const pdfDocument = this.pdfDocument;
  3666. const optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;
  3667. if (pdfDocument !== this.pdfDocument) {
  3668. return;
  3669. }
  3670. let operator;
  3671. for (const elem of action.state) {
  3672. switch (elem) {
  3673. case 'ON':
  3674. case 'OFF':
  3675. case 'Toggle':
  3676. operator = elem;
  3677. continue;
  3678. }
  3679. switch (operator) {
  3680. case 'ON':
  3681. optionalContentConfig.setVisibility(elem, true);
  3682. break;
  3683. case 'OFF':
  3684. optionalContentConfig.setVisibility(elem, false);
  3685. break;
  3686. case 'Toggle':
  3687. const group = optionalContentConfig.getGroup(elem);
  3688. if (group) {
  3689. optionalContentConfig.setVisibility(elem, !group.visible);
  3690. }
  3691. break;
  3692. }
  3693. }
  3694. this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig);
  3695. }
  3696. cachePageRef(pageNum, pageRef) {
  3697. if (!pageRef) {
  3698. return;
  3699. }
  3700. const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`;
  3701. this.#pagesRefCache.set(refStr, pageNum);
  3702. }
  3703. _cachedPageNumber(pageRef) {
  3704. if (!pageRef) {
  3705. return null;
  3706. }
  3707. const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`;
  3708. return this.#pagesRefCache.get(refStr) || null;
  3709. }
  3710. static #isValidExplicitDestination(dest) {
  3711. if (!Array.isArray(dest)) {
  3712. return false;
  3713. }
  3714. const destLength = dest.length;
  3715. if (destLength < 2) {
  3716. return false;
  3717. }
  3718. const page = dest[0];
  3719. if (!(typeof page === 'object' && Number.isInteger(page.num) && Number.isInteger(page.gen)) && !(Number.isInteger(page) && page >= 0)) {
  3720. return false;
  3721. }
  3722. const zoom = dest[1];
  3723. if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
  3724. return false;
  3725. }
  3726. let allowNull = true;
  3727. switch (zoom.name) {
  3728. case 'XYZ':
  3729. if (destLength !== 5) {
  3730. return false;
  3731. }
  3732. break;
  3733. case 'Fit':
  3734. case 'FitB':
  3735. return destLength === 2;
  3736. case 'FitH':
  3737. case 'FitBH':
  3738. case 'FitV':
  3739. case 'FitBV':
  3740. if (destLength !== 3) {
  3741. return false;
  3742. }
  3743. break;
  3744. case 'FitR':
  3745. if (destLength !== 6) {
  3746. return false;
  3747. }
  3748. allowNull = false;
  3749. break;
  3750. default:
  3751. return false;
  3752. }
  3753. for (let i = 2; i < destLength; i++) {
  3754. const param = dest[i];
  3755. if (!(typeof param === 'number' || (allowNull && param === null))) {
  3756. return false;
  3757. }
  3758. }
  3759. return true;
  3760. }
  3761. }
  3762. exports.PDFLinkService = PDFLinkService;
  3763. class SimpleLinkService {
  3764. constructor() {
  3765. this.externalLinkEnabled = true;
  3766. }
  3767. get pagesCount() {
  3768. return 0;
  3769. }
  3770. get page() {
  3771. return 0;
  3772. }
  3773. set page(value) {}
  3774. get rotation() {
  3775. return 0;
  3776. }
  3777. set rotation(value) {}
  3778. get isInPresentationMode() {
  3779. return false;
  3780. }
  3781. async goToDestination(dest) {}
  3782. goToPage(val) {}
  3783. addLinkAttributes(link, url, newWindow = false) {
  3784. addLinkAttributes(link, {
  3785. url,
  3786. enabled: this.externalLinkEnabled
  3787. });
  3788. }
  3789. getDestinationHash(dest) {
  3790. return '#';
  3791. }
  3792. getAnchorUrl(hash) {
  3793. return '#';
  3794. }
  3795. setHash(hash) {}
  3796. executeNamedAction(action) {}
  3797. executeSetOCGState(action) {}
  3798. cachePageRef(pageNum, pageRef) {}
  3799. }
  3800. exports.SimpleLinkService = SimpleLinkService;
  3801. /***/
  3802. },
  3803. /* 8 */
  3804. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  3805. Object.defineProperty(exports, '__esModule', {
  3806. value: true
  3807. });
  3808. exports.AnnotationEditorParams = void 0;
  3809. var _pdfjsLib = __webpack_require__(4);
  3810. class AnnotationEditorParams {
  3811. constructor(options, eventBus) {
  3812. this.eventBus = eventBus;
  3813. this.#bindListeners(options);
  3814. }
  3815. #bindListeners({ editorFreeTextFontSize, editorFreeTextColor, editorInkColor, editorInkThickness, editorInkOpacity }) {
  3816. const dispatchEvent = (typeStr, value) => {
  3817. this.eventBus.dispatch('switchannotationeditorparams', {
  3818. source: this,
  3819. type: _pdfjsLib.AnnotationEditorParamsType[typeStr],
  3820. value
  3821. });
  3822. };
  3823. editorFreeTextFontSize.addEventListener('input', function () {
  3824. dispatchEvent('FREETEXT_SIZE', this.valueAsNumber);
  3825. });
  3826. editorFreeTextColor.addEventListener('input', function () {
  3827. dispatchEvent('FREETEXT_COLOR', this.value);
  3828. });
  3829. editorInkColor.addEventListener('input', function () {
  3830. dispatchEvent('INK_COLOR', this.value);
  3831. });
  3832. editorInkThickness.addEventListener('input', function () {
  3833. dispatchEvent('INK_THICKNESS', this.valueAsNumber);
  3834. });
  3835. editorInkOpacity.addEventListener('input', function () {
  3836. dispatchEvent('INK_OPACITY', this.valueAsNumber);
  3837. });
  3838. this.eventBus._on('annotationeditorparamschanged', (evt) => {
  3839. for (const [type, value] of evt.details) {
  3840. switch (type) {
  3841. case _pdfjsLib.AnnotationEditorParamsType.FREETEXT_SIZE:
  3842. editorFreeTextFontSize.value = value;
  3843. break;
  3844. case _pdfjsLib.AnnotationEditorParamsType.FREETEXT_COLOR:
  3845. editorFreeTextColor.value = value;
  3846. break;
  3847. case _pdfjsLib.AnnotationEditorParamsType.INK_COLOR:
  3848. editorInkColor.value = value;
  3849. break;
  3850. case _pdfjsLib.AnnotationEditorParamsType.INK_THICKNESS:
  3851. editorInkThickness.value = value;
  3852. break;
  3853. case _pdfjsLib.AnnotationEditorParamsType.INK_OPACITY:
  3854. editorInkOpacity.value = value;
  3855. break;
  3856. }
  3857. }
  3858. });
  3859. }
  3860. }
  3861. exports.AnnotationEditorParams = AnnotationEditorParams;
  3862. /***/
  3863. },
  3864. /* 9 */
  3865. /***/ (__unused_webpack_module, exports) => {
  3866. Object.defineProperty(exports, '__esModule', {
  3867. value: true
  3868. });
  3869. exports.OverlayManager = void 0;
  3870. class OverlayManager {
  3871. #overlays = new WeakMap();
  3872. #active = null;
  3873. get active() {
  3874. return this.#active;
  3875. }
  3876. async register(dialog, canForceClose = false) {
  3877. if (typeof dialog !== 'object') {
  3878. throw new Error('Not enough parameters.');
  3879. } else if (this.#overlays.has(dialog)) {
  3880. throw new Error('The overlay is already registered.');
  3881. }
  3882. this.#overlays.set(dialog, {
  3883. canForceClose
  3884. });
  3885. dialog.addEventListener('cancel', (evt) => {
  3886. this.#active = null;
  3887. });
  3888. }
  3889. async unregister(dialog) {
  3890. if (!this.#overlays.has(dialog)) {
  3891. throw new Error('The overlay does not exist.');
  3892. } else if (this.#active === dialog) {
  3893. throw new Error('The overlay cannot be removed while it is active.');
  3894. }
  3895. this.#overlays.delete(dialog);
  3896. }
  3897. async open(dialog) {
  3898. if (!this.#overlays.has(dialog)) {
  3899. throw new Error('The overlay does not exist.');
  3900. } else if (this.#active) {
  3901. if (this.#active === dialog) {
  3902. throw new Error('The overlay is already active.');
  3903. } else if (this.#overlays.get(dialog).canForceClose) {
  3904. await this.close();
  3905. } else {
  3906. throw new Error('Another overlay is currently active.');
  3907. }
  3908. }
  3909. this.#active = dialog;
  3910. dialog.showModal();
  3911. }
  3912. async close(dialog = this.#active) {
  3913. if (!this.#overlays.has(dialog)) {
  3914. throw new Error('The overlay does not exist.');
  3915. } else if (!this.#active) {
  3916. throw new Error('The overlay is currently not active.');
  3917. } else if (this.#active !== dialog) {
  3918. throw new Error('Another overlay is currently active.');
  3919. }
  3920. dialog.close();
  3921. this.#active = null;
  3922. }
  3923. }
  3924. exports.OverlayManager = OverlayManager;
  3925. /***/
  3926. },
  3927. /* 10 */
  3928. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  3929. Object.defineProperty(exports, '__esModule', {
  3930. value: true
  3931. });
  3932. exports.PasswordPrompt = void 0;
  3933. var _pdfjsLib = __webpack_require__(4);
  3934. class PasswordPrompt {
  3935. #activeCapability = null;
  3936. #updateCallback = null;
  3937. #reason = null;
  3938. constructor(options, overlayManager, l10n, isViewerEmbedded = false) {
  3939. this.dialog = options.dialog;
  3940. this.label = options.label;
  3941. this.input = options.input;
  3942. this.submitButton = options.submitButton;
  3943. this.cancelButton = options.cancelButton;
  3944. this.overlayManager = overlayManager;
  3945. this.l10n = l10n;
  3946. this._isViewerEmbedded = isViewerEmbedded;
  3947. this.submitButton.addEventListener('click', this.#verify.bind(this));
  3948. this.cancelButton.addEventListener('click', this.close.bind(this));
  3949. this.input.addEventListener('keydown', (e) => {
  3950. if (e.keyCode === 13) {
  3951. this.#verify();
  3952. }
  3953. });
  3954. this.overlayManager.register(this.dialog, true);
  3955. this.dialog.addEventListener('close', this.#cancel.bind(this));
  3956. }
  3957. async open() {
  3958. if (this.#activeCapability) {
  3959. await this.#activeCapability.promise;
  3960. }
  3961. this.#activeCapability = new _pdfjsLib.PromiseCapability();
  3962. try {
  3963. await this.overlayManager.open(this.dialog);
  3964. } catch (ex) {
  3965. this.#activeCapability = null;
  3966. throw ex;
  3967. }
  3968. const passwordIncorrect = this.#reason === _pdfjsLib.PasswordResponses.INCORRECT_PASSWORD;
  3969. if (!this._isViewerEmbedded || passwordIncorrect) {
  3970. this.input.focus();
  3971. }
  3972. this.label.textContent = await this.l10n.get(`password_${passwordIncorrect ? 'invalid' : 'label'}`);
  3973. }
  3974. async close() {
  3975. if (this.overlayManager.active === this.dialog) {
  3976. this.overlayManager.close(this.dialog);
  3977. }
  3978. }
  3979. #verify() {
  3980. const password = this.input.value;
  3981. if (password?.length > 0) {
  3982. this.#invokeCallback(password);
  3983. }
  3984. }
  3985. #cancel() {
  3986. this.#invokeCallback(new Error('PasswordPrompt cancelled.'));
  3987. this.#activeCapability.resolve();
  3988. }
  3989. #invokeCallback(password) {
  3990. if (!this.#updateCallback) {
  3991. return;
  3992. }
  3993. this.close();
  3994. this.input.value = '';
  3995. this.#updateCallback(password);
  3996. this.#updateCallback = null;
  3997. }
  3998. async setUpdateCallback(updateCallback, reason) {
  3999. if (this.#activeCapability) {
  4000. await this.#activeCapability.promise;
  4001. }
  4002. this.#updateCallback = updateCallback;
  4003. this.#reason = reason;
  4004. }
  4005. }
  4006. exports.PasswordPrompt = PasswordPrompt;
  4007. /***/
  4008. },
  4009. /* 11 */
  4010. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  4011. Object.defineProperty(exports, '__esModule', {
  4012. value: true
  4013. });
  4014. exports.PDFAttachmentViewer = void 0;
  4015. var _pdfjsLib = __webpack_require__(4);
  4016. var _base_tree_viewer = __webpack_require__(12);
  4017. var _event_utils = __webpack_require__(6);
  4018. class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer {
  4019. constructor(options) {
  4020. super(options);
  4021. this.downloadManager = options.downloadManager;
  4022. this.eventBus._on('fileattachmentannotation', this.#appendAttachment.bind(this));
  4023. }
  4024. reset(keepRenderedCapability = false) {
  4025. super.reset();
  4026. this._attachments = null;
  4027. if (!keepRenderedCapability) {
  4028. this._renderedCapability = new _pdfjsLib.PromiseCapability();
  4029. }
  4030. this._pendingDispatchEvent = false;
  4031. }
  4032. async _dispatchEvent(attachmentsCount) {
  4033. this._renderedCapability.resolve();
  4034. if (attachmentsCount === 0 && !this._pendingDispatchEvent) {
  4035. this._pendingDispatchEvent = true;
  4036. await (0, _event_utils.waitOnEventOrTimeout)({
  4037. target: this.eventBus,
  4038. name: 'annotationlayerrendered',
  4039. delay: 1000
  4040. });
  4041. if (!this._pendingDispatchEvent) {
  4042. return;
  4043. }
  4044. }
  4045. this._pendingDispatchEvent = false;
  4046. this.eventBus.dispatch('attachmentsloaded', {
  4047. source: this,
  4048. attachmentsCount
  4049. });
  4050. }
  4051. _bindLink(element, { content, filename }) {
  4052. element.onclick = () => {
  4053. this.downloadManager.openOrDownloadData(element, content, filename);
  4054. return false;
  4055. };
  4056. }
  4057. render({ attachments, keepRenderedCapability = false }) {
  4058. if (this._attachments) {
  4059. this.reset(keepRenderedCapability);
  4060. }
  4061. this._attachments = attachments || null;
  4062. if (!attachments) {
  4063. this._dispatchEvent(0);
  4064. return;
  4065. }
  4066. const fragment = document.createDocumentFragment();
  4067. let attachmentsCount = 0;
  4068. for (const name in attachments) {
  4069. const item = attachments[name];
  4070. const content = item.content,
  4071. filename = (0, _pdfjsLib.getFilenameFromUrl)(item.filename, true);
  4072. const div = document.createElement('div');
  4073. div.className = 'treeItem';
  4074. const element = document.createElement('a');
  4075. this._bindLink(element, {
  4076. content,
  4077. filename
  4078. });
  4079. element.textContent = this._normalizeTextContent(filename);
  4080. div.append(element);
  4081. fragment.append(div);
  4082. attachmentsCount++;
  4083. }
  4084. this._finishRendering(fragment, attachmentsCount);
  4085. }
  4086. #appendAttachment({ filename, content }) {
  4087. const renderedPromise = this._renderedCapability.promise;
  4088. renderedPromise.then(() => {
  4089. if (renderedPromise !== this._renderedCapability.promise) {
  4090. return;
  4091. }
  4092. const attachments = this._attachments || Object.create(null);
  4093. for (const name in attachments) {
  4094. if (filename === name) {
  4095. return;
  4096. }
  4097. }
  4098. attachments[filename] = {
  4099. filename,
  4100. content
  4101. };
  4102. this.render({
  4103. attachments,
  4104. keepRenderedCapability: true
  4105. });
  4106. });
  4107. }
  4108. }
  4109. exports.PDFAttachmentViewer = PDFAttachmentViewer;
  4110. /***/
  4111. },
  4112. /* 12 */
  4113. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  4114. Object.defineProperty(exports, '__esModule', {
  4115. value: true
  4116. });
  4117. exports.BaseTreeViewer = void 0;
  4118. var _ui_utils = __webpack_require__(3);
  4119. const TREEITEM_OFFSET_TOP = -100;
  4120. const TREEITEM_SELECTED_CLASS = 'selected';
  4121. class BaseTreeViewer {
  4122. constructor(options) {
  4123. if (this.constructor === BaseTreeViewer) {
  4124. throw new Error('Cannot initialize BaseTreeViewer.');
  4125. }
  4126. this.container = options.container;
  4127. this.eventBus = options.eventBus;
  4128. this.reset();
  4129. }
  4130. reset() {
  4131. this._pdfDocument = null;
  4132. this._lastToggleIsShow = true;
  4133. this._currentTreeItem = null;
  4134. this.container.textContent = '';
  4135. this.container.classList.remove('treeWithDeepNesting');
  4136. }
  4137. _dispatchEvent(count) {
  4138. throw new Error('Not implemented: _dispatchEvent');
  4139. }
  4140. _bindLink(element, params) {
  4141. throw new Error('Not implemented: _bindLink');
  4142. }
  4143. _normalizeTextContent(str) {
  4144. return (0, _ui_utils.removeNullCharacters)(str, true) || '\u2013';
  4145. }
  4146. _addToggleButton(div, hidden = false) {
  4147. const toggler = document.createElement('div');
  4148. toggler.className = 'treeItemToggler';
  4149. if (hidden) {
  4150. toggler.classList.add('treeItemsHidden');
  4151. }
  4152. toggler.onclick = (evt) => {
  4153. evt.stopPropagation();
  4154. toggler.classList.toggle('treeItemsHidden');
  4155. if (evt.shiftKey) {
  4156. const shouldShowAll = !toggler.classList.contains('treeItemsHidden');
  4157. this._toggleTreeItem(div, shouldShowAll);
  4158. }
  4159. };
  4160. div.prepend(toggler);
  4161. }
  4162. _toggleTreeItem(root, show = false) {
  4163. this._lastToggleIsShow = show;
  4164. for (const toggler of root.querySelectorAll('.treeItemToggler')) {
  4165. toggler.classList.toggle('treeItemsHidden', !show);
  4166. }
  4167. }
  4168. _toggleAllTreeItems() {
  4169. this._toggleTreeItem(this.container, !this._lastToggleIsShow);
  4170. }
  4171. _finishRendering(fragment, count, hasAnyNesting = false) {
  4172. if (hasAnyNesting) {
  4173. this.container.classList.add('treeWithDeepNesting');
  4174. this._lastToggleIsShow = !fragment.querySelector('.treeItemsHidden');
  4175. }
  4176. this.container.append(fragment);
  4177. this._dispatchEvent(count);
  4178. }
  4179. render(params) {
  4180. throw new Error('Not implemented: render');
  4181. }
  4182. _updateCurrentTreeItem(treeItem = null) {
  4183. if (this._currentTreeItem) {
  4184. this._currentTreeItem.classList.remove(TREEITEM_SELECTED_CLASS);
  4185. this._currentTreeItem = null;
  4186. }
  4187. if (treeItem) {
  4188. treeItem.classList.add(TREEITEM_SELECTED_CLASS);
  4189. this._currentTreeItem = treeItem;
  4190. }
  4191. }
  4192. _scrollToCurrentTreeItem(treeItem) {
  4193. if (!treeItem) {
  4194. return;
  4195. }
  4196. let currentNode = treeItem.parentNode;
  4197. while (currentNode && currentNode !== this.container) {
  4198. if (currentNode.classList.contains('treeItem')) {
  4199. const toggler = currentNode.firstElementChild;
  4200. toggler?.classList.remove('treeItemsHidden');
  4201. }
  4202. currentNode = currentNode.parentNode;
  4203. }
  4204. this._updateCurrentTreeItem(treeItem);
  4205. this.container.scrollTo(treeItem.offsetLeft, treeItem.offsetTop + TREEITEM_OFFSET_TOP);
  4206. }
  4207. }
  4208. exports.BaseTreeViewer = BaseTreeViewer;
  4209. /***/
  4210. },
  4211. /* 13 */
  4212. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  4213. Object.defineProperty(exports, '__esModule', {
  4214. value: true
  4215. });
  4216. exports.PDFCursorTools = void 0;
  4217. var _ui_utils = __webpack_require__(3);
  4218. var _pdfjsLib = __webpack_require__(4);
  4219. var _grab_to_pan = __webpack_require__(14);
  4220. class PDFCursorTools {
  4221. constructor({ container, eventBus, cursorToolOnLoad = _ui_utils.CursorTool.SELECT }) {
  4222. this.container = container;
  4223. this.eventBus = eventBus;
  4224. this.active = _ui_utils.CursorTool.SELECT;
  4225. this.previouslyActive = null;
  4226. this.handTool = new _grab_to_pan.GrabToPan({
  4227. element: this.container
  4228. });
  4229. this.#addEventListeners();
  4230. Promise.resolve().then(() => {
  4231. this.switchTool(cursorToolOnLoad);
  4232. });
  4233. }
  4234. get activeTool() {
  4235. return this.active;
  4236. }
  4237. switchTool(tool) {
  4238. if (this.previouslyActive !== null) {
  4239. return;
  4240. }
  4241. if (tool === this.active) {
  4242. return;
  4243. }
  4244. const disableActiveTool = () => {
  4245. switch (this.active) {
  4246. case _ui_utils.CursorTool.SELECT:
  4247. break;
  4248. case _ui_utils.CursorTool.HAND:
  4249. this.handTool.deactivate();
  4250. break;
  4251. case _ui_utils.CursorTool.ZOOM:
  4252. }
  4253. };
  4254. switch (tool) {
  4255. case _ui_utils.CursorTool.SELECT:
  4256. disableActiveTool();
  4257. break;
  4258. case _ui_utils.CursorTool.HAND:
  4259. disableActiveTool();
  4260. this.handTool.activate();
  4261. break;
  4262. case _ui_utils.CursorTool.ZOOM:
  4263. default:
  4264. console.error(`switchTool: "${tool}" is an unsupported value.`);
  4265. return;
  4266. }
  4267. this.active = tool;
  4268. this.#dispatchEvent();
  4269. }
  4270. #dispatchEvent() {
  4271. this.eventBus.dispatch('cursortoolchanged', {
  4272. source: this,
  4273. tool: this.active
  4274. });
  4275. }
  4276. #addEventListeners() {
  4277. this.eventBus._on('switchcursortool', (evt) => {
  4278. this.switchTool(evt.tool);
  4279. });
  4280. let annotationEditorMode = _pdfjsLib.AnnotationEditorType.NONE,
  4281. presentationModeState = _ui_utils.PresentationModeState.NORMAL;
  4282. const disableActive = () => {
  4283. const previouslyActive = this.active;
  4284. this.switchTool(_ui_utils.CursorTool.SELECT);
  4285. this.previouslyActive ??= previouslyActive;
  4286. };
  4287. const enableActive = () => {
  4288. const previouslyActive = this.previouslyActive;
  4289. if (
  4290. previouslyActive !== null &&
  4291. annotationEditorMode === _pdfjsLib.AnnotationEditorType.NONE &&
  4292. presentationModeState === _ui_utils.PresentationModeState.NORMAL
  4293. ) {
  4294. this.previouslyActive = null;
  4295. this.switchTool(previouslyActive);
  4296. }
  4297. };
  4298. this.eventBus._on('secondarytoolbarreset', (evt) => {
  4299. if (this.previouslyActive !== null) {
  4300. annotationEditorMode = _pdfjsLib.AnnotationEditorType.NONE;
  4301. presentationModeState = _ui_utils.PresentationModeState.NORMAL;
  4302. enableActive();
  4303. }
  4304. });
  4305. this.eventBus._on('annotationeditormodechanged', ({ mode }) => {
  4306. annotationEditorMode = mode;
  4307. if (mode === _pdfjsLib.AnnotationEditorType.NONE) {
  4308. enableActive();
  4309. } else {
  4310. disableActive();
  4311. }
  4312. });
  4313. this.eventBus._on('presentationmodechanged', ({ state }) => {
  4314. presentationModeState = state;
  4315. if (state === _ui_utils.PresentationModeState.NORMAL) {
  4316. enableActive();
  4317. } else if (state === _ui_utils.PresentationModeState.FULLSCREEN) {
  4318. disableActive();
  4319. }
  4320. });
  4321. }
  4322. }
  4323. exports.PDFCursorTools = PDFCursorTools;
  4324. /***/
  4325. },
  4326. /* 14 */
  4327. /***/ (__unused_webpack_module, exports) => {
  4328. Object.defineProperty(exports, '__esModule', {
  4329. value: true
  4330. });
  4331. exports.GrabToPan = void 0;
  4332. const CSS_CLASS_GRAB = 'grab-to-pan-grab';
  4333. class GrabToPan {
  4334. constructor(options) {
  4335. this.element = options.element;
  4336. this.document = options.element.ownerDocument;
  4337. if (typeof options.ignoreTarget === 'function') {
  4338. this.ignoreTarget = options.ignoreTarget;
  4339. }
  4340. this.onActiveChanged = options.onActiveChanged;
  4341. this.activate = this.activate.bind(this);
  4342. this.deactivate = this.deactivate.bind(this);
  4343. this.toggle = this.toggle.bind(this);
  4344. this._onMouseDown = this.#onMouseDown.bind(this);
  4345. this._onMouseMove = this.#onMouseMove.bind(this);
  4346. this._endPan = this.#endPan.bind(this);
  4347. const overlay = (this.overlay = document.createElement('div'));
  4348. overlay.className = 'grab-to-pan-grabbing';
  4349. }
  4350. activate() {
  4351. if (!this.active) {
  4352. this.active = true;
  4353. this.element.addEventListener('mousedown', this._onMouseDown, true);
  4354. this.element.classList.add(CSS_CLASS_GRAB);
  4355. this.onActiveChanged?.(true);
  4356. }
  4357. }
  4358. deactivate() {
  4359. if (this.active) {
  4360. this.active = false;
  4361. this.element.removeEventListener('mousedown', this._onMouseDown, true);
  4362. this._endPan();
  4363. this.element.classList.remove(CSS_CLASS_GRAB);
  4364. this.onActiveChanged?.(false);
  4365. }
  4366. }
  4367. toggle() {
  4368. if (this.active) {
  4369. this.deactivate();
  4370. } else {
  4371. this.activate();
  4372. }
  4373. }
  4374. ignoreTarget(node) {
  4375. return node.matches('a[href], a[href] *, input, textarea, button, button *, select, option');
  4376. }
  4377. #onMouseDown(event) {
  4378. if (event.button !== 0 || this.ignoreTarget(event.target)) {
  4379. return;
  4380. }
  4381. if (event.originalTarget) {
  4382. try {
  4383. event.originalTarget.tagName;
  4384. } catch (e) {
  4385. return;
  4386. }
  4387. }
  4388. this.scrollLeftStart = this.element.scrollLeft;
  4389. this.scrollTopStart = this.element.scrollTop;
  4390. this.clientXStart = event.clientX;
  4391. this.clientYStart = event.clientY;
  4392. this.document.addEventListener('mousemove', this._onMouseMove, true);
  4393. this.document.addEventListener('mouseup', this._endPan, true);
  4394. this.element.addEventListener('scroll', this._endPan, true);
  4395. event.preventDefault();
  4396. event.stopPropagation();
  4397. const focusedElement = document.activeElement;
  4398. if (focusedElement && !focusedElement.contains(event.target)) {
  4399. focusedElement.blur();
  4400. }
  4401. }
  4402. #onMouseMove(event) {
  4403. this.element.removeEventListener('scroll', this._endPan, true);
  4404. if (!(event.buttons & 1)) {
  4405. this._endPan();
  4406. return;
  4407. }
  4408. const xDiff = event.clientX - this.clientXStart;
  4409. const yDiff = event.clientY - this.clientYStart;
  4410. const scrollTop = this.scrollTopStart - yDiff;
  4411. const scrollLeft = this.scrollLeftStart - xDiff;
  4412. if (this.element.scrollTo) {
  4413. this.element.scrollTo({
  4414. top: scrollTop,
  4415. left: scrollLeft,
  4416. behavior: 'instant'
  4417. });
  4418. } else {
  4419. this.element.scrollTop = scrollTop;
  4420. this.element.scrollLeft = scrollLeft;
  4421. }
  4422. if (!this.overlay.parentNode) {
  4423. document.body.append(this.overlay);
  4424. }
  4425. }
  4426. #endPan() {
  4427. this.element.removeEventListener('scroll', this._endPan, true);
  4428. this.document.removeEventListener('mousemove', this._onMouseMove, true);
  4429. this.document.removeEventListener('mouseup', this._endPan, true);
  4430. this.overlay.remove();
  4431. }
  4432. }
  4433. exports.GrabToPan = GrabToPan;
  4434. /***/
  4435. },
  4436. /* 15 */
  4437. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  4438. Object.defineProperty(exports, '__esModule', {
  4439. value: true
  4440. });
  4441. exports.PDFDocumentProperties = void 0;
  4442. var _ui_utils = __webpack_require__(3);
  4443. var _pdfjsLib = __webpack_require__(4);
  4444. const DEFAULT_FIELD_CONTENT = '-';
  4445. const NON_METRIC_LOCALES = ['en-us', 'en-lr', 'my'];
  4446. const US_PAGE_NAMES = {
  4447. '8.5x11': 'Letter',
  4448. '8.5x14': 'Legal'
  4449. };
  4450. const METRIC_PAGE_NAMES = {
  4451. '297x420': 'A3',
  4452. '210x297': 'A4'
  4453. };
  4454. function getPageName(size, isPortrait, pageNames) {
  4455. const width = isPortrait ? size.width : size.height;
  4456. const height = isPortrait ? size.height : size.width;
  4457. return pageNames[`${width}x${height}`];
  4458. }
  4459. class PDFDocumentProperties {
  4460. #fieldData = null;
  4461. constructor({ dialog, fields, closeButton }, overlayManager, eventBus, l10n, fileNameLookup) {
  4462. this.dialog = dialog;
  4463. this.fields = fields;
  4464. this.overlayManager = overlayManager;
  4465. this.l10n = l10n;
  4466. this._fileNameLookup = fileNameLookup;
  4467. this.#reset();
  4468. closeButton.addEventListener('click', this.close.bind(this));
  4469. this.overlayManager.register(this.dialog);
  4470. eventBus._on('pagechanging', (evt) => {
  4471. this._currentPageNumber = evt.pageNumber;
  4472. });
  4473. eventBus._on('rotationchanging', (evt) => {
  4474. this._pagesRotation = evt.pagesRotation;
  4475. });
  4476. this._isNonMetricLocale = true;
  4477. l10n.getLanguage().then((locale) => {
  4478. this._isNonMetricLocale = NON_METRIC_LOCALES.includes(locale);
  4479. });
  4480. }
  4481. async open() {
  4482. await Promise.all([this.overlayManager.open(this.dialog), this._dataAvailableCapability.promise]);
  4483. const currentPageNumber = this._currentPageNumber;
  4484. const pagesRotation = this._pagesRotation;
  4485. if (this.#fieldData && currentPageNumber === this.#fieldData._currentPageNumber && pagesRotation === this.#fieldData._pagesRotation) {
  4486. this.#updateUI();
  4487. return;
  4488. }
  4489. const { info, contentLength } = await this.pdfDocument.getMetadata();
  4490. const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([
  4491. this._fileNameLookup(),
  4492. this.#parseFileSize(contentLength),
  4493. this.#parseDate(info.CreationDate),
  4494. this.#parseDate(info.ModDate),
  4495. this.pdfDocument.getPage(currentPageNumber).then((pdfPage) => {
  4496. return this.#parsePageSize((0, _ui_utils.getPageSizeInches)(pdfPage), pagesRotation);
  4497. }),
  4498. this.#parseLinearization(info.IsLinearized)
  4499. ]);
  4500. this.#fieldData = Object.freeze({
  4501. fileName,
  4502. fileSize,
  4503. title: info.Title,
  4504. author: info.Author,
  4505. subject: info.Subject,
  4506. keywords: info.Keywords,
  4507. creationDate,
  4508. modificationDate,
  4509. creator: info.Creator,
  4510. producer: info.Producer,
  4511. version: info.PDFFormatVersion,
  4512. pageCount: this.pdfDocument.numPages,
  4513. pageSize,
  4514. linearized: isLinearized,
  4515. _currentPageNumber: currentPageNumber,
  4516. _pagesRotation: pagesRotation
  4517. });
  4518. this.#updateUI();
  4519. const { length } = await this.pdfDocument.getDownloadInfo();
  4520. if (contentLength === length) {
  4521. return;
  4522. }
  4523. const data = Object.assign(Object.create(null), this.#fieldData);
  4524. data.fileSize = await this.#parseFileSize(length);
  4525. this.#fieldData = Object.freeze(data);
  4526. this.#updateUI();
  4527. }
  4528. async close() {
  4529. this.overlayManager.close(this.dialog);
  4530. }
  4531. setDocument(pdfDocument) {
  4532. if (this.pdfDocument) {
  4533. this.#reset();
  4534. this.#updateUI(true);
  4535. }
  4536. if (!pdfDocument) {
  4537. return;
  4538. }
  4539. this.pdfDocument = pdfDocument;
  4540. this._dataAvailableCapability.resolve();
  4541. }
  4542. #reset() {
  4543. this.pdfDocument = null;
  4544. this.#fieldData = null;
  4545. this._dataAvailableCapability = new _pdfjsLib.PromiseCapability();
  4546. this._currentPageNumber = 1;
  4547. this._pagesRotation = 0;
  4548. }
  4549. #updateUI(reset = false) {
  4550. if (reset || !this.#fieldData) {
  4551. for (const id in this.fields) {
  4552. this.fields[id].textContent = DEFAULT_FIELD_CONTENT;
  4553. }
  4554. return;
  4555. }
  4556. if (this.overlayManager.active !== this.dialog) {
  4557. return;
  4558. }
  4559. for (const id in this.fields) {
  4560. const content = this.#fieldData[id];
  4561. this.fields[id].textContent = content || content === 0 ? content : DEFAULT_FIELD_CONTENT;
  4562. }
  4563. }
  4564. async #parseFileSize(fileSize = 0) {
  4565. const kb = fileSize / 1024,
  4566. mb = kb / 1024;
  4567. if (!kb) {
  4568. return undefined;
  4569. }
  4570. return this.l10n.get(`document_properties_${mb >= 1 ? 'mb' : 'kb'}`, {
  4571. size_mb: mb >= 1 && (+mb.toPrecision(3)).toLocaleString(),
  4572. size_kb: mb < 1 && (+kb.toPrecision(3)).toLocaleString(),
  4573. size_b: fileSize.toLocaleString()
  4574. });
  4575. }
  4576. async #parsePageSize(pageSizeInches, pagesRotation) {
  4577. if (!pageSizeInches) {
  4578. return undefined;
  4579. }
  4580. if (pagesRotation % 180 !== 0) {
  4581. pageSizeInches = {
  4582. width: pageSizeInches.height,
  4583. height: pageSizeInches.width
  4584. };
  4585. }
  4586. const isPortrait = (0, _ui_utils.isPortraitOrientation)(pageSizeInches);
  4587. let sizeInches = {
  4588. width: Math.round(pageSizeInches.width * 100) / 100,
  4589. height: Math.round(pageSizeInches.height * 100) / 100
  4590. };
  4591. let sizeMillimeters = {
  4592. width: Math.round(pageSizeInches.width * 25.4 * 10) / 10,
  4593. height: Math.round(pageSizeInches.height * 25.4 * 10) / 10
  4594. };
  4595. let rawName = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES);
  4596. if (!rawName && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) {
  4597. const exactMillimeters = {
  4598. width: pageSizeInches.width * 25.4,
  4599. height: pageSizeInches.height * 25.4
  4600. };
  4601. const intMillimeters = {
  4602. width: Math.round(sizeMillimeters.width),
  4603. height: Math.round(sizeMillimeters.height)
  4604. };
  4605. if (Math.abs(exactMillimeters.width - intMillimeters.width) < 0.1 && Math.abs(exactMillimeters.height - intMillimeters.height) < 0.1) {
  4606. rawName = getPageName(intMillimeters, isPortrait, METRIC_PAGE_NAMES);
  4607. if (rawName) {
  4608. sizeInches = {
  4609. width: Math.round((intMillimeters.width / 25.4) * 100) / 100,
  4610. height: Math.round((intMillimeters.height / 25.4) * 100) / 100
  4611. };
  4612. sizeMillimeters = intMillimeters;
  4613. }
  4614. }
  4615. }
  4616. const [{ width, height }, unit, name, orientation] = await Promise.all([
  4617. this._isNonMetricLocale ? sizeInches : sizeMillimeters,
  4618. this.l10n.get(`document_properties_page_size_unit_${this._isNonMetricLocale ? 'inches' : 'millimeters'}`),
  4619. rawName && this.l10n.get(`document_properties_page_size_name_${rawName.toLowerCase()}`),
  4620. this.l10n.get(`document_properties_page_size_orientation_${isPortrait ? 'portrait' : 'landscape'}`)
  4621. ]);
  4622. return this.l10n.get(`document_properties_page_size_dimension_${name ? 'name_' : ''}string`, {
  4623. width: width.toLocaleString(),
  4624. height: height.toLocaleString(),
  4625. unit,
  4626. name,
  4627. orientation
  4628. });
  4629. }
  4630. async #parseDate(inputDate) {
  4631. const dateObject = _pdfjsLib.PDFDateString.toDateObject(inputDate);
  4632. if (!dateObject) {
  4633. return undefined;
  4634. }
  4635. return this.l10n.get('document_properties_date_string', {
  4636. date: dateObject.toLocaleDateString(),
  4637. time: dateObject.toLocaleTimeString()
  4638. });
  4639. }
  4640. #parseLinearization(isLinearized) {
  4641. return this.l10n.get(`document_properties_linearized_${isLinearized ? 'yes' : 'no'}`);
  4642. }
  4643. }
  4644. exports.PDFDocumentProperties = PDFDocumentProperties;
  4645. /***/
  4646. },
  4647. /* 16 */
  4648. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  4649. Object.defineProperty(exports, '__esModule', {
  4650. value: true
  4651. });
  4652. exports.PDFFindBar = void 0;
  4653. var _pdf_find_controller = __webpack_require__(17);
  4654. var _ui_utils = __webpack_require__(3);
  4655. const MATCHES_COUNT_LIMIT = 1000;
  4656. class PDFFindBar {
  4657. constructor(options, eventBus, l10n) {
  4658. this.opened = false;
  4659. this.bar = options.bar;
  4660. this.toggleButton = options.toggleButton;
  4661. this.findField = options.findField;
  4662. this.highlightAll = options.highlightAllCheckbox;
  4663. this.caseSensitive = options.caseSensitiveCheckbox;
  4664. this.matchDiacritics = options.matchDiacriticsCheckbox;
  4665. this.entireWord = options.entireWordCheckbox;
  4666. this.findMsg = options.findMsg;
  4667. this.findResultsCount = options.findResultsCount;
  4668. this.findPreviousButton = options.findPreviousButton;
  4669. this.findNextButton = options.findNextButton;
  4670. this.eventBus = eventBus;
  4671. this.l10n = l10n;
  4672. this.toggleButton.addEventListener('click', () => {
  4673. this.toggle();
  4674. });
  4675. this.findField.addEventListener('input', () => {
  4676. this.dispatchEvent('');
  4677. });
  4678. this.bar.addEventListener('keydown', (e) => {
  4679. switch (e.keyCode) {
  4680. case 13:
  4681. if (e.target === this.findField) {
  4682. this.dispatchEvent('again', e.shiftKey);
  4683. }
  4684. break;
  4685. case 27:
  4686. this.close();
  4687. break;
  4688. }
  4689. });
  4690. this.findPreviousButton.addEventListener('click', () => {
  4691. this.dispatchEvent('again', true);
  4692. });
  4693. this.findNextButton.addEventListener('click', () => {
  4694. this.dispatchEvent('again', false);
  4695. });
  4696. this.highlightAll.addEventListener('click', () => {
  4697. this.dispatchEvent('highlightallchange');
  4698. });
  4699. this.caseSensitive.addEventListener('click', () => {
  4700. this.dispatchEvent('casesensitivitychange');
  4701. });
  4702. this.entireWord.addEventListener('click', () => {
  4703. this.dispatchEvent('entirewordchange');
  4704. });
  4705. this.matchDiacritics.addEventListener('click', () => {
  4706. this.dispatchEvent('diacriticmatchingchange');
  4707. });
  4708. this.eventBus._on('resize', this.#adjustWidth.bind(this));
  4709. }
  4710. reset() {
  4711. this.updateUIState();
  4712. }
  4713. dispatchEvent(type, findPrev = false) {
  4714. this.eventBus.dispatch('find', {
  4715. source: this,
  4716. type,
  4717. query: this.findField.value,
  4718. caseSensitive: this.caseSensitive.checked,
  4719. entireWord: this.entireWord.checked,
  4720. highlightAll: this.highlightAll.checked,
  4721. findPrevious: findPrev,
  4722. matchDiacritics: this.matchDiacritics.checked
  4723. });
  4724. }
  4725. updateUIState(state, previous, matchesCount) {
  4726. let findMsg = Promise.resolve('');
  4727. let status = '';
  4728. switch (state) {
  4729. case _pdf_find_controller.FindState.FOUND:
  4730. break;
  4731. case _pdf_find_controller.FindState.PENDING:
  4732. status = 'pending';
  4733. break;
  4734. case _pdf_find_controller.FindState.NOT_FOUND:
  4735. findMsg = this.l10n.get('find_not_found');
  4736. status = 'notFound';
  4737. break;
  4738. case _pdf_find_controller.FindState.WRAPPED:
  4739. findMsg = this.l10n.get(`find_reached_${previous ? 'top' : 'bottom'}`);
  4740. break;
  4741. }
  4742. this.findField.setAttribute('data-status', status);
  4743. this.findField.setAttribute('aria-invalid', state === _pdf_find_controller.FindState.NOT_FOUND);
  4744. findMsg.then((msg) => {
  4745. this.findMsg.setAttribute('data-status', status);
  4746. this.findMsg.textContent = msg;
  4747. this.#adjustWidth();
  4748. });
  4749. this.updateResultsCount(matchesCount);
  4750. }
  4751. updateResultsCount({ current = 0, total = 0 } = {}) {
  4752. const limit = MATCHES_COUNT_LIMIT;
  4753. let matchCountMsg = Promise.resolve('');
  4754. if (total > 0) {
  4755. if (total > limit) {
  4756. let key = 'find_match_count_limit';
  4757. matchCountMsg = this.l10n.get(key, {
  4758. limit
  4759. });
  4760. } else {
  4761. let key = 'find_match_count';
  4762. matchCountMsg = this.l10n.get(key, {
  4763. current,
  4764. total
  4765. });
  4766. }
  4767. }
  4768. matchCountMsg.then((msg) => {
  4769. this.findResultsCount.textContent = msg;
  4770. this.#adjustWidth();
  4771. });
  4772. }
  4773. open() {
  4774. if (!this.opened) {
  4775. this.opened = true;
  4776. (0, _ui_utils.toggleExpandedBtn)(this.toggleButton, true, this.bar);
  4777. }
  4778. this.findField.select();
  4779. this.findField.focus();
  4780. this.#adjustWidth();
  4781. }
  4782. close() {
  4783. if (!this.opened) {
  4784. return;
  4785. }
  4786. this.opened = false;
  4787. (0, _ui_utils.toggleExpandedBtn)(this.toggleButton, false, this.bar);
  4788. this.eventBus.dispatch('findbarclose', {
  4789. source: this
  4790. });
  4791. }
  4792. toggle() {
  4793. if (this.opened) {
  4794. this.close();
  4795. } else {
  4796. this.open();
  4797. }
  4798. }
  4799. #adjustWidth() {
  4800. if (!this.opened) {
  4801. return;
  4802. }
  4803. this.bar.classList.remove('wrapContainers');
  4804. const findbarHeight = this.bar.clientHeight;
  4805. const inputContainerHeight = this.bar.firstElementChild.clientHeight;
  4806. if (findbarHeight > inputContainerHeight) {
  4807. this.bar.classList.add('wrapContainers');
  4808. }
  4809. }
  4810. }
  4811. exports.PDFFindBar = PDFFindBar;
  4812. /***/
  4813. },
  4814. /* 17 */
  4815. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  4816. Object.defineProperty(exports, '__esModule', {
  4817. value: true
  4818. });
  4819. exports.PDFFindController = exports.FindState = void 0;
  4820. var _ui_utils = __webpack_require__(3);
  4821. var _pdf_find_utils = __webpack_require__(18);
  4822. var _pdfjsLib = __webpack_require__(4);
  4823. const FindState = {
  4824. FOUND: 0,
  4825. NOT_FOUND: 1,
  4826. WRAPPED: 2,
  4827. PENDING: 3
  4828. };
  4829. exports.FindState = FindState;
  4830. const FIND_TIMEOUT = 250;
  4831. const MATCH_SCROLL_OFFSET_TOP = -50;
  4832. const MATCH_SCROLL_OFFSET_LEFT = -400;
  4833. const CHARACTERS_TO_NORMALIZE = {
  4834. '\u2010': '-',
  4835. '\u2018': "'",
  4836. '\u2019': "'",
  4837. '\u201A': "'",
  4838. '\u201B': "'",
  4839. '\u201C': '"',
  4840. '\u201D': '"',
  4841. '\u201E': '"',
  4842. '\u201F': '"',
  4843. '\u00BC': '1/4',
  4844. '\u00BD': '1/2',
  4845. '\u00BE': '3/4'
  4846. };
  4847. const DIACRITICS_EXCEPTION = new Set([
  4848. 0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84,
  4849. 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0,
  4850. 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74
  4851. ]);
  4852. let DIACRITICS_EXCEPTION_STR;
  4853. const DIACRITICS_REG_EXP = /\p{M}+/gu;
  4854. const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu;
  4855. const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u;
  4856. const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u;
  4857. const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g;
  4858. const SYLLABLES_LENGTHS = new Map();
  4859. const FIRST_CHAR_SYLLABLES_REG_EXP = '[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]';
  4860. const NFKC_CHARS_TO_NORMALIZE = new Map();
  4861. let noSyllablesRegExp = null;
  4862. let withSyllablesRegExp = null;
  4863. function normalize(text) {
  4864. const syllablePositions = [];
  4865. let m;
  4866. while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) {
  4867. let { index } = m;
  4868. for (const char of m[0]) {
  4869. let len = SYLLABLES_LENGTHS.get(char);
  4870. if (!len) {
  4871. len = char.normalize('NFD').length;
  4872. SYLLABLES_LENGTHS.set(char, len);
  4873. }
  4874. syllablePositions.push([len, index++]);
  4875. }
  4876. }
  4877. let normalizationRegex;
  4878. if (syllablePositions.length === 0 && noSyllablesRegExp) {
  4879. normalizationRegex = noSyllablesRegExp;
  4880. } else if (syllablePositions.length > 0 && withSyllablesRegExp) {
  4881. normalizationRegex = withSyllablesRegExp;
  4882. } else {
  4883. const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join('');
  4884. const toNormalizeWithNFKC = (0, _pdf_find_utils.getNormalizeWithNFKC)();
  4885. const CJK = '(?:\\p{Ideographic}|[\u3040-\u30FF])';
  4886. const HKDiacritics = '(?:\u3099|\u309A)';
  4887. const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(\\S-\\n)|(${CJK}\\n)|(\\n)`;
  4888. if (syllablePositions.length === 0) {
  4889. normalizationRegex = noSyllablesRegExp = new RegExp(regexp + '|(\\u0000)', 'gum');
  4890. } else {
  4891. normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, 'gum');
  4892. }
  4893. }
  4894. const rawDiacriticsPositions = [];
  4895. while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) {
  4896. rawDiacriticsPositions.push([m[0].length, m.index]);
  4897. }
  4898. let normalized = text.normalize('NFD');
  4899. const positions = [[0, 0]];
  4900. let rawDiacriticsIndex = 0;
  4901. let syllableIndex = 0;
  4902. let shift = 0;
  4903. let shiftOrigin = 0;
  4904. let eol = 0;
  4905. let hasDiacritics = false;
  4906. normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, i) => {
  4907. i -= shiftOrigin;
  4908. if (p1) {
  4909. const replacement = CHARACTERS_TO_NORMALIZE[p1];
  4910. const jj = replacement.length;
  4911. for (let j = 1; j < jj; j++) {
  4912. positions.push([i - shift + j, shift - j]);
  4913. }
  4914. shift -= jj - 1;
  4915. return replacement;
  4916. }
  4917. if (p2) {
  4918. let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2);
  4919. if (!replacement) {
  4920. replacement = p2.normalize('NFKC');
  4921. NFKC_CHARS_TO_NORMALIZE.set(p2, replacement);
  4922. }
  4923. const jj = replacement.length;
  4924. for (let j = 1; j < jj; j++) {
  4925. positions.push([i - shift + j, shift - j]);
  4926. }
  4927. shift -= jj - 1;
  4928. return replacement;
  4929. }
  4930. if (p3) {
  4931. hasDiacritics = true;
  4932. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  4933. ++rawDiacriticsIndex;
  4934. } else {
  4935. positions.push([i - 1 - shift + 1, shift - 1]);
  4936. shift -= 1;
  4937. shiftOrigin += 1;
  4938. }
  4939. positions.push([i - shift + 1, shift]);
  4940. shiftOrigin += 1;
  4941. eol += 1;
  4942. return p3.charAt(0);
  4943. }
  4944. if (p4) {
  4945. const hasTrailingDashEOL = p4.endsWith('\n');
  4946. const len = hasTrailingDashEOL ? p4.length - 2 : p4.length;
  4947. hasDiacritics = true;
  4948. let jj = len;
  4949. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  4950. jj -= rawDiacriticsPositions[rawDiacriticsIndex][0];
  4951. ++rawDiacriticsIndex;
  4952. }
  4953. for (let j = 1; j <= jj; j++) {
  4954. positions.push([i - 1 - shift + j, shift - j]);
  4955. }
  4956. shift -= jj;
  4957. shiftOrigin += jj;
  4958. if (hasTrailingDashEOL) {
  4959. i += len - 1;
  4960. positions.push([i - shift + 1, 1 + shift]);
  4961. shift += 1;
  4962. shiftOrigin += 1;
  4963. eol += 1;
  4964. return p4.slice(0, len);
  4965. }
  4966. return p4;
  4967. }
  4968. if (p5) {
  4969. const len = p5.length - 2;
  4970. positions.push([i - shift + len, 1 + shift]);
  4971. shift += 1;
  4972. shiftOrigin += 1;
  4973. eol += 1;
  4974. return p5.slice(0, -2);
  4975. }
  4976. if (p6) {
  4977. const len = p6.length - 1;
  4978. positions.push([i - shift + len, shift]);
  4979. shiftOrigin += 1;
  4980. eol += 1;
  4981. return p6.slice(0, -1);
  4982. }
  4983. if (p7) {
  4984. positions.push([i - shift + 1, shift - 1]);
  4985. shift -= 1;
  4986. shiftOrigin += 1;
  4987. eol += 1;
  4988. return ' ';
  4989. }
  4990. if (i + eol === syllablePositions[syllableIndex]?.[1]) {
  4991. const newCharLen = syllablePositions[syllableIndex][0] - 1;
  4992. ++syllableIndex;
  4993. for (let j = 1; j <= newCharLen; j++) {
  4994. positions.push([i - (shift - j), shift - j]);
  4995. }
  4996. shift -= newCharLen;
  4997. shiftOrigin += newCharLen;
  4998. }
  4999. return p8;
  5000. });
  5001. positions.push([normalized.length, shift]);
  5002. return [normalized, positions, hasDiacritics];
  5003. }
  5004. function getOriginalIndex(diffs, pos, len) {
  5005. if (!diffs) {
  5006. return [pos, len];
  5007. }
  5008. const start = pos;
  5009. const end = pos + len - 1;
  5010. let i = (0, _ui_utils.binarySearchFirstItem)(diffs, (x) => x[0] >= start);
  5011. if (diffs[i][0] > start) {
  5012. --i;
  5013. }
  5014. let j = (0, _ui_utils.binarySearchFirstItem)(diffs, (x) => x[0] >= end, i);
  5015. if (diffs[j][0] > end) {
  5016. --j;
  5017. }
  5018. const oldStart = start + diffs[i][1];
  5019. const oldEnd = end + diffs[j][1];
  5020. const oldLen = oldEnd + 1 - oldStart;
  5021. return [oldStart, oldLen];
  5022. }
  5023. class PDFFindController {
  5024. #state = null;
  5025. #updateMatchesCountOnProgress = true;
  5026. #visitedPagesCount = 0;
  5027. constructor({ linkService, eventBus, updateMatchesCountOnProgress = true }) {
  5028. this._linkService = linkService;
  5029. this._eventBus = eventBus;
  5030. this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress;
  5031. this.onIsPageVisible = null;
  5032. this.#reset();
  5033. eventBus._on('find', this.#onFind.bind(this));
  5034. eventBus._on('findbarclose', this.#onFindBarClose.bind(this));
  5035. }
  5036. get highlightMatches() {
  5037. return this._highlightMatches;
  5038. }
  5039. get pageMatches() {
  5040. return this._pageMatches;
  5041. }
  5042. get pageMatchesLength() {
  5043. return this._pageMatchesLength;
  5044. }
  5045. get selected() {
  5046. return this._selected;
  5047. }
  5048. get state() {
  5049. return this.#state;
  5050. }
  5051. setDocument(pdfDocument) {
  5052. if (this._pdfDocument) {
  5053. this.#reset();
  5054. }
  5055. if (!pdfDocument) {
  5056. return;
  5057. }
  5058. this._pdfDocument = pdfDocument;
  5059. this._firstPageCapability.resolve();
  5060. }
  5061. #onFind(state) {
  5062. if (!state) {
  5063. return;
  5064. }
  5065. if (state.phraseSearch === false) {
  5066. console.error('The `phraseSearch`-parameter was removed, please provide ' + 'an Array of strings in the `query`-parameter instead.');
  5067. if (typeof state.query === 'string') {
  5068. state.query = state.query.match(/\S+/g);
  5069. }
  5070. }
  5071. const pdfDocument = this._pdfDocument;
  5072. const { type } = state;
  5073. if (this.#state === null || this.#shouldDirtyMatch(state)) {
  5074. this._dirtyMatch = true;
  5075. }
  5076. this.#state = state;
  5077. if (type !== 'highlightallchange') {
  5078. this.#updateUIState(FindState.PENDING);
  5079. }
  5080. this._firstPageCapability.promise.then(() => {
  5081. if (!this._pdfDocument || (pdfDocument && this._pdfDocument !== pdfDocument)) {
  5082. return;
  5083. }
  5084. this.#extractText();
  5085. const findbarClosed = !this._highlightMatches;
  5086. const pendingTimeout = !!this._findTimeout;
  5087. if (this._findTimeout) {
  5088. clearTimeout(this._findTimeout);
  5089. this._findTimeout = null;
  5090. }
  5091. if (!type) {
  5092. this._findTimeout = setTimeout(() => {
  5093. this.#nextMatch();
  5094. this._findTimeout = null;
  5095. }, FIND_TIMEOUT);
  5096. } else if (this._dirtyMatch) {
  5097. this.#nextMatch();
  5098. } else if (type === 'again') {
  5099. this.#nextMatch();
  5100. if (findbarClosed && this.#state.highlightAll) {
  5101. this.#updateAllPages();
  5102. }
  5103. } else if (type === 'highlightallchange') {
  5104. if (pendingTimeout) {
  5105. this.#nextMatch();
  5106. } else {
  5107. this._highlightMatches = true;
  5108. }
  5109. this.#updateAllPages();
  5110. } else {
  5111. this.#nextMatch();
  5112. }
  5113. });
  5114. }
  5115. scrollMatchIntoView({ element = null, selectedLeft = 0, pageIndex = -1, matchIndex = -1 }) {
  5116. if (!this._scrollMatches || !element) {
  5117. return;
  5118. } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) {
  5119. return;
  5120. } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) {
  5121. return;
  5122. }
  5123. this._scrollMatches = false;
  5124. const spot = {
  5125. top: MATCH_SCROLL_OFFSET_TOP,
  5126. left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT
  5127. };
  5128. (0, _ui_utils.scrollIntoView)(element, spot, true);
  5129. }
  5130. #reset() {
  5131. this._highlightMatches = false;
  5132. this._scrollMatches = false;
  5133. this._pdfDocument = null;
  5134. this._pageMatches = [];
  5135. this._pageMatchesLength = [];
  5136. this.#visitedPagesCount = 0;
  5137. this.#state = null;
  5138. this._selected = {
  5139. pageIdx: -1,
  5140. matchIdx: -1
  5141. };
  5142. this._offset = {
  5143. pageIdx: null,
  5144. matchIdx: null,
  5145. wrapped: false
  5146. };
  5147. this._extractTextPromises = [];
  5148. this._pageContents = [];
  5149. this._pageDiffs = [];
  5150. this._hasDiacritics = [];
  5151. this._matchesCountTotal = 0;
  5152. this._pagesToSearch = null;
  5153. this._pendingFindMatches = new Set();
  5154. this._resumePageIdx = null;
  5155. this._dirtyMatch = false;
  5156. clearTimeout(this._findTimeout);
  5157. this._findTimeout = null;
  5158. this._firstPageCapability = new _pdfjsLib.PromiseCapability();
  5159. }
  5160. get #query() {
  5161. const { query } = this.#state;
  5162. if (typeof query === 'string') {
  5163. if (query !== this._rawQuery) {
  5164. this._rawQuery = query;
  5165. [this._normalizedQuery] = normalize(query);
  5166. }
  5167. return this._normalizedQuery;
  5168. }
  5169. return (query || []).filter((q) => !!q).map((q) => normalize(q)[0]);
  5170. }
  5171. #shouldDirtyMatch(state) {
  5172. const newQuery = state.query,
  5173. prevQuery = this.#state.query;
  5174. const newType = typeof newQuery,
  5175. prevType = typeof prevQuery;
  5176. if (newType !== prevType) {
  5177. return true;
  5178. }
  5179. if (newType === 'string') {
  5180. if (newQuery !== prevQuery) {
  5181. return true;
  5182. }
  5183. } else {
  5184. if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) {
  5185. return true;
  5186. }
  5187. }
  5188. switch (state.type) {
  5189. case 'again':
  5190. const pageNumber = this._selected.pageIdx + 1;
  5191. const linkService = this._linkService;
  5192. return (
  5193. pageNumber >= 1 &&
  5194. pageNumber <= linkService.pagesCount &&
  5195. pageNumber !== linkService.page &&
  5196. !(this.onIsPageVisible?.(pageNumber) ?? true)
  5197. );
  5198. case 'highlightallchange':
  5199. return false;
  5200. }
  5201. return true;
  5202. }
  5203. #isEntireWord(content, startIdx, length) {
  5204. let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP);
  5205. if (match) {
  5206. const first = content.charCodeAt(startIdx);
  5207. const limit = match[1].charCodeAt(0);
  5208. if ((0, _pdf_find_utils.getCharacterType)(first) === (0, _pdf_find_utils.getCharacterType)(limit)) {
  5209. return false;
  5210. }
  5211. }
  5212. match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP);
  5213. if (match) {
  5214. const last = content.charCodeAt(startIdx + length - 1);
  5215. const limit = match[1].charCodeAt(0);
  5216. if ((0, _pdf_find_utils.getCharacterType)(last) === (0, _pdf_find_utils.getCharacterType)(limit)) {
  5217. return false;
  5218. }
  5219. }
  5220. return true;
  5221. }
  5222. #calculateRegExpMatch(query, entireWord, pageIndex, pageContent) {
  5223. const matches = (this._pageMatches[pageIndex] = []);
  5224. const matchesLength = (this._pageMatchesLength[pageIndex] = []);
  5225. if (!query) {
  5226. return;
  5227. }
  5228. const diffs = this._pageDiffs[pageIndex];
  5229. let match;
  5230. while ((match = query.exec(pageContent)) !== null) {
  5231. if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) {
  5232. continue;
  5233. }
  5234. const [matchPos, matchLen] = getOriginalIndex(diffs, match.index, match[0].length);
  5235. if (matchLen) {
  5236. matches.push(matchPos);
  5237. matchesLength.push(matchLen);
  5238. }
  5239. }
  5240. }
  5241. #convertToRegExpString(query, hasDiacritics) {
  5242. const { matchDiacritics } = this.#state;
  5243. let isUnicode = false;
  5244. query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => {
  5245. if (p1) {
  5246. return `[ ]*\\${p1}[ ]*`;
  5247. }
  5248. if (p2) {
  5249. return `[ ]*${p2}[ ]*`;
  5250. }
  5251. if (p3) {
  5252. return '[ ]+';
  5253. }
  5254. if (matchDiacritics) {
  5255. return p4 || p5;
  5256. }
  5257. if (p4) {
  5258. return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : '';
  5259. }
  5260. if (hasDiacritics) {
  5261. isUnicode = true;
  5262. return `${p5}\\p{M}*`;
  5263. }
  5264. return p5;
  5265. });
  5266. const trailingSpaces = '[ ]*';
  5267. if (query.endsWith(trailingSpaces)) {
  5268. query = query.slice(0, query.length - trailingSpaces.length);
  5269. }
  5270. if (matchDiacritics) {
  5271. if (hasDiacritics) {
  5272. DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION);
  5273. isUnicode = true;
  5274. query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`;
  5275. }
  5276. }
  5277. return [isUnicode, query];
  5278. }
  5279. #calculateMatch(pageIndex) {
  5280. let query = this.#query;
  5281. if (query.length === 0) {
  5282. return;
  5283. }
  5284. const { caseSensitive, entireWord } = this.#state;
  5285. const pageContent = this._pageContents[pageIndex];
  5286. const hasDiacritics = this._hasDiacritics[pageIndex];
  5287. let isUnicode = false;
  5288. if (typeof query === 'string') {
  5289. [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics);
  5290. } else {
  5291. query = query
  5292. .sort()
  5293. .reverse()
  5294. .map((q) => {
  5295. const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics);
  5296. isUnicode ||= isUnicodePart;
  5297. return `(${queryPart})`;
  5298. })
  5299. .join('|');
  5300. }
  5301. const flags = `g${isUnicode ? 'u' : ''}${caseSensitive ? '' : 'i'}`;
  5302. query = query ? new RegExp(query, flags) : null;
  5303. this.#calculateRegExpMatch(query, entireWord, pageIndex, pageContent);
  5304. if (this.#state.highlightAll) {
  5305. this.#updatePage(pageIndex);
  5306. }
  5307. if (this._resumePageIdx === pageIndex) {
  5308. this._resumePageIdx = null;
  5309. this.#nextPageMatch();
  5310. }
  5311. const pageMatchesCount = this._pageMatches[pageIndex].length;
  5312. this._matchesCountTotal += pageMatchesCount;
  5313. if (this.#updateMatchesCountOnProgress) {
  5314. if (pageMatchesCount > 0) {
  5315. this.#updateUIResultsCount();
  5316. }
  5317. } else if (++this.#visitedPagesCount === this._linkService.pagesCount) {
  5318. this.#updateUIResultsCount();
  5319. }
  5320. }
  5321. #extractText() {
  5322. if (this._extractTextPromises.length > 0) {
  5323. return;
  5324. }
  5325. let promise = Promise.resolve();
  5326. const textOptions = {
  5327. disableNormalization: true
  5328. };
  5329. for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) {
  5330. const extractTextCapability = new _pdfjsLib.PromiseCapability();
  5331. this._extractTextPromises[i] = extractTextCapability.promise;
  5332. promise = promise.then(() => {
  5333. return this._pdfDocument
  5334. .getPage(i + 1)
  5335. .then((pdfPage) => {
  5336. return pdfPage.getTextContent(textOptions);
  5337. })
  5338. .then(
  5339. (textContent) => {
  5340. const strBuf = [];
  5341. for (const textItem of textContent.items) {
  5342. strBuf.push(textItem.str);
  5343. if (textItem.hasEOL) {
  5344. strBuf.push('\n');
  5345. }
  5346. }
  5347. [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join(''));
  5348. extractTextCapability.resolve();
  5349. },
  5350. (reason) => {
  5351. console.error(`Unable to get text content for page ${i + 1}`, reason);
  5352. this._pageContents[i] = '';
  5353. this._pageDiffs[i] = null;
  5354. this._hasDiacritics[i] = false;
  5355. extractTextCapability.resolve();
  5356. }
  5357. );
  5358. });
  5359. }
  5360. }
  5361. #updatePage(index) {
  5362. if (this._scrollMatches && this._selected.pageIdx === index) {
  5363. this._linkService.page = index + 1;
  5364. }
  5365. this._eventBus.dispatch('updatetextlayermatches', {
  5366. source: this,
  5367. pageIndex: index
  5368. });
  5369. }
  5370. #updateAllPages() {
  5371. this._eventBus.dispatch('updatetextlayermatches', {
  5372. source: this,
  5373. pageIndex: -1
  5374. });
  5375. }
  5376. #nextMatch() {
  5377. const previous = this.#state.findPrevious;
  5378. const currentPageIndex = this._linkService.page - 1;
  5379. const numPages = this._linkService.pagesCount;
  5380. this._highlightMatches = true;
  5381. if (this._dirtyMatch) {
  5382. this._dirtyMatch = false;
  5383. this._selected.pageIdx = this._selected.matchIdx = -1;
  5384. this._offset.pageIdx = currentPageIndex;
  5385. this._offset.matchIdx = null;
  5386. this._offset.wrapped = false;
  5387. this._resumePageIdx = null;
  5388. this._pageMatches.length = 0;
  5389. this._pageMatchesLength.length = 0;
  5390. this.#visitedPagesCount = 0;
  5391. this._matchesCountTotal = 0;
  5392. this.#updateAllPages();
  5393. for (let i = 0; i < numPages; i++) {
  5394. if (this._pendingFindMatches.has(i)) {
  5395. continue;
  5396. }
  5397. this._pendingFindMatches.add(i);
  5398. this._extractTextPromises[i].then(() => {
  5399. this._pendingFindMatches.delete(i);
  5400. this.#calculateMatch(i);
  5401. });
  5402. }
  5403. }
  5404. const query = this.#query;
  5405. if (query.length === 0) {
  5406. this.#updateUIState(FindState.FOUND);
  5407. return;
  5408. }
  5409. if (this._resumePageIdx) {
  5410. return;
  5411. }
  5412. const offset = this._offset;
  5413. this._pagesToSearch = numPages;
  5414. if (offset.matchIdx !== null) {
  5415. const numPageMatches = this._pageMatches[offset.pageIdx].length;
  5416. if ((!previous && offset.matchIdx + 1 < numPageMatches) || (previous && offset.matchIdx > 0)) {
  5417. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  5418. this.#updateMatch(true);
  5419. return;
  5420. }
  5421. this.#advanceOffsetPage(previous);
  5422. }
  5423. this.#nextPageMatch();
  5424. }
  5425. #matchesReady(matches) {
  5426. const offset = this._offset;
  5427. const numMatches = matches.length;
  5428. const previous = this.#state.findPrevious;
  5429. if (numMatches) {
  5430. offset.matchIdx = previous ? numMatches - 1 : 0;
  5431. this.#updateMatch(true);
  5432. return true;
  5433. }
  5434. this.#advanceOffsetPage(previous);
  5435. if (offset.wrapped) {
  5436. offset.matchIdx = null;
  5437. if (this._pagesToSearch < 0) {
  5438. this.#updateMatch(false);
  5439. return true;
  5440. }
  5441. }
  5442. return false;
  5443. }
  5444. #nextPageMatch() {
  5445. if (this._resumePageIdx !== null) {
  5446. console.error('There can only be one pending page.');
  5447. }
  5448. let matches = null;
  5449. do {
  5450. const pageIdx = this._offset.pageIdx;
  5451. matches = this._pageMatches[pageIdx];
  5452. if (!matches) {
  5453. this._resumePageIdx = pageIdx;
  5454. break;
  5455. }
  5456. } while (!this.#matchesReady(matches));
  5457. }
  5458. #advanceOffsetPage(previous) {
  5459. const offset = this._offset;
  5460. const numPages = this._linkService.pagesCount;
  5461. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  5462. offset.matchIdx = null;
  5463. this._pagesToSearch--;
  5464. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  5465. offset.pageIdx = previous ? numPages - 1 : 0;
  5466. offset.wrapped = true;
  5467. }
  5468. }
  5469. #updateMatch(found = false) {
  5470. let state = FindState.NOT_FOUND;
  5471. const wrapped = this._offset.wrapped;
  5472. this._offset.wrapped = false;
  5473. if (found) {
  5474. const previousPage = this._selected.pageIdx;
  5475. this._selected.pageIdx = this._offset.pageIdx;
  5476. this._selected.matchIdx = this._offset.matchIdx;
  5477. state = wrapped ? FindState.WRAPPED : FindState.FOUND;
  5478. if (previousPage !== -1 && previousPage !== this._selected.pageIdx) {
  5479. this.#updatePage(previousPage);
  5480. }
  5481. }
  5482. this.#updateUIState(state, this.#state.findPrevious);
  5483. if (this._selected.pageIdx !== -1) {
  5484. this._scrollMatches = true;
  5485. this.#updatePage(this._selected.pageIdx);
  5486. }
  5487. }
  5488. #onFindBarClose(evt) {
  5489. const pdfDocument = this._pdfDocument;
  5490. this._firstPageCapability.promise.then(() => {
  5491. if (!this._pdfDocument || (pdfDocument && this._pdfDocument !== pdfDocument)) {
  5492. return;
  5493. }
  5494. if (this._findTimeout) {
  5495. clearTimeout(this._findTimeout);
  5496. this._findTimeout = null;
  5497. }
  5498. if (this._resumePageIdx) {
  5499. this._resumePageIdx = null;
  5500. this._dirtyMatch = true;
  5501. }
  5502. this.#updateUIState(FindState.FOUND);
  5503. this._highlightMatches = false;
  5504. this.#updateAllPages();
  5505. });
  5506. }
  5507. #requestMatchesCount() {
  5508. const { pageIdx, matchIdx } = this._selected;
  5509. let current = 0,
  5510. total = this._matchesCountTotal;
  5511. if (matchIdx !== -1) {
  5512. for (let i = 0; i < pageIdx; i++) {
  5513. current += this._pageMatches[i]?.length || 0;
  5514. }
  5515. current += matchIdx + 1;
  5516. }
  5517. if (current < 1 || current > total) {
  5518. current = total = 0;
  5519. }
  5520. return {
  5521. current,
  5522. total
  5523. };
  5524. }
  5525. #updateUIResultsCount() {
  5526. this._eventBus.dispatch('updatefindmatchescount', {
  5527. source: this,
  5528. matchesCount: this.#requestMatchesCount()
  5529. });
  5530. }
  5531. #updateUIState(state, previous = false) {
  5532. if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) {
  5533. return;
  5534. }
  5535. this._eventBus.dispatch('updatefindcontrolstate', {
  5536. source: this,
  5537. state,
  5538. previous,
  5539. matchesCount: this.#requestMatchesCount(),
  5540. rawQuery: this.#state?.query ?? null
  5541. });
  5542. }
  5543. }
  5544. exports.PDFFindController = PDFFindController;
  5545. /***/
  5546. },
  5547. /* 18 */
  5548. /***/ (__unused_webpack_module, exports) => {
  5549. Object.defineProperty(exports, '__esModule', {
  5550. value: true
  5551. });
  5552. exports.CharacterType = void 0;
  5553. exports.getCharacterType = getCharacterType;
  5554. exports.getNormalizeWithNFKC = getNormalizeWithNFKC;
  5555. const CharacterType = {
  5556. SPACE: 0,
  5557. ALPHA_LETTER: 1,
  5558. PUNCT: 2,
  5559. HAN_LETTER: 3,
  5560. KATAKANA_LETTER: 4,
  5561. HIRAGANA_LETTER: 5,
  5562. HALFWIDTH_KATAKANA_LETTER: 6,
  5563. THAI_LETTER: 7
  5564. };
  5565. exports.CharacterType = CharacterType;
  5566. function isAlphabeticalScript(charCode) {
  5567. return charCode < 0x2e80;
  5568. }
  5569. function isAscii(charCode) {
  5570. return (charCode & 0xff80) === 0;
  5571. }
  5572. function isAsciiAlpha(charCode) {
  5573. return (charCode >= 0x61 && charCode <= 0x7a) || (charCode >= 0x41 && charCode <= 0x5a);
  5574. }
  5575. function isAsciiDigit(charCode) {
  5576. return charCode >= 0x30 && charCode <= 0x39;
  5577. }
  5578. function isAsciiSpace(charCode) {
  5579. return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a;
  5580. }
  5581. function isHan(charCode) {
  5582. return (charCode >= 0x3400 && charCode <= 0x9fff) || (charCode >= 0xf900 && charCode <= 0xfaff);
  5583. }
  5584. function isKatakana(charCode) {
  5585. return charCode >= 0x30a0 && charCode <= 0x30ff;
  5586. }
  5587. function isHiragana(charCode) {
  5588. return charCode >= 0x3040 && charCode <= 0x309f;
  5589. }
  5590. function isHalfwidthKatakana(charCode) {
  5591. return charCode >= 0xff60 && charCode <= 0xff9f;
  5592. }
  5593. function isThai(charCode) {
  5594. return (charCode & 0xff80) === 0x0e00;
  5595. }
  5596. function getCharacterType(charCode) {
  5597. if (isAlphabeticalScript(charCode)) {
  5598. if (isAscii(charCode)) {
  5599. if (isAsciiSpace(charCode)) {
  5600. return CharacterType.SPACE;
  5601. } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) {
  5602. return CharacterType.ALPHA_LETTER;
  5603. }
  5604. return CharacterType.PUNCT;
  5605. } else if (isThai(charCode)) {
  5606. return CharacterType.THAI_LETTER;
  5607. } else if (charCode === 0xa0) {
  5608. return CharacterType.SPACE;
  5609. }
  5610. return CharacterType.ALPHA_LETTER;
  5611. }
  5612. if (isHan(charCode)) {
  5613. return CharacterType.HAN_LETTER;
  5614. } else if (isKatakana(charCode)) {
  5615. return CharacterType.KATAKANA_LETTER;
  5616. } else if (isHiragana(charCode)) {
  5617. return CharacterType.HIRAGANA_LETTER;
  5618. } else if (isHalfwidthKatakana(charCode)) {
  5619. return CharacterType.HALFWIDTH_KATAKANA_LETTER;
  5620. }
  5621. return CharacterType.ALPHA_LETTER;
  5622. }
  5623. let NormalizeWithNFKC;
  5624. function getNormalizeWithNFKC() {
  5625. NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`;
  5626. return NormalizeWithNFKC;
  5627. }
  5628. /***/
  5629. },
  5630. /* 19 */
  5631. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  5632. Object.defineProperty(exports, '__esModule', {
  5633. value: true
  5634. });
  5635. exports.PDFHistory = void 0;
  5636. exports.isDestArraysEqual = isDestArraysEqual;
  5637. exports.isDestHashesEqual = isDestHashesEqual;
  5638. var _ui_utils = __webpack_require__(3);
  5639. var _event_utils = __webpack_require__(6);
  5640. const HASH_CHANGE_TIMEOUT = 1000;
  5641. const POSITION_UPDATED_THRESHOLD = 50;
  5642. const UPDATE_VIEWAREA_TIMEOUT = 1000;
  5643. function getCurrentHash() {
  5644. return document.location.hash;
  5645. }
  5646. class PDFHistory {
  5647. constructor({ linkService, eventBus }) {
  5648. this.linkService = linkService;
  5649. this.eventBus = eventBus;
  5650. this._initialized = false;
  5651. this._fingerprint = '';
  5652. this.reset();
  5653. this._boundEvents = null;
  5654. this.eventBus._on('pagesinit', () => {
  5655. this._isPagesLoaded = false;
  5656. this.eventBus._on(
  5657. 'pagesloaded',
  5658. (evt) => {
  5659. this._isPagesLoaded = !!evt.pagesCount;
  5660. },
  5661. {
  5662. once: true
  5663. }
  5664. );
  5665. });
  5666. }
  5667. initialize({ fingerprint, resetHistory = false, updateUrl = false }) {
  5668. if (!fingerprint || typeof fingerprint !== 'string') {
  5669. console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');
  5670. return;
  5671. }
  5672. if (this._initialized) {
  5673. this.reset();
  5674. }
  5675. const reInitialized = this._fingerprint !== '' && this._fingerprint !== fingerprint;
  5676. this._fingerprint = fingerprint;
  5677. this._updateUrl = updateUrl === true;
  5678. this._initialized = true;
  5679. this._bindEvents();
  5680. const state = window.history.state;
  5681. this._popStateInProgress = false;
  5682. this._blockHashChange = 0;
  5683. this._currentHash = getCurrentHash();
  5684. this._numPositionUpdates = 0;
  5685. this._uid = this._maxUid = 0;
  5686. this._destination = null;
  5687. this._position = null;
  5688. if (!this._isValidState(state, true) || resetHistory) {
  5689. const { hash, page, rotation } = this._parseCurrentHash(true);
  5690. if (!hash || reInitialized || resetHistory) {
  5691. this._pushOrReplaceState(null, true);
  5692. return;
  5693. }
  5694. this._pushOrReplaceState(
  5695. {
  5696. hash,
  5697. page,
  5698. rotation
  5699. },
  5700. true
  5701. );
  5702. return;
  5703. }
  5704. const destination = state.destination;
  5705. this._updateInternalState(destination, state.uid, true);
  5706. if (destination.rotation !== undefined) {
  5707. this._initialRotation = destination.rotation;
  5708. }
  5709. if (destination.dest) {
  5710. this._initialBookmark = JSON.stringify(destination.dest);
  5711. this._destination.page = null;
  5712. } else if (destination.hash) {
  5713. this._initialBookmark = destination.hash;
  5714. } else if (destination.page) {
  5715. this._initialBookmark = `page=${destination.page}`;
  5716. }
  5717. }
  5718. reset() {
  5719. if (this._initialized) {
  5720. this._pageHide();
  5721. this._initialized = false;
  5722. this._unbindEvents();
  5723. }
  5724. if (this._updateViewareaTimeout) {
  5725. clearTimeout(this._updateViewareaTimeout);
  5726. this._updateViewareaTimeout = null;
  5727. }
  5728. this._initialBookmark = null;
  5729. this._initialRotation = null;
  5730. }
  5731. push({ namedDest = null, explicitDest, pageNumber }) {
  5732. if (!this._initialized) {
  5733. return;
  5734. }
  5735. if (namedDest && typeof namedDest !== 'string') {
  5736. console.error('PDFHistory.push: ' + `"${namedDest}" is not a valid namedDest parameter.`);
  5737. return;
  5738. } else if (!Array.isArray(explicitDest)) {
  5739. console.error('PDFHistory.push: ' + `"${explicitDest}" is not a valid explicitDest parameter.`);
  5740. return;
  5741. } else if (!this._isValidPage(pageNumber)) {
  5742. if (pageNumber !== null || this._destination) {
  5743. console.error('PDFHistory.push: ' + `"${pageNumber}" is not a valid pageNumber parameter.`);
  5744. return;
  5745. }
  5746. }
  5747. const hash = namedDest || JSON.stringify(explicitDest);
  5748. if (!hash) {
  5749. return;
  5750. }
  5751. let forceReplace = false;
  5752. if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) {
  5753. if (this._destination.page) {
  5754. return;
  5755. }
  5756. forceReplace = true;
  5757. }
  5758. if (this._popStateInProgress && !forceReplace) {
  5759. return;
  5760. }
  5761. this._pushOrReplaceState(
  5762. {
  5763. dest: explicitDest,
  5764. hash,
  5765. page: pageNumber,
  5766. rotation: this.linkService.rotation
  5767. },
  5768. forceReplace
  5769. );
  5770. if (!this._popStateInProgress) {
  5771. this._popStateInProgress = true;
  5772. Promise.resolve().then(() => {
  5773. this._popStateInProgress = false;
  5774. });
  5775. }
  5776. }
  5777. pushPage(pageNumber) {
  5778. if (!this._initialized) {
  5779. return;
  5780. }
  5781. if (!this._isValidPage(pageNumber)) {
  5782. console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`);
  5783. return;
  5784. }
  5785. if (this._destination?.page === pageNumber) {
  5786. return;
  5787. }
  5788. if (this._popStateInProgress) {
  5789. return;
  5790. }
  5791. this._pushOrReplaceState({
  5792. dest: null,
  5793. hash: `page=${pageNumber}`,
  5794. page: pageNumber,
  5795. rotation: this.linkService.rotation
  5796. });
  5797. if (!this._popStateInProgress) {
  5798. this._popStateInProgress = true;
  5799. Promise.resolve().then(() => {
  5800. this._popStateInProgress = false;
  5801. });
  5802. }
  5803. }
  5804. pushCurrentPosition() {
  5805. if (!this._initialized || this._popStateInProgress) {
  5806. return;
  5807. }
  5808. this._tryPushCurrentPosition();
  5809. }
  5810. back() {
  5811. if (!this._initialized || this._popStateInProgress) {
  5812. return;
  5813. }
  5814. const state = window.history.state;
  5815. if (this._isValidState(state) && state.uid > 0) {
  5816. window.history.back();
  5817. }
  5818. }
  5819. forward() {
  5820. if (!this._initialized || this._popStateInProgress) {
  5821. return;
  5822. }
  5823. const state = window.history.state;
  5824. if (this._isValidState(state) && state.uid < this._maxUid) {
  5825. window.history.forward();
  5826. }
  5827. }
  5828. get popStateInProgress() {
  5829. return this._initialized && (this._popStateInProgress || this._blockHashChange > 0);
  5830. }
  5831. get initialBookmark() {
  5832. return this._initialized ? this._initialBookmark : null;
  5833. }
  5834. get initialRotation() {
  5835. return this._initialized ? this._initialRotation : null;
  5836. }
  5837. _pushOrReplaceState(destination, forceReplace = false) {
  5838. const shouldReplace = forceReplace || !this._destination;
  5839. const newState = {
  5840. fingerprint: this._fingerprint,
  5841. uid: shouldReplace ? this._uid : this._uid + 1,
  5842. destination
  5843. };
  5844. this._updateInternalState(destination, newState.uid);
  5845. let newUrl;
  5846. if (this._updateUrl && destination?.hash) {
  5847. const baseUrl = document.location.href.split('#')[0];
  5848. if (!baseUrl.startsWith('file://')) {
  5849. newUrl = `${baseUrl}#${destination.hash}`;
  5850. }
  5851. }
  5852. if (shouldReplace) {
  5853. window.history.replaceState(newState, '', newUrl);
  5854. } else {
  5855. window.history.pushState(newState, '', newUrl);
  5856. }
  5857. }
  5858. _tryPushCurrentPosition(temporary = false) {
  5859. if (!this._position) {
  5860. return;
  5861. }
  5862. let position = this._position;
  5863. if (temporary) {
  5864. position = Object.assign(Object.create(null), this._position);
  5865. position.temporary = true;
  5866. }
  5867. if (!this._destination) {
  5868. this._pushOrReplaceState(position);
  5869. return;
  5870. }
  5871. if (this._destination.temporary) {
  5872. this._pushOrReplaceState(position, true);
  5873. return;
  5874. }
  5875. if (this._destination.hash === position.hash) {
  5876. return;
  5877. }
  5878. if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) {
  5879. return;
  5880. }
  5881. let forceReplace = false;
  5882. if (this._destination.page >= position.first && this._destination.page <= position.page) {
  5883. if (this._destination.dest !== undefined || !this._destination.first) {
  5884. return;
  5885. }
  5886. forceReplace = true;
  5887. }
  5888. this._pushOrReplaceState(position, forceReplace);
  5889. }
  5890. _isValidPage(val) {
  5891. return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount;
  5892. }
  5893. _isValidState(state, checkReload = false) {
  5894. if (!state) {
  5895. return false;
  5896. }
  5897. if (state.fingerprint !== this._fingerprint) {
  5898. if (checkReload) {
  5899. if (typeof state.fingerprint !== 'string' || state.fingerprint.length !== this._fingerprint.length) {
  5900. return false;
  5901. }
  5902. const [perfEntry] = performance.getEntriesByType('navigation');
  5903. if (perfEntry?.type !== 'reload') {
  5904. return false;
  5905. }
  5906. } else {
  5907. return false;
  5908. }
  5909. }
  5910. if (!Number.isInteger(state.uid) || state.uid < 0) {
  5911. return false;
  5912. }
  5913. if (state.destination === null || typeof state.destination !== 'object') {
  5914. return false;
  5915. }
  5916. return true;
  5917. }
  5918. _updateInternalState(destination, uid, removeTemporary = false) {
  5919. if (this._updateViewareaTimeout) {
  5920. clearTimeout(this._updateViewareaTimeout);
  5921. this._updateViewareaTimeout = null;
  5922. }
  5923. if (removeTemporary && destination?.temporary) {
  5924. delete destination.temporary;
  5925. }
  5926. this._destination = destination;
  5927. this._uid = uid;
  5928. this._maxUid = Math.max(this._maxUid, uid);
  5929. this._numPositionUpdates = 0;
  5930. }
  5931. _parseCurrentHash(checkNameddest = false) {
  5932. const hash = unescape(getCurrentHash()).substring(1);
  5933. const params = (0, _ui_utils.parseQueryString)(hash);
  5934. const nameddest = params.get('nameddest') || '';
  5935. let page = params.get('page') | 0;
  5936. if (!this._isValidPage(page) || (checkNameddest && nameddest.length > 0)) {
  5937. page = null;
  5938. }
  5939. return {
  5940. hash,
  5941. page,
  5942. rotation: this.linkService.rotation
  5943. };
  5944. }
  5945. _updateViewarea({ location }) {
  5946. if (this._updateViewareaTimeout) {
  5947. clearTimeout(this._updateViewareaTimeout);
  5948. this._updateViewareaTimeout = null;
  5949. }
  5950. this._position = {
  5951. hash: location.pdfOpenParams.substring(1),
  5952. page: this.linkService.page,
  5953. first: location.pageNumber,
  5954. rotation: location.rotation
  5955. };
  5956. if (this._popStateInProgress) {
  5957. return;
  5958. }
  5959. if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) {
  5960. this._numPositionUpdates++;
  5961. }
  5962. if (UPDATE_VIEWAREA_TIMEOUT > 0) {
  5963. this._updateViewareaTimeout = setTimeout(() => {
  5964. if (!this._popStateInProgress) {
  5965. this._tryPushCurrentPosition(true);
  5966. }
  5967. this._updateViewareaTimeout = null;
  5968. }, UPDATE_VIEWAREA_TIMEOUT);
  5969. }
  5970. }
  5971. _popState({ state }) {
  5972. const newHash = getCurrentHash(),
  5973. hashChanged = this._currentHash !== newHash;
  5974. this._currentHash = newHash;
  5975. if (!state) {
  5976. this._uid++;
  5977. const { hash, page, rotation } = this._parseCurrentHash();
  5978. this._pushOrReplaceState(
  5979. {
  5980. hash,
  5981. page,
  5982. rotation
  5983. },
  5984. true
  5985. );
  5986. return;
  5987. }
  5988. if (!this._isValidState(state)) {
  5989. return;
  5990. }
  5991. this._popStateInProgress = true;
  5992. if (hashChanged) {
  5993. this._blockHashChange++;
  5994. (0, _event_utils.waitOnEventOrTimeout)({
  5995. target: window,
  5996. name: 'hashchange',
  5997. delay: HASH_CHANGE_TIMEOUT
  5998. }).then(() => {
  5999. this._blockHashChange--;
  6000. });
  6001. }
  6002. const destination = state.destination;
  6003. this._updateInternalState(destination, state.uid, true);
  6004. if ((0, _ui_utils.isValidRotation)(destination.rotation)) {
  6005. this.linkService.rotation = destination.rotation;
  6006. }
  6007. if (destination.dest) {
  6008. this.linkService.goToDestination(destination.dest);
  6009. } else if (destination.hash) {
  6010. this.linkService.setHash(destination.hash);
  6011. } else if (destination.page) {
  6012. this.linkService.page = destination.page;
  6013. }
  6014. Promise.resolve().then(() => {
  6015. this._popStateInProgress = false;
  6016. });
  6017. }
  6018. _pageHide() {
  6019. if (!this._destination || this._destination.temporary) {
  6020. this._tryPushCurrentPosition();
  6021. }
  6022. }
  6023. _bindEvents() {
  6024. if (this._boundEvents) {
  6025. return;
  6026. }
  6027. this._boundEvents = {
  6028. updateViewarea: this._updateViewarea.bind(this),
  6029. popState: this._popState.bind(this),
  6030. pageHide: this._pageHide.bind(this)
  6031. };
  6032. this.eventBus._on('updateviewarea', this._boundEvents.updateViewarea);
  6033. window.addEventListener('popstate', this._boundEvents.popState);
  6034. window.addEventListener('pagehide', this._boundEvents.pageHide);
  6035. }
  6036. _unbindEvents() {
  6037. if (!this._boundEvents) {
  6038. return;
  6039. }
  6040. this.eventBus._off('updateviewarea', this._boundEvents.updateViewarea);
  6041. window.removeEventListener('popstate', this._boundEvents.popState);
  6042. window.removeEventListener('pagehide', this._boundEvents.pageHide);
  6043. this._boundEvents = null;
  6044. }
  6045. }
  6046. exports.PDFHistory = PDFHistory;
  6047. function isDestHashesEqual(destHash, pushHash) {
  6048. if (typeof destHash !== 'string' || typeof pushHash !== 'string') {
  6049. return false;
  6050. }
  6051. if (destHash === pushHash) {
  6052. return true;
  6053. }
  6054. const nameddest = (0, _ui_utils.parseQueryString)(destHash).get('nameddest');
  6055. if (nameddest === pushHash) {
  6056. return true;
  6057. }
  6058. return false;
  6059. }
  6060. function isDestArraysEqual(firstDest, secondDest) {
  6061. function isEntryEqual(first, second) {
  6062. if (typeof first !== typeof second) {
  6063. return false;
  6064. }
  6065. if (Array.isArray(first) || Array.isArray(second)) {
  6066. return false;
  6067. }
  6068. if (first !== null && typeof first === 'object' && second !== null) {
  6069. if (Object.keys(first).length !== Object.keys(second).length) {
  6070. return false;
  6071. }
  6072. for (const key in first) {
  6073. if (!isEntryEqual(first[key], second[key])) {
  6074. return false;
  6075. }
  6076. }
  6077. return true;
  6078. }
  6079. return first === second || (Number.isNaN(first) && Number.isNaN(second));
  6080. }
  6081. if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) {
  6082. return false;
  6083. }
  6084. if (firstDest.length !== secondDest.length) {
  6085. return false;
  6086. }
  6087. for (let i = 0, ii = firstDest.length; i < ii; i++) {
  6088. if (!isEntryEqual(firstDest[i], secondDest[i])) {
  6089. return false;
  6090. }
  6091. }
  6092. return true;
  6093. }
  6094. /***/
  6095. },
  6096. /* 20 */
  6097. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  6098. Object.defineProperty(exports, '__esModule', {
  6099. value: true
  6100. });
  6101. exports.PDFLayerViewer = void 0;
  6102. var _base_tree_viewer = __webpack_require__(12);
  6103. class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer {
  6104. constructor(options) {
  6105. super(options);
  6106. this.l10n = options.l10n;
  6107. this.eventBus._on('optionalcontentconfigchanged', (evt) => {
  6108. this.#updateLayers(evt.promise);
  6109. });
  6110. this.eventBus._on('resetlayers', () => {
  6111. this.#updateLayers();
  6112. });
  6113. this.eventBus._on('togglelayerstree', this._toggleAllTreeItems.bind(this));
  6114. }
  6115. reset() {
  6116. super.reset();
  6117. this._optionalContentConfig = null;
  6118. this._optionalContentHash = null;
  6119. }
  6120. _dispatchEvent(layersCount) {
  6121. this.eventBus.dispatch('layersloaded', {
  6122. source: this,
  6123. layersCount
  6124. });
  6125. }
  6126. _bindLink(element, { groupId, input }) {
  6127. const setVisibility = () => {
  6128. this._optionalContentConfig.setVisibility(groupId, input.checked);
  6129. this._optionalContentHash = this._optionalContentConfig.getHash();
  6130. this.eventBus.dispatch('optionalcontentconfig', {
  6131. source: this,
  6132. promise: Promise.resolve(this._optionalContentConfig)
  6133. });
  6134. };
  6135. element.onclick = (evt) => {
  6136. if (evt.target === input) {
  6137. setVisibility();
  6138. return true;
  6139. } else if (evt.target !== element) {
  6140. return true;
  6141. }
  6142. input.checked = !input.checked;
  6143. setVisibility();
  6144. return false;
  6145. };
  6146. }
  6147. async _setNestedName(element, { name = null }) {
  6148. if (typeof name === 'string') {
  6149. element.textContent = this._normalizeTextContent(name);
  6150. return;
  6151. }
  6152. element.textContent = await this.l10n.get('additional_layers');
  6153. element.style.fontStyle = 'italic';
  6154. }
  6155. _addToggleButton(div, { name = null }) {
  6156. super._addToggleButton(div, name === null);
  6157. }
  6158. _toggleAllTreeItems() {
  6159. if (!this._optionalContentConfig) {
  6160. return;
  6161. }
  6162. super._toggleAllTreeItems();
  6163. }
  6164. render({ optionalContentConfig, pdfDocument }) {
  6165. if (this._optionalContentConfig) {
  6166. this.reset();
  6167. }
  6168. this._optionalContentConfig = optionalContentConfig || null;
  6169. this._pdfDocument = pdfDocument || null;
  6170. const groups = optionalContentConfig?.getOrder();
  6171. if (!groups) {
  6172. this._dispatchEvent(0);
  6173. return;
  6174. }
  6175. this._optionalContentHash = optionalContentConfig.getHash();
  6176. const fragment = document.createDocumentFragment(),
  6177. queue = [
  6178. {
  6179. parent: fragment,
  6180. groups
  6181. }
  6182. ];
  6183. let layersCount = 0,
  6184. hasAnyNesting = false;
  6185. while (queue.length > 0) {
  6186. const levelData = queue.shift();
  6187. for (const groupId of levelData.groups) {
  6188. const div = document.createElement('div');
  6189. div.className = 'treeItem';
  6190. const element = document.createElement('a');
  6191. div.append(element);
  6192. if (typeof groupId === 'object') {
  6193. hasAnyNesting = true;
  6194. this._addToggleButton(div, groupId);
  6195. this._setNestedName(element, groupId);
  6196. const itemsDiv = document.createElement('div');
  6197. itemsDiv.className = 'treeItems';
  6198. div.append(itemsDiv);
  6199. queue.push({
  6200. parent: itemsDiv,
  6201. groups: groupId.order
  6202. });
  6203. } else {
  6204. const group = optionalContentConfig.getGroup(groupId);
  6205. const input = document.createElement('input');
  6206. this._bindLink(element, {
  6207. groupId,
  6208. input
  6209. });
  6210. input.type = 'checkbox';
  6211. input.checked = group.visible;
  6212. const label = document.createElement('label');
  6213. label.textContent = this._normalizeTextContent(group.name);
  6214. label.append(input);
  6215. element.append(label);
  6216. layersCount++;
  6217. }
  6218. levelData.parent.append(div);
  6219. }
  6220. }
  6221. this._finishRendering(fragment, layersCount, hasAnyNesting);
  6222. }
  6223. async #updateLayers(promise = null) {
  6224. if (!this._optionalContentConfig) {
  6225. return;
  6226. }
  6227. const pdfDocument = this._pdfDocument;
  6228. const optionalContentConfig = await (promise || pdfDocument.getOptionalContentConfig());
  6229. if (pdfDocument !== this._pdfDocument) {
  6230. return;
  6231. }
  6232. if (promise) {
  6233. if (optionalContentConfig.getHash() === this._optionalContentHash) {
  6234. return;
  6235. }
  6236. } else {
  6237. this.eventBus.dispatch('optionalcontentconfig', {
  6238. source: this,
  6239. promise: Promise.resolve(optionalContentConfig)
  6240. });
  6241. }
  6242. this.render({
  6243. optionalContentConfig,
  6244. pdfDocument: this._pdfDocument
  6245. });
  6246. }
  6247. }
  6248. exports.PDFLayerViewer = PDFLayerViewer;
  6249. /***/
  6250. },
  6251. /* 21 */
  6252. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  6253. Object.defineProperty(exports, '__esModule', {
  6254. value: true
  6255. });
  6256. exports.PDFOutlineViewer = void 0;
  6257. var _base_tree_viewer = __webpack_require__(12);
  6258. var _pdfjsLib = __webpack_require__(4);
  6259. var _ui_utils = __webpack_require__(3);
  6260. class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer {
  6261. constructor(options) {
  6262. super(options);
  6263. this.linkService = options.linkService;
  6264. this.downloadManager = options.downloadManager;
  6265. this.eventBus._on('toggleoutlinetree', this._toggleAllTreeItems.bind(this));
  6266. this.eventBus._on('currentoutlineitem', this._currentOutlineItem.bind(this));
  6267. this.eventBus._on('pagechanging', (evt) => {
  6268. this._currentPageNumber = evt.pageNumber;
  6269. });
  6270. this.eventBus._on('pagesloaded', (evt) => {
  6271. this._isPagesLoaded = !!evt.pagesCount;
  6272. if (this._currentOutlineItemCapability && !this._currentOutlineItemCapability.settled) {
  6273. this._currentOutlineItemCapability.resolve(this._isPagesLoaded);
  6274. }
  6275. });
  6276. this.eventBus._on('sidebarviewchanged', (evt) => {
  6277. this._sidebarView = evt.view;
  6278. });
  6279. }
  6280. reset() {
  6281. super.reset();
  6282. this._outline = null;
  6283. this._pageNumberToDestHashCapability = null;
  6284. this._currentPageNumber = 1;
  6285. this._isPagesLoaded = null;
  6286. if (this._currentOutlineItemCapability && !this._currentOutlineItemCapability.settled) {
  6287. this._currentOutlineItemCapability.resolve(false);
  6288. }
  6289. this._currentOutlineItemCapability = null;
  6290. }
  6291. _dispatchEvent(outlineCount) {
  6292. this._currentOutlineItemCapability = new _pdfjsLib.PromiseCapability();
  6293. if (outlineCount === 0 || this._pdfDocument?.loadingParams.disableAutoFetch) {
  6294. this._currentOutlineItemCapability.resolve(false);
  6295. } else if (this._isPagesLoaded !== null) {
  6296. this._currentOutlineItemCapability.resolve(this._isPagesLoaded);
  6297. }
  6298. this.eventBus.dispatch('outlineloaded', {
  6299. source: this,
  6300. outlineCount,
  6301. currentOutlineItemPromise: this._currentOutlineItemCapability.promise
  6302. });
  6303. }
  6304. _bindLink(element, { url, newWindow, action, attachment, dest, setOCGState }) {
  6305. const { linkService } = this;
  6306. if (url) {
  6307. linkService.addLinkAttributes(element, url, newWindow);
  6308. return;
  6309. }
  6310. if (action) {
  6311. element.href = linkService.getAnchorUrl('');
  6312. element.onclick = () => {
  6313. linkService.executeNamedAction(action);
  6314. return false;
  6315. };
  6316. return;
  6317. }
  6318. if (attachment) {
  6319. element.href = linkService.getAnchorUrl('');
  6320. element.onclick = () => {
  6321. this.downloadManager.openOrDownloadData(element, attachment.content, attachment.filename);
  6322. return false;
  6323. };
  6324. return;
  6325. }
  6326. if (setOCGState) {
  6327. element.href = linkService.getAnchorUrl('');
  6328. element.onclick = () => {
  6329. linkService.executeSetOCGState(setOCGState);
  6330. return false;
  6331. };
  6332. return;
  6333. }
  6334. element.href = linkService.getDestinationHash(dest);
  6335. element.onclick = (evt) => {
  6336. this._updateCurrentTreeItem(evt.target.parentNode);
  6337. if (dest) {
  6338. linkService.goToDestination(dest);
  6339. }
  6340. return false;
  6341. };
  6342. }
  6343. _setStyles(element, { bold, italic }) {
  6344. if (bold) {
  6345. element.style.fontWeight = 'bold';
  6346. }
  6347. if (italic) {
  6348. element.style.fontStyle = 'italic';
  6349. }
  6350. }
  6351. _addToggleButton(div, { count, items }) {
  6352. let hidden = false;
  6353. if (count < 0) {
  6354. let totalCount = items.length;
  6355. if (totalCount > 0) {
  6356. const queue = [...items];
  6357. while (queue.length > 0) {
  6358. const { count: nestedCount, items: nestedItems } = queue.shift();
  6359. if (nestedCount > 0 && nestedItems.length > 0) {
  6360. totalCount += nestedItems.length;
  6361. queue.push(...nestedItems);
  6362. }
  6363. }
  6364. }
  6365. if (Math.abs(count) === totalCount) {
  6366. hidden = true;
  6367. }
  6368. }
  6369. super._addToggleButton(div, hidden);
  6370. }
  6371. _toggleAllTreeItems() {
  6372. if (!this._outline) {
  6373. return;
  6374. }
  6375. super._toggleAllTreeItems();
  6376. }
  6377. render({ outline, pdfDocument }) {
  6378. if (this._outline) {
  6379. this.reset();
  6380. }
  6381. this._outline = outline || null;
  6382. this._pdfDocument = pdfDocument || null;
  6383. if (!outline) {
  6384. this._dispatchEvent(0);
  6385. return;
  6386. }
  6387. const fragment = document.createDocumentFragment();
  6388. const queue = [
  6389. {
  6390. parent: fragment,
  6391. items: outline
  6392. }
  6393. ];
  6394. let outlineCount = 0,
  6395. hasAnyNesting = false;
  6396. while (queue.length > 0) {
  6397. const levelData = queue.shift();
  6398. for (const item of levelData.items) {
  6399. const div = document.createElement('div');
  6400. div.className = 'treeItem';
  6401. const element = document.createElement('a');
  6402. this._bindLink(element, item);
  6403. this._setStyles(element, item);
  6404. element.textContent = this._normalizeTextContent(item.title);
  6405. div.append(element);
  6406. if (item.items.length > 0) {
  6407. hasAnyNesting = true;
  6408. this._addToggleButton(div, item);
  6409. const itemsDiv = document.createElement('div');
  6410. itemsDiv.className = 'treeItems';
  6411. div.append(itemsDiv);
  6412. queue.push({
  6413. parent: itemsDiv,
  6414. items: item.items
  6415. });
  6416. }
  6417. levelData.parent.append(div);
  6418. outlineCount++;
  6419. }
  6420. }
  6421. this._finishRendering(fragment, outlineCount, hasAnyNesting);
  6422. }
  6423. async _currentOutlineItem() {
  6424. if (!this._isPagesLoaded) {
  6425. throw new Error('_currentOutlineItem: All pages have not been loaded.');
  6426. }
  6427. if (!this._outline || !this._pdfDocument) {
  6428. return;
  6429. }
  6430. const pageNumberToDestHash = await this._getPageNumberToDestHash(this._pdfDocument);
  6431. if (!pageNumberToDestHash) {
  6432. return;
  6433. }
  6434. this._updateCurrentTreeItem(null);
  6435. if (this._sidebarView !== _ui_utils.SidebarView.OUTLINE) {
  6436. return;
  6437. }
  6438. for (let i = this._currentPageNumber; i > 0; i--) {
  6439. const destHash = pageNumberToDestHash.get(i);
  6440. if (!destHash) {
  6441. continue;
  6442. }
  6443. const linkElement = this.container.querySelector(`a[href="${destHash}"]`);
  6444. if (!linkElement) {
  6445. continue;
  6446. }
  6447. this._scrollToCurrentTreeItem(linkElement.parentNode);
  6448. break;
  6449. }
  6450. }
  6451. async _getPageNumberToDestHash(pdfDocument) {
  6452. if (this._pageNumberToDestHashCapability) {
  6453. return this._pageNumberToDestHashCapability.promise;
  6454. }
  6455. this._pageNumberToDestHashCapability = new _pdfjsLib.PromiseCapability();
  6456. const pageNumberToDestHash = new Map(),
  6457. pageNumberNesting = new Map();
  6458. const queue = [
  6459. {
  6460. nesting: 0,
  6461. items: this._outline
  6462. }
  6463. ];
  6464. while (queue.length > 0) {
  6465. const levelData = queue.shift(),
  6466. currentNesting = levelData.nesting;
  6467. for (const { dest, items } of levelData.items) {
  6468. let explicitDest, pageNumber;
  6469. if (typeof dest === 'string') {
  6470. explicitDest = await pdfDocument.getDestination(dest);
  6471. if (pdfDocument !== this._pdfDocument) {
  6472. return null;
  6473. }
  6474. } else {
  6475. explicitDest = dest;
  6476. }
  6477. if (Array.isArray(explicitDest)) {
  6478. const [destRef] = explicitDest;
  6479. if (typeof destRef === 'object' && destRef !== null) {
  6480. pageNumber = this.linkService._cachedPageNumber(destRef);
  6481. if (!pageNumber) {
  6482. try {
  6483. pageNumber = (await pdfDocument.getPageIndex(destRef)) + 1;
  6484. if (pdfDocument !== this._pdfDocument) {
  6485. return null;
  6486. }
  6487. this.linkService.cachePageRef(pageNumber, destRef);
  6488. } catch (ex) {}
  6489. }
  6490. } else if (Number.isInteger(destRef)) {
  6491. pageNumber = destRef + 1;
  6492. }
  6493. if (Number.isInteger(pageNumber) && (!pageNumberToDestHash.has(pageNumber) || currentNesting > pageNumberNesting.get(pageNumber))) {
  6494. const destHash = this.linkService.getDestinationHash(dest);
  6495. pageNumberToDestHash.set(pageNumber, destHash);
  6496. pageNumberNesting.set(pageNumber, currentNesting);
  6497. }
  6498. }
  6499. if (items.length > 0) {
  6500. queue.push({
  6501. nesting: currentNesting + 1,
  6502. items
  6503. });
  6504. }
  6505. }
  6506. }
  6507. this._pageNumberToDestHashCapability.resolve(pageNumberToDestHash.size > 0 ? pageNumberToDestHash : null);
  6508. return this._pageNumberToDestHashCapability.promise;
  6509. }
  6510. }
  6511. exports.PDFOutlineViewer = PDFOutlineViewer;
  6512. /***/
  6513. },
  6514. /* 22 */
  6515. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  6516. Object.defineProperty(exports, '__esModule', {
  6517. value: true
  6518. });
  6519. exports.PDFPresentationMode = void 0;
  6520. var _ui_utils = __webpack_require__(3);
  6521. var _pdfjsLib = __webpack_require__(4);
  6522. const DELAY_BEFORE_HIDING_CONTROLS = 3000;
  6523. const ACTIVE_SELECTOR = 'pdfPresentationMode';
  6524. const CONTROLS_SELECTOR = 'pdfPresentationModeControls';
  6525. const MOUSE_SCROLL_COOLDOWN_TIME = 50;
  6526. const PAGE_SWITCH_THRESHOLD = 0.1;
  6527. const SWIPE_MIN_DISTANCE_THRESHOLD = 50;
  6528. const SWIPE_ANGLE_THRESHOLD = Math.PI / 6;
  6529. class PDFPresentationMode {
  6530. #state = _ui_utils.PresentationModeState.UNKNOWN;
  6531. #args = null;
  6532. constructor({ container, pdfViewer, eventBus }) {
  6533. this.container = container;
  6534. this.pdfViewer = pdfViewer;
  6535. this.eventBus = eventBus;
  6536. this.contextMenuOpen = false;
  6537. this.mouseScrollTimeStamp = 0;
  6538. this.mouseScrollDelta = 0;
  6539. this.touchSwipeState = null;
  6540. }
  6541. async request() {
  6542. const { container, pdfViewer } = this;
  6543. if (this.active || !pdfViewer.pagesCount || !container.requestFullscreen) {
  6544. return false;
  6545. }
  6546. this.#addFullscreenChangeListeners();
  6547. this.#notifyStateChange(_ui_utils.PresentationModeState.CHANGING);
  6548. const promise = container.requestFullscreen();
  6549. this.#args = {
  6550. pageNumber: pdfViewer.currentPageNumber,
  6551. scaleValue: pdfViewer.currentScaleValue,
  6552. scrollMode: pdfViewer.scrollMode,
  6553. spreadMode: null,
  6554. annotationEditorMode: null
  6555. };
  6556. if (pdfViewer.spreadMode !== _ui_utils.SpreadMode.NONE && !(pdfViewer.pageViewsReady && pdfViewer.hasEqualPageSizes)) {
  6557. console.warn('Ignoring Spread modes when entering PresentationMode, ' + 'since the document may contain varying page sizes.');
  6558. this.#args.spreadMode = pdfViewer.spreadMode;
  6559. }
  6560. if (pdfViewer.annotationEditorMode !== _pdfjsLib.AnnotationEditorType.DISABLE) {
  6561. this.#args.annotationEditorMode = pdfViewer.annotationEditorMode;
  6562. }
  6563. try {
  6564. await promise;
  6565. pdfViewer.focus();
  6566. return true;
  6567. } catch (reason) {
  6568. this.#removeFullscreenChangeListeners();
  6569. this.#notifyStateChange(_ui_utils.PresentationModeState.NORMAL);
  6570. }
  6571. return false;
  6572. }
  6573. get active() {
  6574. return this.#state === _ui_utils.PresentationModeState.CHANGING || this.#state === _ui_utils.PresentationModeState.FULLSCREEN;
  6575. }
  6576. #mouseWheel(evt) {
  6577. if (!this.active) {
  6578. return;
  6579. }
  6580. evt.preventDefault();
  6581. const delta = (0, _ui_utils.normalizeWheelEventDelta)(evt);
  6582. const currentTime = Date.now();
  6583. const storedTime = this.mouseScrollTimeStamp;
  6584. if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
  6585. return;
  6586. }
  6587. if ((this.mouseScrollDelta > 0 && delta < 0) || (this.mouseScrollDelta < 0 && delta > 0)) {
  6588. this.#resetMouseScrollState();
  6589. }
  6590. this.mouseScrollDelta += delta;
  6591. if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) {
  6592. const totalDelta = this.mouseScrollDelta;
  6593. this.#resetMouseScrollState();
  6594. const success = totalDelta > 0 ? this.pdfViewer.previousPage() : this.pdfViewer.nextPage();
  6595. if (success) {
  6596. this.mouseScrollTimeStamp = currentTime;
  6597. }
  6598. }
  6599. }
  6600. #notifyStateChange(state) {
  6601. this.#state = state;
  6602. this.eventBus.dispatch('presentationmodechanged', {
  6603. source: this,
  6604. state
  6605. });
  6606. }
  6607. #enter() {
  6608. this.#notifyStateChange(_ui_utils.PresentationModeState.FULLSCREEN);
  6609. this.container.classList.add(ACTIVE_SELECTOR);
  6610. setTimeout(() => {
  6611. this.pdfViewer.scrollMode = _ui_utils.ScrollMode.PAGE;
  6612. if (this.#args.spreadMode !== null) {
  6613. this.pdfViewer.spreadMode = _ui_utils.SpreadMode.NONE;
  6614. }
  6615. this.pdfViewer.currentPageNumber = this.#args.pageNumber;
  6616. this.pdfViewer.currentScaleValue = 'page-fit';
  6617. if (this.#args.annotationEditorMode !== null) {
  6618. this.pdfViewer.annotationEditorMode = _pdfjsLib.AnnotationEditorType.NONE;
  6619. }
  6620. }, 0);
  6621. this.#addWindowListeners();
  6622. this.#showControls();
  6623. this.contextMenuOpen = false;
  6624. window.getSelection().removeAllRanges();
  6625. }
  6626. #exit() {
  6627. const pageNumber = this.pdfViewer.currentPageNumber;
  6628. this.container.classList.remove(ACTIVE_SELECTOR);
  6629. setTimeout(() => {
  6630. this.#removeFullscreenChangeListeners();
  6631. this.#notifyStateChange(_ui_utils.PresentationModeState.NORMAL);
  6632. this.pdfViewer.scrollMode = this.#args.scrollMode;
  6633. if (this.#args.spreadMode !== null) {
  6634. this.pdfViewer.spreadMode = this.#args.spreadMode;
  6635. }
  6636. this.pdfViewer.currentScaleValue = this.#args.scaleValue;
  6637. this.pdfViewer.currentPageNumber = pageNumber;
  6638. if (this.#args.annotationEditorMode !== null) {
  6639. this.pdfViewer.annotationEditorMode = this.#args.annotationEditorMode;
  6640. }
  6641. this.#args = null;
  6642. }, 0);
  6643. this.#removeWindowListeners();
  6644. this.#hideControls();
  6645. this.#resetMouseScrollState();
  6646. this.contextMenuOpen = false;
  6647. }
  6648. #mouseDown(evt) {
  6649. if (this.contextMenuOpen) {
  6650. this.contextMenuOpen = false;
  6651. evt.preventDefault();
  6652. return;
  6653. }
  6654. if (evt.button !== 0) {
  6655. return;
  6656. }
  6657. if (evt.target.href && evt.target.parentNode?.hasAttribute('data-internal-link')) {
  6658. return;
  6659. }
  6660. evt.preventDefault();
  6661. if (evt.shiftKey) {
  6662. this.pdfViewer.previousPage();
  6663. } else {
  6664. this.pdfViewer.nextPage();
  6665. }
  6666. }
  6667. #contextMenu() {
  6668. this.contextMenuOpen = true;
  6669. }
  6670. #showControls() {
  6671. if (this.controlsTimeout) {
  6672. clearTimeout(this.controlsTimeout);
  6673. } else {
  6674. this.container.classList.add(CONTROLS_SELECTOR);
  6675. }
  6676. this.controlsTimeout = setTimeout(() => {
  6677. this.container.classList.remove(CONTROLS_SELECTOR);
  6678. delete this.controlsTimeout;
  6679. }, DELAY_BEFORE_HIDING_CONTROLS);
  6680. }
  6681. #hideControls() {
  6682. if (!this.controlsTimeout) {
  6683. return;
  6684. }
  6685. clearTimeout(this.controlsTimeout);
  6686. this.container.classList.remove(CONTROLS_SELECTOR);
  6687. delete this.controlsTimeout;
  6688. }
  6689. #resetMouseScrollState() {
  6690. this.mouseScrollTimeStamp = 0;
  6691. this.mouseScrollDelta = 0;
  6692. }
  6693. #touchSwipe(evt) {
  6694. if (!this.active) {
  6695. return;
  6696. }
  6697. if (evt.touches.length > 1) {
  6698. this.touchSwipeState = null;
  6699. return;
  6700. }
  6701. switch (evt.type) {
  6702. case 'touchstart':
  6703. this.touchSwipeState = {
  6704. startX: evt.touches[0].pageX,
  6705. startY: evt.touches[0].pageY,
  6706. endX: evt.touches[0].pageX,
  6707. endY: evt.touches[0].pageY
  6708. };
  6709. break;
  6710. case 'touchmove':
  6711. if (this.touchSwipeState === null) {
  6712. return;
  6713. }
  6714. this.touchSwipeState.endX = evt.touches[0].pageX;
  6715. this.touchSwipeState.endY = evt.touches[0].pageY;
  6716. evt.preventDefault();
  6717. break;
  6718. case 'touchend':
  6719. if (this.touchSwipeState === null) {
  6720. return;
  6721. }
  6722. let delta = 0;
  6723. const dx = this.touchSwipeState.endX - this.touchSwipeState.startX;
  6724. const dy = this.touchSwipeState.endY - this.touchSwipeState.startY;
  6725. const absAngle = Math.abs(Math.atan2(dy, dx));
  6726. if (Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && (absAngle <= SWIPE_ANGLE_THRESHOLD || absAngle >= Math.PI - SWIPE_ANGLE_THRESHOLD)) {
  6727. delta = dx;
  6728. } else if (Math.abs(dy) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(absAngle - Math.PI / 2) <= SWIPE_ANGLE_THRESHOLD) {
  6729. delta = dy;
  6730. }
  6731. if (delta > 0) {
  6732. this.pdfViewer.previousPage();
  6733. } else if (delta < 0) {
  6734. this.pdfViewer.nextPage();
  6735. }
  6736. break;
  6737. }
  6738. }
  6739. #addWindowListeners() {
  6740. this.showControlsBind = this.#showControls.bind(this);
  6741. this.mouseDownBind = this.#mouseDown.bind(this);
  6742. this.mouseWheelBind = this.#mouseWheel.bind(this);
  6743. this.resetMouseScrollStateBind = this.#resetMouseScrollState.bind(this);
  6744. this.contextMenuBind = this.#contextMenu.bind(this);
  6745. this.touchSwipeBind = this.#touchSwipe.bind(this);
  6746. window.addEventListener('mousemove', this.showControlsBind);
  6747. window.addEventListener('mousedown', this.mouseDownBind);
  6748. window.addEventListener('wheel', this.mouseWheelBind, {
  6749. passive: false
  6750. });
  6751. window.addEventListener('keydown', this.resetMouseScrollStateBind);
  6752. window.addEventListener('contextmenu', this.contextMenuBind);
  6753. window.addEventListener('touchstart', this.touchSwipeBind);
  6754. window.addEventListener('touchmove', this.touchSwipeBind);
  6755. window.addEventListener('touchend', this.touchSwipeBind);
  6756. }
  6757. #removeWindowListeners() {
  6758. window.removeEventListener('mousemove', this.showControlsBind);
  6759. window.removeEventListener('mousedown', this.mouseDownBind);
  6760. window.removeEventListener('wheel', this.mouseWheelBind, {
  6761. passive: false
  6762. });
  6763. window.removeEventListener('keydown', this.resetMouseScrollStateBind);
  6764. window.removeEventListener('contextmenu', this.contextMenuBind);
  6765. window.removeEventListener('touchstart', this.touchSwipeBind);
  6766. window.removeEventListener('touchmove', this.touchSwipeBind);
  6767. window.removeEventListener('touchend', this.touchSwipeBind);
  6768. delete this.showControlsBind;
  6769. delete this.mouseDownBind;
  6770. delete this.mouseWheelBind;
  6771. delete this.resetMouseScrollStateBind;
  6772. delete this.contextMenuBind;
  6773. delete this.touchSwipeBind;
  6774. }
  6775. #fullscreenChange() {
  6776. if (document.fullscreenElement) {
  6777. this.#enter();
  6778. } else {
  6779. this.#exit();
  6780. }
  6781. }
  6782. #addFullscreenChangeListeners() {
  6783. this.fullscreenChangeBind = this.#fullscreenChange.bind(this);
  6784. window.addEventListener('fullscreenchange', this.fullscreenChangeBind);
  6785. }
  6786. #removeFullscreenChangeListeners() {
  6787. window.removeEventListener('fullscreenchange', this.fullscreenChangeBind);
  6788. delete this.fullscreenChangeBind;
  6789. }
  6790. }
  6791. exports.PDFPresentationMode = PDFPresentationMode;
  6792. /***/
  6793. },
  6794. /* 23 */
  6795. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  6796. Object.defineProperty(exports, '__esModule', {
  6797. value: true
  6798. });
  6799. exports.PDFRenderingQueue = void 0;
  6800. var _pdfjsLib = __webpack_require__(4);
  6801. var _ui_utils = __webpack_require__(3);
  6802. const CLEANUP_TIMEOUT = 30000;
  6803. class PDFRenderingQueue {
  6804. constructor() {
  6805. this.pdfViewer = null;
  6806. this.pdfThumbnailViewer = null;
  6807. this.onIdle = null;
  6808. this.highestPriorityPage = null;
  6809. this.idleTimeout = null;
  6810. this.printing = false;
  6811. this.isThumbnailViewEnabled = false;
  6812. }
  6813. setViewer(pdfViewer) {
  6814. this.pdfViewer = pdfViewer;
  6815. }
  6816. setThumbnailViewer(pdfThumbnailViewer) {
  6817. this.pdfThumbnailViewer = pdfThumbnailViewer;
  6818. }
  6819. isHighestPriority(view) {
  6820. return this.highestPriorityPage === view.renderingId;
  6821. }
  6822. hasViewer() {
  6823. return !!this.pdfViewer;
  6824. }
  6825. renderHighestPriority(currentlyVisiblePages) {
  6826. if (this.idleTimeout) {
  6827. clearTimeout(this.idleTimeout);
  6828. this.idleTimeout = null;
  6829. }
  6830. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  6831. return;
  6832. }
  6833. if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) {
  6834. return;
  6835. }
  6836. if (this.printing) {
  6837. return;
  6838. }
  6839. if (this.onIdle) {
  6840. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  6841. }
  6842. }
  6843. getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) {
  6844. const visibleViews = visible.views,
  6845. numVisible = visibleViews.length;
  6846. if (numVisible === 0) {
  6847. return null;
  6848. }
  6849. for (let i = 0; i < numVisible; i++) {
  6850. const view = visibleViews[i].view;
  6851. if (!this.isViewFinished(view)) {
  6852. return view;
  6853. }
  6854. }
  6855. const firstId = visible.first.id,
  6856. lastId = visible.last.id;
  6857. if (lastId - firstId + 1 > numVisible) {
  6858. const visibleIds = visible.ids;
  6859. for (let i = 1, ii = lastId - firstId; i < ii; i++) {
  6860. const holeId = scrolledDown ? firstId + i : lastId - i;
  6861. if (visibleIds.has(holeId)) {
  6862. continue;
  6863. }
  6864. const holeView = views[holeId - 1];
  6865. if (!this.isViewFinished(holeView)) {
  6866. return holeView;
  6867. }
  6868. }
  6869. }
  6870. let preRenderIndex = scrolledDown ? lastId : firstId - 2;
  6871. let preRenderView = views[preRenderIndex];
  6872. if (preRenderView && !this.isViewFinished(preRenderView)) {
  6873. return preRenderView;
  6874. }
  6875. if (preRenderExtra) {
  6876. preRenderIndex += scrolledDown ? 1 : -1;
  6877. preRenderView = views[preRenderIndex];
  6878. if (preRenderView && !this.isViewFinished(preRenderView)) {
  6879. return preRenderView;
  6880. }
  6881. }
  6882. return null;
  6883. }
  6884. isViewFinished(view) {
  6885. return view.renderingState === _ui_utils.RenderingStates.FINISHED;
  6886. }
  6887. renderView(view) {
  6888. switch (view.renderingState) {
  6889. case _ui_utils.RenderingStates.FINISHED:
  6890. return false;
  6891. case _ui_utils.RenderingStates.PAUSED:
  6892. this.highestPriorityPage = view.renderingId;
  6893. view.resume();
  6894. break;
  6895. case _ui_utils.RenderingStates.RUNNING:
  6896. this.highestPriorityPage = view.renderingId;
  6897. break;
  6898. case _ui_utils.RenderingStates.INITIAL:
  6899. this.highestPriorityPage = view.renderingId;
  6900. view
  6901. .draw()
  6902. .finally(() => {
  6903. this.renderHighestPriority();
  6904. })
  6905. .catch((reason) => {
  6906. if (reason instanceof _pdfjsLib.RenderingCancelledException) {
  6907. return;
  6908. }
  6909. console.error(`renderView: "${reason}"`);
  6910. });
  6911. break;
  6912. }
  6913. return true;
  6914. }
  6915. }
  6916. exports.PDFRenderingQueue = PDFRenderingQueue;
  6917. /***/
  6918. },
  6919. /* 24 */
  6920. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  6921. Object.defineProperty(exports, '__esModule', {
  6922. value: true
  6923. });
  6924. exports.PDFScriptingManager = void 0;
  6925. var _ui_utils = __webpack_require__(3);
  6926. var _pdfjsLib = __webpack_require__(4);
  6927. class PDFScriptingManager {
  6928. constructor({ eventBus, sandboxBundleSrc = null, scriptingFactory = null, docPropertiesLookup = null }) {
  6929. this._pdfDocument = null;
  6930. this._pdfViewer = null;
  6931. this._closeCapability = null;
  6932. this._destroyCapability = null;
  6933. this._scripting = null;
  6934. this._ready = false;
  6935. this._eventBus = eventBus;
  6936. this._sandboxBundleSrc = sandboxBundleSrc;
  6937. this._scriptingFactory = scriptingFactory;
  6938. this._docPropertiesLookup = docPropertiesLookup;
  6939. }
  6940. setViewer(pdfViewer) {
  6941. this._pdfViewer = pdfViewer;
  6942. }
  6943. async setDocument(pdfDocument) {
  6944. if (this._pdfDocument) {
  6945. await this._destroyScripting();
  6946. }
  6947. this._pdfDocument = pdfDocument;
  6948. if (!pdfDocument) {
  6949. return;
  6950. }
  6951. const [objects, calculationOrder, docActions] = await Promise.all([
  6952. pdfDocument.getFieldObjects(),
  6953. pdfDocument.getCalculationOrderIds(),
  6954. pdfDocument.getJSActions()
  6955. ]);
  6956. if (!objects && !docActions) {
  6957. await this._destroyScripting();
  6958. return;
  6959. }
  6960. if (pdfDocument !== this._pdfDocument) {
  6961. return;
  6962. }
  6963. try {
  6964. this._scripting = this._createScripting();
  6965. } catch (error) {
  6966. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  6967. await this._destroyScripting();
  6968. return;
  6969. }
  6970. this._internalEvents.set('updatefromsandbox', (event) => {
  6971. if (event?.source !== window) {
  6972. return;
  6973. }
  6974. this._updateFromSandbox(event.detail);
  6975. });
  6976. this._internalEvents.set('dispatcheventinsandbox', (event) => {
  6977. this._scripting?.dispatchEventInSandbox(event.detail);
  6978. });
  6979. this._internalEvents.set('pagechanging', ({ pageNumber, previous }) => {
  6980. if (pageNumber === previous) {
  6981. return;
  6982. }
  6983. this._dispatchPageClose(previous);
  6984. this._dispatchPageOpen(pageNumber);
  6985. });
  6986. this._internalEvents.set('pagerendered', ({ pageNumber }) => {
  6987. if (!this._pageOpenPending.has(pageNumber)) {
  6988. return;
  6989. }
  6990. if (pageNumber !== this._pdfViewer.currentPageNumber) {
  6991. return;
  6992. }
  6993. this._dispatchPageOpen(pageNumber);
  6994. });
  6995. this._internalEvents.set('pagesdestroy', async (event) => {
  6996. await this._dispatchPageClose(this._pdfViewer.currentPageNumber);
  6997. await this._scripting?.dispatchEventInSandbox({
  6998. id: 'doc',
  6999. name: 'WillClose'
  7000. });
  7001. this._closeCapability?.resolve();
  7002. });
  7003. for (const [name, listener] of this._internalEvents) {
  7004. this._eventBus._on(name, listener);
  7005. }
  7006. try {
  7007. const docProperties = await this._getDocProperties();
  7008. if (pdfDocument !== this._pdfDocument) {
  7009. return;
  7010. }
  7011. await this._scripting.createSandbox({
  7012. objects,
  7013. calculationOrder,
  7014. appInfo: {
  7015. platform: navigator.platform,
  7016. language: navigator.language
  7017. },
  7018. docInfo: {
  7019. ...docProperties,
  7020. actions: docActions
  7021. }
  7022. });
  7023. this._eventBus.dispatch('sandboxcreated', {
  7024. source: this
  7025. });
  7026. } catch (error) {
  7027. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  7028. await this._destroyScripting();
  7029. return;
  7030. }
  7031. await this._scripting?.dispatchEventInSandbox({
  7032. id: 'doc',
  7033. name: 'Open'
  7034. });
  7035. await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true);
  7036. Promise.resolve().then(() => {
  7037. if (pdfDocument === this._pdfDocument) {
  7038. this._ready = true;
  7039. }
  7040. });
  7041. }
  7042. async dispatchWillSave(detail) {
  7043. return this._scripting?.dispatchEventInSandbox({
  7044. id: 'doc',
  7045. name: 'WillSave'
  7046. });
  7047. }
  7048. async dispatchDidSave(detail) {
  7049. return this._scripting?.dispatchEventInSandbox({
  7050. id: 'doc',
  7051. name: 'DidSave'
  7052. });
  7053. }
  7054. async dispatchWillPrint(detail) {
  7055. return this._scripting?.dispatchEventInSandbox({
  7056. id: 'doc',
  7057. name: 'WillPrint'
  7058. });
  7059. }
  7060. async dispatchDidPrint(detail) {
  7061. return this._scripting?.dispatchEventInSandbox({
  7062. id: 'doc',
  7063. name: 'DidPrint'
  7064. });
  7065. }
  7066. get destroyPromise() {
  7067. return this._destroyCapability?.promise || null;
  7068. }
  7069. get ready() {
  7070. return this._ready;
  7071. }
  7072. get _internalEvents() {
  7073. return (0, _pdfjsLib.shadow)(this, '_internalEvents', new Map());
  7074. }
  7075. get _pageOpenPending() {
  7076. return (0, _pdfjsLib.shadow)(this, '_pageOpenPending', new Set());
  7077. }
  7078. get _visitedPages() {
  7079. return (0, _pdfjsLib.shadow)(this, '_visitedPages', new Map());
  7080. }
  7081. async _updateFromSandbox(detail) {
  7082. const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode;
  7083. const { id, siblings, command, value } = detail;
  7084. if (!id) {
  7085. switch (command) {
  7086. case 'clear':
  7087. console.clear();
  7088. break;
  7089. case 'error':
  7090. console.error(value);
  7091. break;
  7092. case 'layout': {
  7093. if (isInPresentationMode) {
  7094. return;
  7095. }
  7096. const modes = (0, _ui_utils.apiPageLayoutToViewerModes)(value);
  7097. this._pdfViewer.spreadMode = modes.spreadMode;
  7098. break;
  7099. }
  7100. case 'page-num':
  7101. this._pdfViewer.currentPageNumber = value + 1;
  7102. break;
  7103. case 'print':
  7104. await this._pdfViewer.pagesPromise;
  7105. this._eventBus.dispatch('print', {
  7106. source: this
  7107. });
  7108. break;
  7109. case 'println':
  7110. console.log(value);
  7111. break;
  7112. case 'zoom':
  7113. if (isInPresentationMode) {
  7114. return;
  7115. }
  7116. this._pdfViewer.currentScaleValue = value;
  7117. break;
  7118. case 'SaveAs':
  7119. this._eventBus.dispatch('download', {
  7120. source: this
  7121. });
  7122. break;
  7123. case 'FirstPage':
  7124. this._pdfViewer.currentPageNumber = 1;
  7125. break;
  7126. case 'LastPage':
  7127. this._pdfViewer.currentPageNumber = this._pdfViewer.pagesCount;
  7128. break;
  7129. case 'NextPage':
  7130. this._pdfViewer.nextPage();
  7131. break;
  7132. case 'PrevPage':
  7133. this._pdfViewer.previousPage();
  7134. break;
  7135. case 'ZoomViewIn':
  7136. if (isInPresentationMode) {
  7137. return;
  7138. }
  7139. this._pdfViewer.increaseScale();
  7140. break;
  7141. case 'ZoomViewOut':
  7142. if (isInPresentationMode) {
  7143. return;
  7144. }
  7145. this._pdfViewer.decreaseScale();
  7146. break;
  7147. }
  7148. return;
  7149. }
  7150. if (isInPresentationMode) {
  7151. if (detail.focus) {
  7152. return;
  7153. }
  7154. }
  7155. delete detail.id;
  7156. delete detail.siblings;
  7157. const ids = siblings ? [id, ...siblings] : [id];
  7158. for (const elementId of ids) {
  7159. const element = document.querySelector(`[data-element-id="${elementId}"]`);
  7160. if (element) {
  7161. element.dispatchEvent(
  7162. new CustomEvent('updatefromsandbox', {
  7163. detail
  7164. })
  7165. );
  7166. } else {
  7167. this._pdfDocument?.annotationStorage.setValue(elementId, detail);
  7168. }
  7169. }
  7170. }
  7171. async _dispatchPageOpen(pageNumber, initialize = false) {
  7172. const pdfDocument = this._pdfDocument,
  7173. visitedPages = this._visitedPages;
  7174. if (initialize) {
  7175. this._closeCapability = new _pdfjsLib.PromiseCapability();
  7176. }
  7177. if (!this._closeCapability) {
  7178. return;
  7179. }
  7180. const pageView = this._pdfViewer.getPageView(pageNumber - 1);
  7181. if (pageView?.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  7182. this._pageOpenPending.add(pageNumber);
  7183. return;
  7184. }
  7185. this._pageOpenPending.delete(pageNumber);
  7186. const actionsPromise = (async () => {
  7187. const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null);
  7188. if (pdfDocument !== this._pdfDocument) {
  7189. return;
  7190. }
  7191. await this._scripting?.dispatchEventInSandbox({
  7192. id: 'page',
  7193. name: 'PageOpen',
  7194. pageNumber,
  7195. actions
  7196. });
  7197. })();
  7198. visitedPages.set(pageNumber, actionsPromise);
  7199. }
  7200. async _dispatchPageClose(pageNumber) {
  7201. const pdfDocument = this._pdfDocument,
  7202. visitedPages = this._visitedPages;
  7203. if (!this._closeCapability) {
  7204. return;
  7205. }
  7206. if (this._pageOpenPending.has(pageNumber)) {
  7207. return;
  7208. }
  7209. const actionsPromise = visitedPages.get(pageNumber);
  7210. if (!actionsPromise) {
  7211. return;
  7212. }
  7213. visitedPages.set(pageNumber, null);
  7214. await actionsPromise;
  7215. if (pdfDocument !== this._pdfDocument) {
  7216. return;
  7217. }
  7218. await this._scripting?.dispatchEventInSandbox({
  7219. id: 'page',
  7220. name: 'PageClose',
  7221. pageNumber
  7222. });
  7223. }
  7224. async _getDocProperties() {
  7225. if (this._docPropertiesLookup) {
  7226. return this._docPropertiesLookup(this._pdfDocument);
  7227. }
  7228. throw new Error('_getDocProperties: Unable to lookup properties.');
  7229. }
  7230. _createScripting() {
  7231. this._destroyCapability = new _pdfjsLib.PromiseCapability();
  7232. if (this._scripting) {
  7233. throw new Error('_createScripting: Scripting already exists.');
  7234. }
  7235. if (this._scriptingFactory) {
  7236. return this._scriptingFactory.createScripting({
  7237. sandboxBundleSrc: this._sandboxBundleSrc
  7238. });
  7239. }
  7240. throw new Error('_createScripting: Cannot create scripting.');
  7241. }
  7242. async _destroyScripting() {
  7243. if (!this._scripting) {
  7244. this._pdfDocument = null;
  7245. this._destroyCapability?.resolve();
  7246. return;
  7247. }
  7248. if (this._closeCapability) {
  7249. await Promise.race([
  7250. this._closeCapability.promise,
  7251. new Promise((resolve) => {
  7252. setTimeout(resolve, 1000);
  7253. })
  7254. ]).catch((reason) => {});
  7255. this._closeCapability = null;
  7256. }
  7257. this._pdfDocument = null;
  7258. try {
  7259. await this._scripting.destroySandbox();
  7260. } catch (ex) {}
  7261. for (const [name, listener] of this._internalEvents) {
  7262. this._eventBus._off(name, listener);
  7263. }
  7264. this._internalEvents.clear();
  7265. this._pageOpenPending.clear();
  7266. this._visitedPages.clear();
  7267. this._scripting = null;
  7268. this._ready = false;
  7269. this._destroyCapability?.resolve();
  7270. }
  7271. }
  7272. exports.PDFScriptingManager = PDFScriptingManager;
  7273. /***/
  7274. },
  7275. /* 25 */
  7276. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  7277. Object.defineProperty(exports, '__esModule', {
  7278. value: true
  7279. });
  7280. exports.PDFSidebar = void 0;
  7281. var _ui_utils = __webpack_require__(3);
  7282. const SIDEBAR_WIDTH_VAR = '--sidebar-width';
  7283. const SIDEBAR_MIN_WIDTH = 200;
  7284. const SIDEBAR_RESIZING_CLASS = 'sidebarResizing';
  7285. const UI_NOTIFICATION_CLASS = 'pdfSidebarNotification';
  7286. class PDFSidebar {
  7287. #isRTL = false;
  7288. #mouseMoveBound = this.#mouseMove.bind(this);
  7289. #mouseUpBound = this.#mouseUp.bind(this);
  7290. #outerContainerWidth = null;
  7291. #width = null;
  7292. constructor({ elements, eventBus, l10n }) {
  7293. this.isOpen = false;
  7294. this.active = _ui_utils.SidebarView.THUMBS;
  7295. this.isInitialViewSet = false;
  7296. this.isInitialEventDispatched = false;
  7297. this.onToggled = null;
  7298. this.onUpdateThumbnails = null;
  7299. this.outerContainer = elements.outerContainer;
  7300. this.sidebarContainer = elements.sidebarContainer;
  7301. this.toggleButton = elements.toggleButton;
  7302. this.resizer = elements.resizer;
  7303. this.thumbnailButton = elements.thumbnailButton;
  7304. this.outlineButton = elements.outlineButton;
  7305. this.attachmentsButton = elements.attachmentsButton;
  7306. this.layersButton = elements.layersButton;
  7307. this.thumbnailView = elements.thumbnailView;
  7308. this.outlineView = elements.outlineView;
  7309. this.attachmentsView = elements.attachmentsView;
  7310. this.layersView = elements.layersView;
  7311. this._outlineOptionsContainer = elements.outlineOptionsContainer;
  7312. this._currentOutlineItemButton = elements.currentOutlineItemButton;
  7313. this.eventBus = eventBus;
  7314. this.l10n = l10n;
  7315. l10n.getDirection().then((dir) => {
  7316. this.#isRTL = dir === 'rtl';
  7317. });
  7318. this.#addEventListeners();
  7319. }
  7320. reset() {
  7321. this.isInitialViewSet = false;
  7322. this.isInitialEventDispatched = false;
  7323. this.#hideUINotification(true);
  7324. this.switchView(_ui_utils.SidebarView.THUMBS);
  7325. this.outlineButton.disabled = false;
  7326. this.attachmentsButton.disabled = false;
  7327. this.layersButton.disabled = false;
  7328. this._currentOutlineItemButton.disabled = true;
  7329. }
  7330. get visibleView() {
  7331. return this.isOpen ? this.active : _ui_utils.SidebarView.NONE;
  7332. }
  7333. setInitialView(view = _ui_utils.SidebarView.NONE) {
  7334. if (this.isInitialViewSet) {
  7335. return;
  7336. }
  7337. this.isInitialViewSet = true;
  7338. if (view === _ui_utils.SidebarView.NONE || view === _ui_utils.SidebarView.UNKNOWN) {
  7339. this.#dispatchEvent();
  7340. return;
  7341. }
  7342. this.switchView(view, true);
  7343. if (!this.isInitialEventDispatched) {
  7344. this.#dispatchEvent();
  7345. }
  7346. }
  7347. switchView(view, forceOpen = false) {
  7348. const isViewChanged = view !== this.active;
  7349. let forceRendering = false;
  7350. switch (view) {
  7351. case _ui_utils.SidebarView.NONE:
  7352. if (this.isOpen) {
  7353. this.close();
  7354. }
  7355. return;
  7356. case _ui_utils.SidebarView.THUMBS:
  7357. if (this.isOpen && isViewChanged) {
  7358. forceRendering = true;
  7359. }
  7360. break;
  7361. case _ui_utils.SidebarView.OUTLINE:
  7362. if (this.outlineButton.disabled) {
  7363. return;
  7364. }
  7365. break;
  7366. case _ui_utils.SidebarView.ATTACHMENTS:
  7367. if (this.attachmentsButton.disabled) {
  7368. return;
  7369. }
  7370. break;
  7371. case _ui_utils.SidebarView.LAYERS:
  7372. if (this.layersButton.disabled) {
  7373. return;
  7374. }
  7375. break;
  7376. default:
  7377. console.error(`PDFSidebar.switchView: "${view}" is not a valid view.`);
  7378. return;
  7379. }
  7380. this.active = view;
  7381. (0, _ui_utils.toggleCheckedBtn)(this.thumbnailButton, view === _ui_utils.SidebarView.THUMBS, this.thumbnailView);
  7382. (0, _ui_utils.toggleCheckedBtn)(this.outlineButton, view === _ui_utils.SidebarView.OUTLINE, this.outlineView);
  7383. (0, _ui_utils.toggleCheckedBtn)(this.attachmentsButton, view === _ui_utils.SidebarView.ATTACHMENTS, this.attachmentsView);
  7384. (0, _ui_utils.toggleCheckedBtn)(this.layersButton, view === _ui_utils.SidebarView.LAYERS, this.layersView);
  7385. this._outlineOptionsContainer.classList.toggle('hidden', view !== _ui_utils.SidebarView.OUTLINE);
  7386. if (forceOpen && !this.isOpen) {
  7387. this.open();
  7388. return;
  7389. }
  7390. if (forceRendering) {
  7391. this.onUpdateThumbnails();
  7392. this.onToggled();
  7393. }
  7394. if (isViewChanged) {
  7395. this.#dispatchEvent();
  7396. }
  7397. }
  7398. open() {
  7399. if (this.isOpen) {
  7400. return;
  7401. }
  7402. this.isOpen = true;
  7403. (0, _ui_utils.toggleExpandedBtn)(this.toggleButton, true);
  7404. this.outerContainer.classList.add('sidebarMoving', 'sidebarOpen');
  7405. if (this.active === _ui_utils.SidebarView.THUMBS) {
  7406. this.onUpdateThumbnails();
  7407. }
  7408. this.onToggled();
  7409. this.#dispatchEvent();
  7410. this.#hideUINotification();
  7411. }
  7412. close() {
  7413. if (!this.isOpen) {
  7414. return;
  7415. }
  7416. this.isOpen = false;
  7417. (0, _ui_utils.toggleExpandedBtn)(this.toggleButton, false);
  7418. this.outerContainer.classList.add('sidebarMoving');
  7419. this.outerContainer.classList.remove('sidebarOpen');
  7420. this.onToggled();
  7421. this.#dispatchEvent();
  7422. }
  7423. toggle() {
  7424. if (this.isOpen) {
  7425. this.close();
  7426. } else {
  7427. this.open();
  7428. }
  7429. }
  7430. #dispatchEvent() {
  7431. if (this.isInitialViewSet) {
  7432. this.isInitialEventDispatched ||= true;
  7433. }
  7434. this.eventBus.dispatch('sidebarviewchanged', {
  7435. source: this,
  7436. view: this.visibleView
  7437. });
  7438. }
  7439. #showUINotification() {
  7440. this.toggleButton.setAttribute('data-l10n-id', 'toggle_sidebar_notification2');
  7441. this.l10n.translate(this.toggleButton);
  7442. if (!this.isOpen) {
  7443. this.toggleButton.classList.add(UI_NOTIFICATION_CLASS);
  7444. }
  7445. }
  7446. #hideUINotification(reset = false) {
  7447. if (this.isOpen || reset) {
  7448. this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS);
  7449. }
  7450. if (reset) {
  7451. this.toggleButton.setAttribute('data-l10n-id', 'toggle_sidebar');
  7452. this.l10n.translate(this.toggleButton);
  7453. }
  7454. }
  7455. #addEventListeners() {
  7456. this.sidebarContainer.addEventListener('transitionend', (evt) => {
  7457. if (evt.target === this.sidebarContainer) {
  7458. this.outerContainer.classList.remove('sidebarMoving');
  7459. }
  7460. });
  7461. this.toggleButton.addEventListener('click', () => {
  7462. this.toggle();
  7463. });
  7464. this.thumbnailButton.addEventListener('click', () => {
  7465. this.switchView(_ui_utils.SidebarView.THUMBS);
  7466. });
  7467. this.outlineButton.addEventListener('click', () => {
  7468. this.switchView(_ui_utils.SidebarView.OUTLINE);
  7469. });
  7470. this.outlineButton.addEventListener('dblclick', () => {
  7471. this.eventBus.dispatch('toggleoutlinetree', {
  7472. source: this
  7473. });
  7474. });
  7475. this.attachmentsButton.addEventListener('click', () => {
  7476. this.switchView(_ui_utils.SidebarView.ATTACHMENTS);
  7477. });
  7478. this.layersButton.addEventListener('click', () => {
  7479. this.switchView(_ui_utils.SidebarView.LAYERS);
  7480. });
  7481. this.layersButton.addEventListener('dblclick', () => {
  7482. this.eventBus.dispatch('resetlayers', {
  7483. source: this
  7484. });
  7485. });
  7486. this._currentOutlineItemButton.addEventListener('click', () => {
  7487. this.eventBus.dispatch('currentoutlineitem', {
  7488. source: this
  7489. });
  7490. });
  7491. const onTreeLoaded = (count, button, view) => {
  7492. button.disabled = !count;
  7493. if (count) {
  7494. this.#showUINotification();
  7495. } else if (this.active === view) {
  7496. this.switchView(_ui_utils.SidebarView.THUMBS);
  7497. }
  7498. };
  7499. this.eventBus._on('outlineloaded', (evt) => {
  7500. onTreeLoaded(evt.outlineCount, this.outlineButton, _ui_utils.SidebarView.OUTLINE);
  7501. evt.currentOutlineItemPromise.then((enabled) => {
  7502. if (!this.isInitialViewSet) {
  7503. return;
  7504. }
  7505. this._currentOutlineItemButton.disabled = !enabled;
  7506. });
  7507. });
  7508. this.eventBus._on('attachmentsloaded', (evt) => {
  7509. onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, _ui_utils.SidebarView.ATTACHMENTS);
  7510. });
  7511. this.eventBus._on('layersloaded', (evt) => {
  7512. onTreeLoaded(evt.layersCount, this.layersButton, _ui_utils.SidebarView.LAYERS);
  7513. });
  7514. this.eventBus._on('presentationmodechanged', (evt) => {
  7515. if (evt.state === _ui_utils.PresentationModeState.NORMAL && this.visibleView === _ui_utils.SidebarView.THUMBS) {
  7516. this.onUpdateThumbnails();
  7517. }
  7518. });
  7519. this.resizer.addEventListener('mousedown', (evt) => {
  7520. if (evt.button !== 0) {
  7521. return;
  7522. }
  7523. this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS);
  7524. window.addEventListener('mousemove', this.#mouseMoveBound);
  7525. window.addEventListener('mouseup', this.#mouseUpBound);
  7526. });
  7527. this.eventBus._on('resize', (evt) => {
  7528. if (evt.source !== window) {
  7529. return;
  7530. }
  7531. this.#outerContainerWidth = null;
  7532. if (!this.#width) {
  7533. return;
  7534. }
  7535. if (!this.isOpen) {
  7536. this.#updateWidth(this.#width);
  7537. return;
  7538. }
  7539. this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS);
  7540. const updated = this.#updateWidth(this.#width);
  7541. Promise.resolve().then(() => {
  7542. this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS);
  7543. if (updated) {
  7544. this.eventBus.dispatch('resize', {
  7545. source: this
  7546. });
  7547. }
  7548. });
  7549. });
  7550. }
  7551. get outerContainerWidth() {
  7552. return (this.#outerContainerWidth ||= this.outerContainer.clientWidth);
  7553. }
  7554. #updateWidth(width = 0) {
  7555. const maxWidth = Math.floor(this.outerContainerWidth / 2);
  7556. if (width > maxWidth) {
  7557. width = maxWidth;
  7558. }
  7559. if (width < SIDEBAR_MIN_WIDTH) {
  7560. width = SIDEBAR_MIN_WIDTH;
  7561. }
  7562. if (width === this.#width) {
  7563. return false;
  7564. }
  7565. this.#width = width;
  7566. _ui_utils.docStyle.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`);
  7567. return true;
  7568. }
  7569. #mouseMove(evt) {
  7570. let width = evt.clientX;
  7571. if (this.#isRTL) {
  7572. width = this.outerContainerWidth - width;
  7573. }
  7574. this.#updateWidth(width);
  7575. }
  7576. #mouseUp(evt) {
  7577. this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS);
  7578. this.eventBus.dispatch('resize', {
  7579. source: this
  7580. });
  7581. window.removeEventListener('mousemove', this.#mouseMoveBound);
  7582. window.removeEventListener('mouseup', this.#mouseUpBound);
  7583. }
  7584. }
  7585. exports.PDFSidebar = PDFSidebar;
  7586. /***/
  7587. },
  7588. /* 26 */
  7589. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  7590. Object.defineProperty(exports, '__esModule', {
  7591. value: true
  7592. });
  7593. exports.PDFThumbnailViewer = void 0;
  7594. var _ui_utils = __webpack_require__(3);
  7595. var _pdf_thumbnail_view = __webpack_require__(27);
  7596. const THUMBNAIL_SCROLL_MARGIN = -19;
  7597. const THUMBNAIL_SELECTED_CLASS = 'selected';
  7598. class PDFThumbnailViewer {
  7599. constructor({ container, eventBus, linkService, renderingQueue, l10n, pageColors }) {
  7600. this.container = container;
  7601. this.eventBus = eventBus;
  7602. this.linkService = linkService;
  7603. this.renderingQueue = renderingQueue;
  7604. this.l10n = l10n;
  7605. this.pageColors = pageColors || null;
  7606. if (this.pageColors && !(CSS.supports('color', this.pageColors.background) && CSS.supports('color', this.pageColors.foreground))) {
  7607. if (this.pageColors.background || this.pageColors.foreground) {
  7608. console.warn("PDFThumbnailViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used.");
  7609. }
  7610. this.pageColors = null;
  7611. }
  7612. this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdated.bind(this));
  7613. this._resetView();
  7614. }
  7615. _scrollUpdated() {
  7616. this.renderingQueue.renderHighestPriority();
  7617. }
  7618. getThumbnail(index) {
  7619. return this._thumbnails[index];
  7620. }
  7621. _getVisibleThumbs() {
  7622. return (0, _ui_utils.getVisibleElements)({
  7623. scrollEl: this.container,
  7624. views: this._thumbnails
  7625. });
  7626. }
  7627. scrollThumbnailIntoView(pageNumber) {
  7628. if (!this.pdfDocument) {
  7629. return;
  7630. }
  7631. const thumbnailView = this._thumbnails[pageNumber - 1];
  7632. if (!thumbnailView) {
  7633. console.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.');
  7634. return;
  7635. }
  7636. if (pageNumber !== this._currentPageNumber) {
  7637. const prevThumbnailView = this._thumbnails[this._currentPageNumber - 1];
  7638. prevThumbnailView.div.classList.remove(THUMBNAIL_SELECTED_CLASS);
  7639. thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS);
  7640. }
  7641. const { first, last, views } = this._getVisibleThumbs();
  7642. if (views.length > 0) {
  7643. let shouldScroll = false;
  7644. if (pageNumber <= first.id || pageNumber >= last.id) {
  7645. shouldScroll = true;
  7646. } else {
  7647. for (const { id, percent } of views) {
  7648. if (id !== pageNumber) {
  7649. continue;
  7650. }
  7651. shouldScroll = percent < 100;
  7652. break;
  7653. }
  7654. }
  7655. if (shouldScroll) {
  7656. (0, _ui_utils.scrollIntoView)(thumbnailView.div, {
  7657. top: THUMBNAIL_SCROLL_MARGIN
  7658. });
  7659. }
  7660. }
  7661. this._currentPageNumber = pageNumber;
  7662. }
  7663. get pagesRotation() {
  7664. return this._pagesRotation;
  7665. }
  7666. set pagesRotation(rotation) {
  7667. if (!(0, _ui_utils.isValidRotation)(rotation)) {
  7668. throw new Error('Invalid thumbnails rotation angle.');
  7669. }
  7670. if (!this.pdfDocument) {
  7671. return;
  7672. }
  7673. if (this._pagesRotation === rotation) {
  7674. return;
  7675. }
  7676. this._pagesRotation = rotation;
  7677. const updateArgs = {
  7678. rotation
  7679. };
  7680. for (const thumbnail of this._thumbnails) {
  7681. thumbnail.update(updateArgs);
  7682. }
  7683. }
  7684. cleanup() {
  7685. for (const thumbnail of this._thumbnails) {
  7686. if (thumbnail.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  7687. thumbnail.reset();
  7688. }
  7689. }
  7690. _pdf_thumbnail_view.TempImageFactory.destroyCanvas();
  7691. }
  7692. _resetView() {
  7693. this._thumbnails = [];
  7694. this._currentPageNumber = 1;
  7695. this._pageLabels = null;
  7696. this._pagesRotation = 0;
  7697. this.container.textContent = '';
  7698. }
  7699. setDocument(pdfDocument) {
  7700. if (this.pdfDocument) {
  7701. this._cancelRendering();
  7702. this._resetView();
  7703. }
  7704. this.pdfDocument = pdfDocument;
  7705. if (!pdfDocument) {
  7706. return;
  7707. }
  7708. const firstPagePromise = pdfDocument.getPage(1);
  7709. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();
  7710. firstPagePromise
  7711. .then((firstPdfPage) => {
  7712. const pagesCount = pdfDocument.numPages;
  7713. const viewport = firstPdfPage.getViewport({
  7714. scale: 1
  7715. });
  7716. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  7717. const thumbnail = new _pdf_thumbnail_view.PDFThumbnailView({
  7718. container: this.container,
  7719. eventBus: this.eventBus,
  7720. id: pageNum,
  7721. defaultViewport: viewport.clone(),
  7722. optionalContentConfigPromise,
  7723. linkService: this.linkService,
  7724. renderingQueue: this.renderingQueue,
  7725. l10n: this.l10n,
  7726. pageColors: this.pageColors
  7727. });
  7728. this._thumbnails.push(thumbnail);
  7729. }
  7730. this._thumbnails[0]?.setPdfPage(firstPdfPage);
  7731. const thumbnailView = this._thumbnails[this._currentPageNumber - 1];
  7732. thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS);
  7733. })
  7734. .catch((reason) => {
  7735. console.error('Unable to initialize thumbnail viewer', reason);
  7736. });
  7737. }
  7738. _cancelRendering() {
  7739. for (const thumbnail of this._thumbnails) {
  7740. thumbnail.cancelRendering();
  7741. }
  7742. }
  7743. setPageLabels(labels) {
  7744. if (!this.pdfDocument) {
  7745. return;
  7746. }
  7747. if (!labels) {
  7748. this._pageLabels = null;
  7749. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  7750. this._pageLabels = null;
  7751. console.error('PDFThumbnailViewer_setPageLabels: Invalid page labels.');
  7752. } else {
  7753. this._pageLabels = labels;
  7754. }
  7755. for (let i = 0, ii = this._thumbnails.length; i < ii; i++) {
  7756. this._thumbnails[i].setPageLabel(this._pageLabels?.[i] ?? null);
  7757. }
  7758. }
  7759. async #ensurePdfPageLoaded(thumbView) {
  7760. if (thumbView.pdfPage) {
  7761. return thumbView.pdfPage;
  7762. }
  7763. try {
  7764. const pdfPage = await this.pdfDocument.getPage(thumbView.id);
  7765. if (!thumbView.pdfPage) {
  7766. thumbView.setPdfPage(pdfPage);
  7767. }
  7768. return pdfPage;
  7769. } catch (reason) {
  7770. console.error('Unable to get page for thumb view', reason);
  7771. return null;
  7772. }
  7773. }
  7774. #getScrollAhead(visible) {
  7775. if (visible.first?.id === 1) {
  7776. return true;
  7777. } else if (visible.last?.id === this._thumbnails.length) {
  7778. return false;
  7779. }
  7780. return this.scroll.down;
  7781. }
  7782. forceRendering() {
  7783. const visibleThumbs = this._getVisibleThumbs();
  7784. const scrollAhead = this.#getScrollAhead(visibleThumbs);
  7785. const thumbView = this.renderingQueue.getHighestPriority(visibleThumbs, this._thumbnails, scrollAhead);
  7786. if (thumbView) {
  7787. this.#ensurePdfPageLoaded(thumbView).then(() => {
  7788. this.renderingQueue.renderView(thumbView);
  7789. });
  7790. return true;
  7791. }
  7792. return false;
  7793. }
  7794. }
  7795. exports.PDFThumbnailViewer = PDFThumbnailViewer;
  7796. /***/
  7797. },
  7798. /* 27 */
  7799. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  7800. Object.defineProperty(exports, '__esModule', {
  7801. value: true
  7802. });
  7803. exports.TempImageFactory = exports.PDFThumbnailView = void 0;
  7804. var _ui_utils = __webpack_require__(3);
  7805. var _pdfjsLib = __webpack_require__(4);
  7806. const DRAW_UPSCALE_FACTOR = 2;
  7807. const MAX_NUM_SCALING_STEPS = 3;
  7808. const THUMBNAIL_WIDTH = 98;
  7809. class TempImageFactory {
  7810. static #tempCanvas = null;
  7811. static getCanvas(width, height) {
  7812. const tempCanvas = (this.#tempCanvas ||= document.createElement('canvas'));
  7813. tempCanvas.width = width;
  7814. tempCanvas.height = height;
  7815. const ctx = tempCanvas.getContext('2d', {
  7816. alpha: false
  7817. });
  7818. ctx.save();
  7819. ctx.fillStyle = 'rgb(255, 255, 255)';
  7820. ctx.fillRect(0, 0, width, height);
  7821. ctx.restore();
  7822. return [tempCanvas, tempCanvas.getContext('2d')];
  7823. }
  7824. static destroyCanvas() {
  7825. const tempCanvas = this.#tempCanvas;
  7826. if (tempCanvas) {
  7827. tempCanvas.width = 0;
  7828. tempCanvas.height = 0;
  7829. }
  7830. this.#tempCanvas = null;
  7831. }
  7832. }
  7833. exports.TempImageFactory = TempImageFactory;
  7834. class PDFThumbnailView {
  7835. constructor({ container, eventBus, id, defaultViewport, optionalContentConfigPromise, linkService, renderingQueue, l10n, pageColors }) {
  7836. this.id = id;
  7837. this.renderingId = 'thumbnail' + id;
  7838. this.pageLabel = null;
  7839. this.pdfPage = null;
  7840. this.rotation = 0;
  7841. this.viewport = defaultViewport;
  7842. this.pdfPageRotate = defaultViewport.rotation;
  7843. this._optionalContentConfigPromise = optionalContentConfigPromise || null;
  7844. this.pageColors = pageColors || null;
  7845. this.eventBus = eventBus;
  7846. this.linkService = linkService;
  7847. this.renderingQueue = renderingQueue;
  7848. this.renderTask = null;
  7849. this.renderingState = _ui_utils.RenderingStates.INITIAL;
  7850. this.resume = null;
  7851. this.l10n = l10n;
  7852. const anchor = document.createElement('a');
  7853. anchor.href = linkService.getAnchorUrl('#page=' + id);
  7854. this._thumbPageTitle.then((msg) => {
  7855. anchor.title = msg;
  7856. });
  7857. anchor.onclick = function () {
  7858. linkService.goToPage(id);
  7859. return false;
  7860. };
  7861. this.anchor = anchor;
  7862. const div = document.createElement('div');
  7863. div.className = 'thumbnail';
  7864. div.setAttribute('data-page-number', this.id);
  7865. this.div = div;
  7866. this.#updateDims();
  7867. const img = document.createElement('div');
  7868. img.className = 'thumbnailImage';
  7869. this._placeholderImg = img;
  7870. div.append(img);
  7871. anchor.append(div);
  7872. container.append(anchor);
  7873. }
  7874. #updateDims() {
  7875. const { width, height } = this.viewport;
  7876. const ratio = width / height;
  7877. this.canvasWidth = THUMBNAIL_WIDTH;
  7878. this.canvasHeight = (this.canvasWidth / ratio) | 0;
  7879. this.scale = this.canvasWidth / width;
  7880. const { style } = this.div;
  7881. style.setProperty('--thumbnail-width', `${this.canvasWidth}px`);
  7882. style.setProperty('--thumbnail-height', `${this.canvasHeight}px`);
  7883. }
  7884. setPdfPage(pdfPage) {
  7885. this.pdfPage = pdfPage;
  7886. this.pdfPageRotate = pdfPage.rotate;
  7887. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  7888. this.viewport = pdfPage.getViewport({
  7889. scale: 1,
  7890. rotation: totalRotation
  7891. });
  7892. this.reset();
  7893. }
  7894. reset() {
  7895. this.cancelRendering();
  7896. this.renderingState = _ui_utils.RenderingStates.INITIAL;
  7897. this.div.removeAttribute('data-loaded');
  7898. this.image?.replaceWith(this._placeholderImg);
  7899. this.#updateDims();
  7900. if (this.image) {
  7901. this.image.removeAttribute('src');
  7902. delete this.image;
  7903. }
  7904. }
  7905. update({ rotation = null }) {
  7906. if (typeof rotation === 'number') {
  7907. this.rotation = rotation;
  7908. }
  7909. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  7910. this.viewport = this.viewport.clone({
  7911. scale: 1,
  7912. rotation: totalRotation
  7913. });
  7914. this.reset();
  7915. }
  7916. cancelRendering() {
  7917. if (this.renderTask) {
  7918. this.renderTask.cancel();
  7919. this.renderTask = null;
  7920. }
  7921. this.resume = null;
  7922. }
  7923. _getPageDrawContext(upscaleFactor = 1) {
  7924. const canvas = document.createElement('canvas');
  7925. const ctx = canvas.getContext('2d', {
  7926. alpha: false
  7927. });
  7928. const outputScale = new _ui_utils.OutputScale();
  7929. canvas.width = (upscaleFactor * this.canvasWidth * outputScale.sx) | 0;
  7930. canvas.height = (upscaleFactor * this.canvasHeight * outputScale.sy) | 0;
  7931. const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null;
  7932. return {
  7933. ctx,
  7934. canvas,
  7935. transform
  7936. };
  7937. }
  7938. _convertCanvasToImage(canvas) {
  7939. if (this.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  7940. throw new Error('_convertCanvasToImage: Rendering has not finished.');
  7941. }
  7942. const reducedCanvas = this._reduceImage(canvas);
  7943. const image = document.createElement('img');
  7944. image.className = 'thumbnailImage';
  7945. this._thumbPageCanvas.then((msg) => {
  7946. image.setAttribute('aria-label', msg);
  7947. });
  7948. image.src = reducedCanvas.toDataURL();
  7949. this.image = image;
  7950. this.div.setAttribute('data-loaded', true);
  7951. this._placeholderImg.replaceWith(image);
  7952. reducedCanvas.width = 0;
  7953. reducedCanvas.height = 0;
  7954. }
  7955. async #finishRenderTask(renderTask, canvas, error = null) {
  7956. if (renderTask === this.renderTask) {
  7957. this.renderTask = null;
  7958. }
  7959. if (error instanceof _pdfjsLib.RenderingCancelledException) {
  7960. return;
  7961. }
  7962. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  7963. this._convertCanvasToImage(canvas);
  7964. if (error) {
  7965. throw error;
  7966. }
  7967. }
  7968. async draw() {
  7969. if (this.renderingState !== _ui_utils.RenderingStates.INITIAL) {
  7970. console.error('Must be in new state before drawing');
  7971. return undefined;
  7972. }
  7973. const { pdfPage } = this;
  7974. if (!pdfPage) {
  7975. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  7976. throw new Error('pdfPage is not loaded');
  7977. }
  7978. this.renderingState = _ui_utils.RenderingStates.RUNNING;
  7979. const { ctx, canvas, transform } = this._getPageDrawContext(DRAW_UPSCALE_FACTOR);
  7980. const drawViewport = this.viewport.clone({
  7981. scale: DRAW_UPSCALE_FACTOR * this.scale
  7982. });
  7983. const renderContinueCallback = (cont) => {
  7984. if (!this.renderingQueue.isHighestPriority(this)) {
  7985. this.renderingState = _ui_utils.RenderingStates.PAUSED;
  7986. this.resume = () => {
  7987. this.renderingState = _ui_utils.RenderingStates.RUNNING;
  7988. cont();
  7989. };
  7990. return;
  7991. }
  7992. cont();
  7993. };
  7994. const renderContext = {
  7995. canvasContext: ctx,
  7996. transform,
  7997. viewport: drawViewport,
  7998. optionalContentConfigPromise: this._optionalContentConfigPromise,
  7999. pageColors: this.pageColors
  8000. };
  8001. const renderTask = (this.renderTask = pdfPage.render(renderContext));
  8002. renderTask.onContinue = renderContinueCallback;
  8003. const resultPromise = renderTask.promise.then(
  8004. () => this.#finishRenderTask(renderTask, canvas),
  8005. (error) => this.#finishRenderTask(renderTask, canvas, error)
  8006. );
  8007. resultPromise.finally(() => {
  8008. canvas.width = 0;
  8009. canvas.height = 0;
  8010. this.eventBus.dispatch('thumbnailrendered', {
  8011. source: this,
  8012. pageNumber: this.id,
  8013. pdfPage: this.pdfPage
  8014. });
  8015. });
  8016. return resultPromise;
  8017. }
  8018. setImage(pageView) {
  8019. if (this.renderingState !== _ui_utils.RenderingStates.INITIAL) {
  8020. return;
  8021. }
  8022. const { thumbnailCanvas: canvas, pdfPage, scale } = pageView;
  8023. if (!canvas) {
  8024. return;
  8025. }
  8026. if (!this.pdfPage) {
  8027. this.setPdfPage(pdfPage);
  8028. }
  8029. if (scale < this.scale) {
  8030. return;
  8031. }
  8032. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  8033. this._convertCanvasToImage(canvas);
  8034. }
  8035. _reduceImage(img) {
  8036. const { ctx, canvas } = this._getPageDrawContext();
  8037. if (img.width <= 2 * canvas.width) {
  8038. ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
  8039. return canvas;
  8040. }
  8041. let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
  8042. let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
  8043. const [reducedImage, reducedImageCtx] = TempImageFactory.getCanvas(reducedWidth, reducedHeight);
  8044. while (reducedWidth > img.width || reducedHeight > img.height) {
  8045. reducedWidth >>= 1;
  8046. reducedHeight >>= 1;
  8047. }
  8048. reducedImageCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, reducedWidth, reducedHeight);
  8049. while (reducedWidth > 2 * canvas.width) {
  8050. reducedImageCtx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, reducedWidth >> 1, reducedHeight >> 1);
  8051. reducedWidth >>= 1;
  8052. reducedHeight >>= 1;
  8053. }
  8054. ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height);
  8055. return canvas;
  8056. }
  8057. get _thumbPageTitle() {
  8058. return this.l10n.get('thumb_page_title', {
  8059. page: this.pageLabel ?? this.id
  8060. });
  8061. }
  8062. get _thumbPageCanvas() {
  8063. return this.l10n.get('thumb_page_canvas', {
  8064. page: this.pageLabel ?? this.id
  8065. });
  8066. }
  8067. setPageLabel(label) {
  8068. this.pageLabel = typeof label === 'string' ? label : null;
  8069. this._thumbPageTitle.then((msg) => {
  8070. this.anchor.title = msg;
  8071. });
  8072. if (this.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  8073. return;
  8074. }
  8075. this._thumbPageCanvas.then((msg) => {
  8076. this.image?.setAttribute('aria-label', msg);
  8077. });
  8078. }
  8079. }
  8080. exports.PDFThumbnailView = PDFThumbnailView;
  8081. /***/
  8082. },
  8083. /* 28 */
  8084. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  8085. Object.defineProperty(exports, '__esModule', {
  8086. value: true
  8087. });
  8088. exports.PagesCountLimit = exports.PDFViewer = exports.PDFPageViewBuffer = void 0;
  8089. var _pdfjsLib = __webpack_require__(4);
  8090. var _ui_utils = __webpack_require__(3);
  8091. var _l10n_utils = __webpack_require__(29);
  8092. var _pdf_page_view = __webpack_require__(30);
  8093. var _pdf_rendering_queue = __webpack_require__(23);
  8094. var _pdf_link_service = __webpack_require__(7);
  8095. const DEFAULT_CACHE_SIZE = 10;
  8096. const PagesCountLimit = {
  8097. FORCE_SCROLL_MODE_PAGE: 15000,
  8098. FORCE_LAZY_PAGE_INIT: 7500,
  8099. PAUSE_EAGER_PAGE_INIT: 250
  8100. };
  8101. exports.PagesCountLimit = PagesCountLimit;
  8102. function isValidAnnotationEditorMode(mode) {
  8103. return Object.values(_pdfjsLib.AnnotationEditorType).includes(mode) && mode !== _pdfjsLib.AnnotationEditorType.DISABLE;
  8104. }
  8105. class PDFPageViewBuffer {
  8106. #buf = new Set();
  8107. #size = 0;
  8108. constructor(size) {
  8109. this.#size = size;
  8110. }
  8111. push(view) {
  8112. const buf = this.#buf;
  8113. if (buf.has(view)) {
  8114. buf.delete(view);
  8115. }
  8116. buf.add(view);
  8117. if (buf.size > this.#size) {
  8118. this.#destroyFirstView();
  8119. }
  8120. }
  8121. resize(newSize, idsToKeep = null) {
  8122. this.#size = newSize;
  8123. const buf = this.#buf;
  8124. if (idsToKeep) {
  8125. const ii = buf.size;
  8126. let i = 1;
  8127. for (const view of buf) {
  8128. if (idsToKeep.has(view.id)) {
  8129. buf.delete(view);
  8130. buf.add(view);
  8131. }
  8132. if (++i > ii) {
  8133. break;
  8134. }
  8135. }
  8136. }
  8137. while (buf.size > this.#size) {
  8138. this.#destroyFirstView();
  8139. }
  8140. }
  8141. has(view) {
  8142. return this.#buf.has(view);
  8143. }
  8144. [Symbol.iterator]() {
  8145. return this.#buf.keys();
  8146. }
  8147. #destroyFirstView() {
  8148. const firstView = this.#buf.keys().next().value;
  8149. firstView?.destroy();
  8150. this.#buf.delete(firstView);
  8151. }
  8152. }
  8153. exports.PDFPageViewBuffer = PDFPageViewBuffer;
  8154. class PDFViewer {
  8155. #buffer = null;
  8156. #annotationEditorMode = _pdfjsLib.AnnotationEditorType.NONE;
  8157. #annotationEditorUIManager = null;
  8158. #annotationMode = _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  8159. #containerTopLeft = null;
  8160. #copyCallbackBound = null;
  8161. #enablePermissions = false;
  8162. #getAllTextInProgress = false;
  8163. #hiddenCopyElement = null;
  8164. #interruptCopyCondition = false;
  8165. #previousContainerHeight = 0;
  8166. #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this));
  8167. #scrollModePageState = null;
  8168. #onVisibilityChange = null;
  8169. #scaleTimeoutId = null;
  8170. #textLayerMode = _ui_utils.TextLayerMode.ENABLE;
  8171. constructor(options) {
  8172. const viewerVersion = '3.7.107';
  8173. if (_pdfjsLib.version !== viewerVersion) {
  8174. throw new Error(`The API version "${_pdfjsLib.version}" does not match the Viewer version "${viewerVersion}".`);
  8175. }
  8176. this.container = options.container;
  8177. this.viewer = options.viewer || options.container.firstElementChild;
  8178. if (this.container?.tagName !== 'DIV' || this.viewer?.tagName !== 'DIV') {
  8179. throw new Error('Invalid `container` and/or `viewer` option.');
  8180. }
  8181. if (this.container.offsetParent && getComputedStyle(this.container).position !== 'absolute') {
  8182. throw new Error('The `container` must be absolutely positioned.');
  8183. }
  8184. this.#resizeObserver.observe(this.container);
  8185. this.eventBus = options.eventBus;
  8186. this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService();
  8187. this.downloadManager = options.downloadManager || null;
  8188. this.findController = options.findController || null;
  8189. if (this.findController) {
  8190. this.findController.onIsPageVisible = (pageNumber) => this._getVisiblePages().ids.has(pageNumber);
  8191. }
  8192. this._scriptingManager = options.scriptingManager || null;
  8193. this.#textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE;
  8194. this.#annotationMode = options.annotationMode ?? _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  8195. this.#annotationEditorMode = options.annotationEditorMode ?? _pdfjsLib.AnnotationEditorType.NONE;
  8196. this.imageResourcesPath = options.imageResourcesPath || '';
  8197. this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;
  8198. this.removePageBorders = options.removePageBorders || false;
  8199. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  8200. this.isOffscreenCanvasSupported = options.isOffscreenCanvasSupported ?? true;
  8201. this.maxCanvasPixels = options.maxCanvasPixels;
  8202. this.l10n = options.l10n || _l10n_utils.NullL10n;
  8203. this.#enablePermissions = options.enablePermissions || false;
  8204. this.pageColors = options.pageColors || null;
  8205. if (this.pageColors && !(CSS.supports('color', this.pageColors.background) && CSS.supports('color', this.pageColors.foreground))) {
  8206. if (this.pageColors.background || this.pageColors.foreground) {
  8207. console.warn("PDFViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used.");
  8208. }
  8209. this.pageColors = null;
  8210. }
  8211. this.defaultRenderingQueue = !options.renderingQueue;
  8212. if (this.defaultRenderingQueue) {
  8213. this.renderingQueue = new _pdf_rendering_queue.PDFRenderingQueue();
  8214. this.renderingQueue.setViewer(this);
  8215. } else {
  8216. this.renderingQueue = options.renderingQueue;
  8217. }
  8218. this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this));
  8219. this.presentationModeState = _ui_utils.PresentationModeState.UNKNOWN;
  8220. this._onBeforeDraw = this._onAfterDraw = null;
  8221. this._resetView();
  8222. if (this.removePageBorders) {
  8223. this.viewer.classList.add('removePageBorders');
  8224. }
  8225. this.#updateContainerHeightCss();
  8226. this.eventBus._on('thumbnailrendered', ({ pageNumber, pdfPage }) => {
  8227. const pageView = this._pages[pageNumber - 1];
  8228. if (!this.#buffer.has(pageView)) {
  8229. pdfPage?.cleanup();
  8230. }
  8231. });
  8232. }
  8233. get pagesCount() {
  8234. return this._pages.length;
  8235. }
  8236. getPageView(index) {
  8237. return this._pages[index];
  8238. }
  8239. getCachedPageViews() {
  8240. return new Set(this.#buffer);
  8241. }
  8242. get pageViewsReady() {
  8243. return this._pagesCapability.settled && this._pages.every((pageView) => pageView?.pdfPage);
  8244. }
  8245. get renderForms() {
  8246. return this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  8247. }
  8248. get enableScripting() {
  8249. return !!this._scriptingManager;
  8250. }
  8251. get currentPageNumber() {
  8252. return this._currentPageNumber;
  8253. }
  8254. set currentPageNumber(val) {
  8255. if (!Number.isInteger(val)) {
  8256. throw new Error('Invalid page number.');
  8257. }
  8258. if (!this.pdfDocument) {
  8259. return;
  8260. }
  8261. if (!this._setCurrentPageNumber(val, true)) {
  8262. console.error(`currentPageNumber: "${val}" is not a valid page.`);
  8263. }
  8264. }
  8265. _setCurrentPageNumber(val, resetCurrentPageView = false) {
  8266. if (this._currentPageNumber === val) {
  8267. if (resetCurrentPageView) {
  8268. this.#resetCurrentPageView();
  8269. }
  8270. return true;
  8271. }
  8272. if (!(0 < val && val <= this.pagesCount)) {
  8273. return false;
  8274. }
  8275. const previous = this._currentPageNumber;
  8276. this._currentPageNumber = val;
  8277. this.eventBus.dispatch('pagechanging', {
  8278. source: this,
  8279. pageNumber: val,
  8280. pageLabel: this._pageLabels?.[val - 1] ?? null,
  8281. previous
  8282. });
  8283. if (resetCurrentPageView) {
  8284. this.#resetCurrentPageView();
  8285. }
  8286. return true;
  8287. }
  8288. get currentPageLabel() {
  8289. return this._pageLabels?.[this._currentPageNumber - 1] ?? null;
  8290. }
  8291. set currentPageLabel(val) {
  8292. if (!this.pdfDocument) {
  8293. return;
  8294. }
  8295. let page = val | 0;
  8296. if (this._pageLabels) {
  8297. const i = this._pageLabels.indexOf(val);
  8298. if (i >= 0) {
  8299. page = i + 1;
  8300. }
  8301. }
  8302. if (!this._setCurrentPageNumber(page, true)) {
  8303. console.error(`currentPageLabel: "${val}" is not a valid page.`);
  8304. }
  8305. }
  8306. get currentScale() {
  8307. return this._currentScale !== _ui_utils.UNKNOWN_SCALE ? this._currentScale : _ui_utils.DEFAULT_SCALE;
  8308. }
  8309. set currentScale(val) {
  8310. if (isNaN(val)) {
  8311. throw new Error('Invalid numeric scale.');
  8312. }
  8313. if (!this.pdfDocument) {
  8314. return;
  8315. }
  8316. this.#setScale(val, {
  8317. noScroll: false
  8318. });
  8319. }
  8320. get currentScaleValue() {
  8321. return this._currentScaleValue;
  8322. }
  8323. set currentScaleValue(val) {
  8324. if (!this.pdfDocument) {
  8325. return;
  8326. }
  8327. this.#setScale(val, {
  8328. noScroll: false
  8329. });
  8330. }
  8331. get pagesRotation() {
  8332. return this._pagesRotation;
  8333. }
  8334. set pagesRotation(rotation) {
  8335. if (!(0, _ui_utils.isValidRotation)(rotation)) {
  8336. throw new Error('Invalid pages rotation angle.');
  8337. }
  8338. if (!this.pdfDocument) {
  8339. return;
  8340. }
  8341. rotation %= 360;
  8342. if (rotation < 0) {
  8343. rotation += 360;
  8344. }
  8345. if (this._pagesRotation === rotation) {
  8346. return;
  8347. }
  8348. this._pagesRotation = rotation;
  8349. const pageNumber = this._currentPageNumber;
  8350. this.refresh(true, {
  8351. rotation
  8352. });
  8353. if (this._currentScaleValue) {
  8354. this.#setScale(this._currentScaleValue, {
  8355. noScroll: true
  8356. });
  8357. }
  8358. this.eventBus.dispatch('rotationchanging', {
  8359. source: this,
  8360. pagesRotation: rotation,
  8361. pageNumber
  8362. });
  8363. if (this.defaultRenderingQueue) {
  8364. this.update();
  8365. }
  8366. }
  8367. get firstPagePromise() {
  8368. return this.pdfDocument ? this._firstPageCapability.promise : null;
  8369. }
  8370. get onePageRendered() {
  8371. return this.pdfDocument ? this._onePageRenderedCapability.promise : null;
  8372. }
  8373. get pagesPromise() {
  8374. return this.pdfDocument ? this._pagesCapability.promise : null;
  8375. }
  8376. #layerProperties() {
  8377. const self = this;
  8378. return {
  8379. get annotationEditorUIManager() {
  8380. return self.#annotationEditorUIManager;
  8381. },
  8382. get annotationStorage() {
  8383. return self.pdfDocument?.annotationStorage;
  8384. },
  8385. get downloadManager() {
  8386. return self.downloadManager;
  8387. },
  8388. get enableScripting() {
  8389. return !!self._scriptingManager;
  8390. },
  8391. get fieldObjectsPromise() {
  8392. return self.pdfDocument?.getFieldObjects();
  8393. },
  8394. get findController() {
  8395. return self.findController;
  8396. },
  8397. get hasJSActionsPromise() {
  8398. return self.pdfDocument?.hasJSActions();
  8399. },
  8400. get linkService() {
  8401. return self.linkService;
  8402. }
  8403. };
  8404. }
  8405. #initializePermissions(permissions) {
  8406. const params = {
  8407. annotationEditorMode: this.#annotationEditorMode,
  8408. annotationMode: this.#annotationMode,
  8409. textLayerMode: this.#textLayerMode
  8410. };
  8411. if (!permissions) {
  8412. return params;
  8413. }
  8414. if (!permissions.includes(_pdfjsLib.PermissionFlag.COPY) && this.#textLayerMode === _ui_utils.TextLayerMode.ENABLE) {
  8415. params.textLayerMode = _ui_utils.TextLayerMode.ENABLE_PERMISSIONS;
  8416. }
  8417. if (!permissions.includes(_pdfjsLib.PermissionFlag.MODIFY_CONTENTS)) {
  8418. params.annotationEditorMode = _pdfjsLib.AnnotationEditorType.DISABLE;
  8419. }
  8420. if (
  8421. !permissions.includes(_pdfjsLib.PermissionFlag.MODIFY_ANNOTATIONS) &&
  8422. !permissions.includes(_pdfjsLib.PermissionFlag.FILL_INTERACTIVE_FORMS) &&
  8423. this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS
  8424. ) {
  8425. params.annotationMode = _pdfjsLib.AnnotationMode.ENABLE;
  8426. }
  8427. return params;
  8428. }
  8429. #onePageRenderedOrForceFetch() {
  8430. if (document.visibilityState === 'hidden' || !this.container.offsetParent || this._getVisiblePages().views.length === 0) {
  8431. return Promise.resolve();
  8432. }
  8433. const visibilityChangePromise = new Promise((resolve) => {
  8434. this.#onVisibilityChange = () => {
  8435. if (document.visibilityState !== 'hidden') {
  8436. return;
  8437. }
  8438. resolve();
  8439. document.removeEventListener('visibilitychange', this.#onVisibilityChange);
  8440. this.#onVisibilityChange = null;
  8441. };
  8442. document.addEventListener('visibilitychange', this.#onVisibilityChange);
  8443. });
  8444. return Promise.race([this._onePageRenderedCapability.promise, visibilityChangePromise]);
  8445. }
  8446. async getAllText() {
  8447. const texts = [];
  8448. const buffer = [];
  8449. for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) {
  8450. if (this.#interruptCopyCondition) {
  8451. return null;
  8452. }
  8453. buffer.length = 0;
  8454. const page = await this.pdfDocument.getPage(pageNum);
  8455. const { items } = await page.getTextContent();
  8456. for (const item of items) {
  8457. if (item.str) {
  8458. buffer.push(item.str);
  8459. }
  8460. if (item.hasEOL) {
  8461. buffer.push('\n');
  8462. }
  8463. }
  8464. texts.push((0, _ui_utils.removeNullCharacters)(buffer.join('')));
  8465. }
  8466. return texts.join('\n');
  8467. }
  8468. #copyCallback(textLayerMode, event) {
  8469. const selection = document.getSelection();
  8470. const { focusNode, anchorNode } = selection;
  8471. if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) {
  8472. if (this.#getAllTextInProgress || textLayerMode === _ui_utils.TextLayerMode.ENABLE_PERMISSIONS) {
  8473. event.preventDefault();
  8474. event.stopPropagation();
  8475. return;
  8476. }
  8477. this.#getAllTextInProgress = true;
  8478. const savedCursor = this.container.style.cursor;
  8479. this.container.style.cursor = 'wait';
  8480. const interruptCopy = (ev) => (this.#interruptCopyCondition = ev.key === 'Escape');
  8481. window.addEventListener('keydown', interruptCopy);
  8482. this.getAllText()
  8483. .then(async (text) => {
  8484. if (text !== null) {
  8485. await navigator.clipboard.writeText(text);
  8486. }
  8487. })
  8488. .catch((reason) => {
  8489. console.warn(`Something goes wrong when extracting the text: ${reason.message}`);
  8490. })
  8491. .finally(() => {
  8492. this.#getAllTextInProgress = false;
  8493. this.#interruptCopyCondition = false;
  8494. window.removeEventListener('keydown', interruptCopy);
  8495. this.container.style.cursor = savedCursor;
  8496. });
  8497. event.preventDefault();
  8498. event.stopPropagation();
  8499. }
  8500. }
  8501. setDocument(pdfDocument) {
  8502. if (this.pdfDocument) {
  8503. this.eventBus.dispatch('pagesdestroy', {
  8504. source: this
  8505. });
  8506. this._cancelRendering();
  8507. this._resetView();
  8508. this.findController?.setDocument(null);
  8509. this._scriptingManager?.setDocument(null);
  8510. if (this.#annotationEditorUIManager) {
  8511. this.#annotationEditorUIManager.destroy();
  8512. this.#annotationEditorUIManager = null;
  8513. }
  8514. }
  8515. this.pdfDocument = pdfDocument;
  8516. if (!pdfDocument) {
  8517. return;
  8518. }
  8519. const pagesCount = pdfDocument.numPages;
  8520. const firstPagePromise = pdfDocument.getPage(1);
  8521. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();
  8522. const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve();
  8523. if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  8524. console.warn('Forcing PAGE-scrolling for performance reasons, given the length of the document.');
  8525. const mode = (this._scrollMode = _ui_utils.ScrollMode.PAGE);
  8526. this.eventBus.dispatch('scrollmodechanged', {
  8527. source: this,
  8528. mode
  8529. });
  8530. }
  8531. this._pagesCapability.promise.then(
  8532. () => {
  8533. this.eventBus.dispatch('pagesloaded', {
  8534. source: this,
  8535. pagesCount
  8536. });
  8537. },
  8538. () => {}
  8539. );
  8540. this._onBeforeDraw = (evt) => {
  8541. const pageView = this._pages[evt.pageNumber - 1];
  8542. if (!pageView) {
  8543. return;
  8544. }
  8545. this.#buffer.push(pageView);
  8546. };
  8547. this.eventBus._on('pagerender', this._onBeforeDraw);
  8548. this._onAfterDraw = (evt) => {
  8549. if (evt.cssTransform || this._onePageRenderedCapability.settled) {
  8550. return;
  8551. }
  8552. this._onePageRenderedCapability.resolve({
  8553. timestamp: evt.timestamp
  8554. });
  8555. this.eventBus._off('pagerendered', this._onAfterDraw);
  8556. this._onAfterDraw = null;
  8557. if (this.#onVisibilityChange) {
  8558. document.removeEventListener('visibilitychange', this.#onVisibilityChange);
  8559. this.#onVisibilityChange = null;
  8560. }
  8561. };
  8562. this.eventBus._on('pagerendered', this._onAfterDraw);
  8563. Promise.all([firstPagePromise, permissionsPromise])
  8564. .then(([firstPdfPage, permissions]) => {
  8565. if (pdfDocument !== this.pdfDocument) {
  8566. return;
  8567. }
  8568. this._firstPageCapability.resolve(firstPdfPage);
  8569. this._optionalContentConfigPromise = optionalContentConfigPromise;
  8570. const { annotationEditorMode, annotationMode, textLayerMode } = this.#initializePermissions(permissions);
  8571. if (textLayerMode !== _ui_utils.TextLayerMode.DISABLE) {
  8572. const element = (this.#hiddenCopyElement = document.createElement('div'));
  8573. element.id = 'hiddenCopyElement';
  8574. this.viewer.before(element);
  8575. }
  8576. if (annotationEditorMode !== _pdfjsLib.AnnotationEditorType.DISABLE) {
  8577. const mode = annotationEditorMode;
  8578. if (pdfDocument.isPureXfa) {
  8579. console.warn('Warning: XFA-editing is not implemented.');
  8580. } else if (isValidAnnotationEditorMode(mode)) {
  8581. this.#annotationEditorUIManager = new _pdfjsLib.AnnotationEditorUIManager(
  8582. this.container,
  8583. this.eventBus,
  8584. pdfDocument?.annotationStorage
  8585. );
  8586. if (mode !== _pdfjsLib.AnnotationEditorType.NONE) {
  8587. this.#annotationEditorUIManager.updateMode(mode);
  8588. }
  8589. } else {
  8590. console.error(`Invalid AnnotationEditor mode: ${mode}`);
  8591. }
  8592. }
  8593. const layerProperties = this.#layerProperties.bind(this);
  8594. const viewerElement = this._scrollMode === _ui_utils.ScrollMode.PAGE ? null : this.viewer;
  8595. const scale = this.currentScale;
  8596. const viewport = firstPdfPage.getViewport({
  8597. scale: scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS
  8598. });
  8599. this.viewer.style.setProperty('--scale-factor', viewport.scale);
  8600. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  8601. const pageView = new _pdf_page_view.PDFPageView({
  8602. container: viewerElement,
  8603. eventBus: this.eventBus,
  8604. id: pageNum,
  8605. scale,
  8606. defaultViewport: viewport.clone(),
  8607. optionalContentConfigPromise,
  8608. renderingQueue: this.renderingQueue,
  8609. textLayerMode,
  8610. annotationMode,
  8611. imageResourcesPath: this.imageResourcesPath,
  8612. useOnlyCssZoom: this.useOnlyCssZoom,
  8613. isOffscreenCanvasSupported: this.isOffscreenCanvasSupported,
  8614. maxCanvasPixels: this.maxCanvasPixels,
  8615. pageColors: this.pageColors,
  8616. l10n: this.l10n,
  8617. layerProperties
  8618. });
  8619. this._pages.push(pageView);
  8620. }
  8621. const firstPageView = this._pages[0];
  8622. if (firstPageView) {
  8623. firstPageView.setPdfPage(firstPdfPage);
  8624. this.linkService.cachePageRef(1, firstPdfPage.ref);
  8625. }
  8626. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  8627. this.#ensurePageViewVisible();
  8628. } else if (this._spreadMode !== _ui_utils.SpreadMode.NONE) {
  8629. this._updateSpreadMode();
  8630. }
  8631. this.#onePageRenderedOrForceFetch().then(async () => {
  8632. this.findController?.setDocument(pdfDocument);
  8633. this._scriptingManager?.setDocument(pdfDocument);
  8634. if (this.#hiddenCopyElement) {
  8635. this.#copyCallbackBound = this.#copyCallback.bind(this, textLayerMode);
  8636. document.addEventListener('copy', this.#copyCallbackBound);
  8637. }
  8638. if (this.#annotationEditorUIManager) {
  8639. this.eventBus.dispatch('annotationeditormodechanged', {
  8640. source: this,
  8641. mode: this.#annotationEditorMode
  8642. });
  8643. }
  8644. if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) {
  8645. this._pagesCapability.resolve();
  8646. return;
  8647. }
  8648. let getPagesLeft = pagesCount - 1;
  8649. if (getPagesLeft <= 0) {
  8650. this._pagesCapability.resolve();
  8651. return;
  8652. }
  8653. for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) {
  8654. const promise = pdfDocument.getPage(pageNum).then(
  8655. (pdfPage) => {
  8656. const pageView = this._pages[pageNum - 1];
  8657. if (!pageView.pdfPage) {
  8658. pageView.setPdfPage(pdfPage);
  8659. }
  8660. this.linkService.cachePageRef(pageNum, pdfPage.ref);
  8661. if (--getPagesLeft === 0) {
  8662. this._pagesCapability.resolve();
  8663. }
  8664. },
  8665. (reason) => {
  8666. console.error(`Unable to get page ${pageNum} to initialize viewer`, reason);
  8667. if (--getPagesLeft === 0) {
  8668. this._pagesCapability.resolve();
  8669. }
  8670. }
  8671. );
  8672. if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) {
  8673. await promise;
  8674. }
  8675. }
  8676. });
  8677. this.eventBus.dispatch('pagesinit', {
  8678. source: this
  8679. });
  8680. pdfDocument.getMetadata().then(({ info }) => {
  8681. if (pdfDocument !== this.pdfDocument) {
  8682. return;
  8683. }
  8684. if (info.Language) {
  8685. this.viewer.lang = info.Language;
  8686. }
  8687. });
  8688. if (this.defaultRenderingQueue) {
  8689. this.update();
  8690. }
  8691. })
  8692. .catch((reason) => {
  8693. console.error('Unable to initialize viewer', reason);
  8694. this._pagesCapability.reject(reason);
  8695. });
  8696. }
  8697. setPageLabels(labels) {
  8698. if (!this.pdfDocument) {
  8699. return;
  8700. }
  8701. if (!labels) {
  8702. this._pageLabels = null;
  8703. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  8704. this._pageLabels = null;
  8705. console.error(`setPageLabels: Invalid page labels.`);
  8706. } else {
  8707. this._pageLabels = labels;
  8708. }
  8709. for (let i = 0, ii = this._pages.length; i < ii; i++) {
  8710. this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null);
  8711. }
  8712. }
  8713. _resetView() {
  8714. this._pages = [];
  8715. this._currentPageNumber = 1;
  8716. this._currentScale = _ui_utils.UNKNOWN_SCALE;
  8717. this._currentScaleValue = null;
  8718. this._pageLabels = null;
  8719. this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  8720. this._location = null;
  8721. this._pagesRotation = 0;
  8722. this._optionalContentConfigPromise = null;
  8723. this._firstPageCapability = new _pdfjsLib.PromiseCapability();
  8724. this._onePageRenderedCapability = new _pdfjsLib.PromiseCapability();
  8725. this._pagesCapability = new _pdfjsLib.PromiseCapability();
  8726. this._scrollMode = _ui_utils.ScrollMode.VERTICAL;
  8727. this._previousScrollMode = _ui_utils.ScrollMode.UNKNOWN;
  8728. this._spreadMode = _ui_utils.SpreadMode.NONE;
  8729. this.#scrollModePageState = {
  8730. previousPageNumber: 1,
  8731. scrollDown: true,
  8732. pages: []
  8733. };
  8734. if (this._onBeforeDraw) {
  8735. this.eventBus._off('pagerender', this._onBeforeDraw);
  8736. this._onBeforeDraw = null;
  8737. }
  8738. if (this._onAfterDraw) {
  8739. this.eventBus._off('pagerendered', this._onAfterDraw);
  8740. this._onAfterDraw = null;
  8741. }
  8742. if (this.#onVisibilityChange) {
  8743. document.removeEventListener('visibilitychange', this.#onVisibilityChange);
  8744. this.#onVisibilityChange = null;
  8745. }
  8746. this.viewer.textContent = '';
  8747. this._updateScrollMode();
  8748. this.viewer.removeAttribute('lang');
  8749. if (this.#hiddenCopyElement) {
  8750. document.removeEventListener('copy', this.#copyCallbackBound);
  8751. this.#copyCallbackBound = null;
  8752. this.#hiddenCopyElement.remove();
  8753. this.#hiddenCopyElement = null;
  8754. }
  8755. }
  8756. #ensurePageViewVisible() {
  8757. if (this._scrollMode !== _ui_utils.ScrollMode.PAGE) {
  8758. throw new Error('#ensurePageViewVisible: Invalid scrollMode value.');
  8759. }
  8760. const pageNumber = this._currentPageNumber,
  8761. state = this.#scrollModePageState,
  8762. viewer = this.viewer;
  8763. viewer.textContent = '';
  8764. state.pages.length = 0;
  8765. if (this._spreadMode === _ui_utils.SpreadMode.NONE && !this.isInPresentationMode) {
  8766. const pageView = this._pages[pageNumber - 1];
  8767. viewer.append(pageView.div);
  8768. state.pages.push(pageView);
  8769. } else {
  8770. const pageIndexSet = new Set(),
  8771. parity = this._spreadMode - 1;
  8772. if (parity === -1) {
  8773. pageIndexSet.add(pageNumber - 1);
  8774. } else if (pageNumber % 2 !== parity) {
  8775. pageIndexSet.add(pageNumber - 1);
  8776. pageIndexSet.add(pageNumber);
  8777. } else {
  8778. pageIndexSet.add(pageNumber - 2);
  8779. pageIndexSet.add(pageNumber - 1);
  8780. }
  8781. const spread = document.createElement('div');
  8782. spread.className = 'spread';
  8783. if (this.isInPresentationMode) {
  8784. const dummyPage = document.createElement('div');
  8785. dummyPage.className = 'dummyPage';
  8786. spread.append(dummyPage);
  8787. }
  8788. for (const i of pageIndexSet) {
  8789. const pageView = this._pages[i];
  8790. if (!pageView) {
  8791. continue;
  8792. }
  8793. spread.append(pageView.div);
  8794. state.pages.push(pageView);
  8795. }
  8796. viewer.append(spread);
  8797. }
  8798. state.scrollDown = pageNumber >= state.previousPageNumber;
  8799. state.previousPageNumber = pageNumber;
  8800. }
  8801. _scrollUpdate() {
  8802. if (this.pagesCount === 0) {
  8803. return;
  8804. }
  8805. this.update();
  8806. }
  8807. #scrollIntoView(pageView, pageSpot = null) {
  8808. const { div, id } = pageView;
  8809. if (this._currentPageNumber !== id) {
  8810. this._setCurrentPageNumber(id);
  8811. }
  8812. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  8813. this.#ensurePageViewVisible();
  8814. this.update();
  8815. }
  8816. if (!pageSpot && !this.isInPresentationMode) {
  8817. const left = div.offsetLeft + div.clientLeft,
  8818. right = left + div.clientWidth;
  8819. const { scrollLeft, clientWidth } = this.container;
  8820. if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) {
  8821. pageSpot = {
  8822. left: 0,
  8823. top: 0
  8824. };
  8825. }
  8826. }
  8827. (0, _ui_utils.scrollIntoView)(div, pageSpot);
  8828. if (!this._currentScaleValue && this._location) {
  8829. this._location = null;
  8830. }
  8831. }
  8832. #isSameScale(newScale) {
  8833. return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15;
  8834. }
  8835. #setScaleUpdatePages(newScale, newValue, { noScroll = false, preset = false, drawingDelay = -1 }) {
  8836. this._currentScaleValue = newValue.toString();
  8837. if (this.#isSameScale(newScale)) {
  8838. if (preset) {
  8839. this.eventBus.dispatch('scalechanging', {
  8840. source: this,
  8841. scale: newScale,
  8842. presetValue: newValue
  8843. });
  8844. }
  8845. return;
  8846. }
  8847. this.viewer.style.setProperty('--scale-factor', newScale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS);
  8848. const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000;
  8849. this.refresh(true, {
  8850. scale: newScale,
  8851. drawingDelay: postponeDrawing ? drawingDelay : -1
  8852. });
  8853. if (postponeDrawing) {
  8854. this.#scaleTimeoutId = setTimeout(() => {
  8855. this.#scaleTimeoutId = null;
  8856. this.refresh();
  8857. }, drawingDelay);
  8858. }
  8859. this._currentScale = newScale;
  8860. if (!noScroll) {
  8861. let page = this._currentPageNumber,
  8862. dest;
  8863. if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  8864. page = this._location.pageNumber;
  8865. dest = [
  8866. null,
  8867. {
  8868. name: 'XYZ'
  8869. },
  8870. this._location.left,
  8871. this._location.top,
  8872. null
  8873. ];
  8874. }
  8875. this.scrollPageIntoView({
  8876. pageNumber: page,
  8877. destArray: dest,
  8878. allowNegativeOffset: true
  8879. });
  8880. }
  8881. this.eventBus.dispatch('scalechanging', {
  8882. source: this,
  8883. scale: newScale,
  8884. presetValue: preset ? newValue : undefined
  8885. });
  8886. if (this.defaultRenderingQueue) {
  8887. this.update();
  8888. }
  8889. }
  8890. get #pageWidthScaleFactor() {
  8891. if (this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL) {
  8892. return 2;
  8893. }
  8894. return 1;
  8895. }
  8896. #setScale(value, options) {
  8897. let scale = parseFloat(value);
  8898. if (scale > 0) {
  8899. options.preset = false;
  8900. this.#setScaleUpdatePages(scale, value, options);
  8901. } else {
  8902. const currentPage = this._pages[this._currentPageNumber - 1];
  8903. if (!currentPage) {
  8904. return;
  8905. }
  8906. let hPadding = _ui_utils.SCROLLBAR_PADDING,
  8907. vPadding = _ui_utils.VERTICAL_PADDING;
  8908. if (this.isInPresentationMode) {
  8909. hPadding = vPadding = 4;
  8910. if (this._spreadMode !== _ui_utils.SpreadMode.NONE) {
  8911. hPadding *= 2;
  8912. }
  8913. } else if (this.removePageBorders) {
  8914. hPadding = vPadding = 0;
  8915. } else if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL) {
  8916. [hPadding, vPadding] = [vPadding, hPadding];
  8917. }
  8918. const pageWidthScale = (((this.container.clientWidth - hPadding) / currentPage.width) * currentPage.scale) / this.#pageWidthScaleFactor;
  8919. const pageHeightScale = ((this.container.clientHeight - vPadding) / currentPage.height) * currentPage.scale;
  8920. switch (value) {
  8921. case 'page-actual':
  8922. scale = 1;
  8923. break;
  8924. case 'page-width':
  8925. scale = pageWidthScale;
  8926. break;
  8927. case 'page-height':
  8928. scale = pageHeightScale;
  8929. break;
  8930. case 'page-fit':
  8931. scale = Math.min(pageWidthScale, pageHeightScale);
  8932. break;
  8933. case 'auto':
  8934. const horizontalScale = (0, _ui_utils.isPortraitOrientation)(currentPage)
  8935. ? pageWidthScale
  8936. : Math.min(pageHeightScale, pageWidthScale);
  8937. scale = Math.min(_ui_utils.MAX_AUTO_SCALE, horizontalScale);
  8938. break;
  8939. default:
  8940. console.error(`#setScale: "${value}" is an unknown zoom value.`);
  8941. return;
  8942. }
  8943. options.preset = true;
  8944. this.#setScaleUpdatePages(scale, value, options);
  8945. }
  8946. }
  8947. #resetCurrentPageView() {
  8948. const pageView = this._pages[this._currentPageNumber - 1];
  8949. if (this.isInPresentationMode) {
  8950. this.#setScale(this._currentScaleValue, {
  8951. noScroll: true
  8952. });
  8953. }
  8954. this.#scrollIntoView(pageView);
  8955. }
  8956. pageLabelToPageNumber(label) {
  8957. if (!this._pageLabels) {
  8958. return null;
  8959. }
  8960. const i = this._pageLabels.indexOf(label);
  8961. if (i < 0) {
  8962. return null;
  8963. }
  8964. return i + 1;
  8965. }
  8966. scrollPageIntoView({ pageNumber, destArray = null, allowNegativeOffset = false, ignoreDestinationZoom = false }) {
  8967. if (!this.pdfDocument) {
  8968. return;
  8969. }
  8970. const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1];
  8971. if (!pageView) {
  8972. console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`);
  8973. return;
  8974. }
  8975. if (this.isInPresentationMode || !destArray) {
  8976. this._setCurrentPageNumber(pageNumber, true);
  8977. return;
  8978. }
  8979. let x = 0,
  8980. y = 0;
  8981. let width = 0,
  8982. height = 0,
  8983. widthScale,
  8984. heightScale;
  8985. const changeOrientation = pageView.rotation % 180 !== 0;
  8986. const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  8987. const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  8988. let scale = 0;
  8989. switch (destArray[1].name) {
  8990. case 'XYZ':
  8991. x = destArray[2];
  8992. y = destArray[3];
  8993. scale = destArray[4];
  8994. x = x !== null ? x : 0;
  8995. y = y !== null ? y : pageHeight;
  8996. break;
  8997. case 'Fit':
  8998. case 'FitB':
  8999. scale = 'page-fit';
  9000. break;
  9001. case 'FitH':
  9002. case 'FitBH':
  9003. y = destArray[2];
  9004. scale = 'page-width';
  9005. if (y === null && this._location) {
  9006. x = this._location.left;
  9007. y = this._location.top;
  9008. } else if (typeof y !== 'number' || y < 0) {
  9009. y = pageHeight;
  9010. }
  9011. break;
  9012. case 'FitV':
  9013. case 'FitBV':
  9014. x = destArray[2];
  9015. width = pageWidth;
  9016. height = pageHeight;
  9017. scale = 'page-height';
  9018. break;
  9019. case 'FitR':
  9020. x = destArray[2];
  9021. y = destArray[3];
  9022. width = destArray[4] - x;
  9023. height = destArray[5] - y;
  9024. let hPadding = _ui_utils.SCROLLBAR_PADDING,
  9025. vPadding = _ui_utils.VERTICAL_PADDING;
  9026. if (this.removePageBorders) {
  9027. hPadding = vPadding = 0;
  9028. }
  9029. widthScale = (this.container.clientWidth - hPadding) / width / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  9030. heightScale = (this.container.clientHeight - vPadding) / height / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  9031. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  9032. break;
  9033. default:
  9034. console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`);
  9035. return;
  9036. }
  9037. if (!ignoreDestinationZoom) {
  9038. if (scale && scale !== this._currentScale) {
  9039. this.currentScaleValue = scale;
  9040. } else if (this._currentScale === _ui_utils.UNKNOWN_SCALE) {
  9041. this.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  9042. }
  9043. }
  9044. if (scale === 'page-fit' && !destArray[4]) {
  9045. this.#scrollIntoView(pageView);
  9046. return;
  9047. }
  9048. const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)];
  9049. let left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  9050. let top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  9051. if (!allowNegativeOffset) {
  9052. left = Math.max(left, 0);
  9053. top = Math.max(top, 0);
  9054. }
  9055. this.#scrollIntoView(pageView, {
  9056. left,
  9057. top
  9058. });
  9059. }
  9060. _updateLocation(firstPage) {
  9061. const currentScale = this._currentScale;
  9062. const currentScaleValue = this._currentScaleValue;
  9063. const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  9064. const pageNumber = firstPage.id;
  9065. const currentPageView = this._pages[pageNumber - 1];
  9066. const container = this.container;
  9067. const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  9068. const intLeft = Math.round(topLeft[0]);
  9069. const intTop = Math.round(topLeft[1]);
  9070. let pdfOpenParams = `#page=${pageNumber}`;
  9071. if (!this.isInPresentationMode) {
  9072. pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`;
  9073. }
  9074. this._location = {
  9075. pageNumber,
  9076. scale: normalizedScaleValue,
  9077. top: intTop,
  9078. left: intLeft,
  9079. rotation: this._pagesRotation,
  9080. pdfOpenParams
  9081. };
  9082. }
  9083. update() {
  9084. const visible = this._getVisiblePages();
  9085. const visiblePages = visible.views,
  9086. numVisiblePages = visiblePages.length;
  9087. if (numVisiblePages === 0) {
  9088. return;
  9089. }
  9090. const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1);
  9091. this.#buffer.resize(newCacheSize, visible.ids);
  9092. this.renderingQueue.renderHighestPriority(visible);
  9093. const isSimpleLayout =
  9094. this._spreadMode === _ui_utils.SpreadMode.NONE &&
  9095. (this._scrollMode === _ui_utils.ScrollMode.PAGE || this._scrollMode === _ui_utils.ScrollMode.VERTICAL);
  9096. const currentId = this._currentPageNumber;
  9097. let stillFullyVisible = false;
  9098. for (const page of visiblePages) {
  9099. if (page.percent < 100) {
  9100. break;
  9101. }
  9102. if (page.id === currentId && isSimpleLayout) {
  9103. stillFullyVisible = true;
  9104. break;
  9105. }
  9106. }
  9107. this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id);
  9108. this._updateLocation(visible.first);
  9109. this.eventBus.dispatch('updateviewarea', {
  9110. source: this,
  9111. location: this._location
  9112. });
  9113. }
  9114. containsElement(element) {
  9115. return this.container.contains(element);
  9116. }
  9117. focus() {
  9118. this.container.focus();
  9119. }
  9120. get _isContainerRtl() {
  9121. return getComputedStyle(this.container).direction === 'rtl';
  9122. }
  9123. get isInPresentationMode() {
  9124. return this.presentationModeState === _ui_utils.PresentationModeState.FULLSCREEN;
  9125. }
  9126. get isChangingPresentationMode() {
  9127. return this.presentationModeState === _ui_utils.PresentationModeState.CHANGING;
  9128. }
  9129. get isHorizontalScrollbarEnabled() {
  9130. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  9131. }
  9132. get isVerticalScrollbarEnabled() {
  9133. return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight;
  9134. }
  9135. _getVisiblePages() {
  9136. const views = this._scrollMode === _ui_utils.ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages,
  9137. horizontal = this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL,
  9138. rtl = horizontal && this._isContainerRtl;
  9139. return (0, _ui_utils.getVisibleElements)({
  9140. scrollEl: this.container,
  9141. views,
  9142. sortByVisibility: true,
  9143. horizontal,
  9144. rtl
  9145. });
  9146. }
  9147. cleanup() {
  9148. for (const pageView of this._pages) {
  9149. if (pageView.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  9150. pageView.reset();
  9151. }
  9152. }
  9153. }
  9154. _cancelRendering() {
  9155. for (const pageView of this._pages) {
  9156. pageView.cancelRendering();
  9157. }
  9158. }
  9159. async #ensurePdfPageLoaded(pageView) {
  9160. if (pageView.pdfPage) {
  9161. return pageView.pdfPage;
  9162. }
  9163. try {
  9164. const pdfPage = await this.pdfDocument.getPage(pageView.id);
  9165. if (!pageView.pdfPage) {
  9166. pageView.setPdfPage(pdfPage);
  9167. }
  9168. if (!this.linkService._cachedPageNumber?.(pdfPage.ref)) {
  9169. this.linkService.cachePageRef(pageView.id, pdfPage.ref);
  9170. }
  9171. return pdfPage;
  9172. } catch (reason) {
  9173. console.error('Unable to get page for page view', reason);
  9174. return null;
  9175. }
  9176. }
  9177. #getScrollAhead(visible) {
  9178. if (visible.first?.id === 1) {
  9179. return true;
  9180. } else if (visible.last?.id === this.pagesCount) {
  9181. return false;
  9182. }
  9183. switch (this._scrollMode) {
  9184. case _ui_utils.ScrollMode.PAGE:
  9185. return this.#scrollModePageState.scrollDown;
  9186. case _ui_utils.ScrollMode.HORIZONTAL:
  9187. return this.scroll.right;
  9188. }
  9189. return this.scroll.down;
  9190. }
  9191. forceRendering(currentlyVisiblePages) {
  9192. const visiblePages = currentlyVisiblePages || this._getVisiblePages();
  9193. const scrollAhead = this.#getScrollAhead(visiblePages);
  9194. const preRenderExtra = this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL;
  9195. const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra);
  9196. if (pageView) {
  9197. this.#ensurePdfPageLoaded(pageView).then(() => {
  9198. this.renderingQueue.renderView(pageView);
  9199. });
  9200. return true;
  9201. }
  9202. return false;
  9203. }
  9204. get hasEqualPageSizes() {
  9205. const firstPageView = this._pages[0];
  9206. for (let i = 1, ii = this._pages.length; i < ii; ++i) {
  9207. const pageView = this._pages[i];
  9208. if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) {
  9209. return false;
  9210. }
  9211. }
  9212. return true;
  9213. }
  9214. getPagesOverview() {
  9215. let initialOrientation;
  9216. return this._pages.map((pageView) => {
  9217. const viewport = pageView.pdfPage.getViewport({
  9218. scale: 1
  9219. });
  9220. const orientation = (0, _ui_utils.isPortraitOrientation)(viewport);
  9221. if (initialOrientation === undefined) {
  9222. initialOrientation = orientation;
  9223. } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) {
  9224. return {
  9225. width: viewport.height,
  9226. height: viewport.width,
  9227. rotation: (viewport.rotation - 90) % 360
  9228. };
  9229. }
  9230. return {
  9231. width: viewport.width,
  9232. height: viewport.height,
  9233. rotation: viewport.rotation
  9234. };
  9235. });
  9236. }
  9237. get optionalContentConfigPromise() {
  9238. if (!this.pdfDocument) {
  9239. return Promise.resolve(null);
  9240. }
  9241. if (!this._optionalContentConfigPromise) {
  9242. console.error('optionalContentConfigPromise: Not initialized yet.');
  9243. return this.pdfDocument.getOptionalContentConfig();
  9244. }
  9245. return this._optionalContentConfigPromise;
  9246. }
  9247. set optionalContentConfigPromise(promise) {
  9248. if (!(promise instanceof Promise)) {
  9249. throw new Error(`Invalid optionalContentConfigPromise: ${promise}`);
  9250. }
  9251. if (!this.pdfDocument) {
  9252. return;
  9253. }
  9254. if (!this._optionalContentConfigPromise) {
  9255. return;
  9256. }
  9257. this._optionalContentConfigPromise = promise;
  9258. this.refresh(false, {
  9259. optionalContentConfigPromise: promise
  9260. });
  9261. this.eventBus.dispatch('optionalcontentconfigchanged', {
  9262. source: this,
  9263. promise
  9264. });
  9265. }
  9266. get scrollMode() {
  9267. return this._scrollMode;
  9268. }
  9269. set scrollMode(mode) {
  9270. if (this._scrollMode === mode) {
  9271. return;
  9272. }
  9273. if (!(0, _ui_utils.isValidScrollMode)(mode)) {
  9274. throw new Error(`Invalid scroll mode: ${mode}`);
  9275. }
  9276. if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  9277. return;
  9278. }
  9279. this._previousScrollMode = this._scrollMode;
  9280. this._scrollMode = mode;
  9281. this.eventBus.dispatch('scrollmodechanged', {
  9282. source: this,
  9283. mode
  9284. });
  9285. this._updateScrollMode(this._currentPageNumber);
  9286. }
  9287. _updateScrollMode(pageNumber = null) {
  9288. const scrollMode = this._scrollMode,
  9289. viewer = this.viewer;
  9290. viewer.classList.toggle('scrollHorizontal', scrollMode === _ui_utils.ScrollMode.HORIZONTAL);
  9291. viewer.classList.toggle('scrollWrapped', scrollMode === _ui_utils.ScrollMode.WRAPPED);
  9292. if (!this.pdfDocument || !pageNumber) {
  9293. return;
  9294. }
  9295. if (scrollMode === _ui_utils.ScrollMode.PAGE) {
  9296. this.#ensurePageViewVisible();
  9297. } else if (this._previousScrollMode === _ui_utils.ScrollMode.PAGE) {
  9298. this._updateSpreadMode();
  9299. }
  9300. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  9301. this.#setScale(this._currentScaleValue, {
  9302. noScroll: true
  9303. });
  9304. }
  9305. this._setCurrentPageNumber(pageNumber, true);
  9306. this.update();
  9307. }
  9308. get spreadMode() {
  9309. return this._spreadMode;
  9310. }
  9311. set spreadMode(mode) {
  9312. if (this._spreadMode === mode) {
  9313. return;
  9314. }
  9315. if (!(0, _ui_utils.isValidSpreadMode)(mode)) {
  9316. throw new Error(`Invalid spread mode: ${mode}`);
  9317. }
  9318. this._spreadMode = mode;
  9319. this.eventBus.dispatch('spreadmodechanged', {
  9320. source: this,
  9321. mode
  9322. });
  9323. this._updateSpreadMode(this._currentPageNumber);
  9324. }
  9325. _updateSpreadMode(pageNumber = null) {
  9326. if (!this.pdfDocument) {
  9327. return;
  9328. }
  9329. const viewer = this.viewer,
  9330. pages = this._pages;
  9331. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  9332. this.#ensurePageViewVisible();
  9333. } else {
  9334. viewer.textContent = '';
  9335. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  9336. for (const pageView of this._pages) {
  9337. viewer.append(pageView.div);
  9338. }
  9339. } else {
  9340. const parity = this._spreadMode - 1;
  9341. let spread = null;
  9342. for (let i = 0, ii = pages.length; i < ii; ++i) {
  9343. if (spread === null) {
  9344. spread = document.createElement('div');
  9345. spread.className = 'spread';
  9346. viewer.append(spread);
  9347. } else if (i % 2 === parity) {
  9348. spread = spread.cloneNode(false);
  9349. viewer.append(spread);
  9350. }
  9351. spread.append(pages[i].div);
  9352. }
  9353. }
  9354. }
  9355. if (!pageNumber) {
  9356. return;
  9357. }
  9358. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  9359. this.#setScale(this._currentScaleValue, {
  9360. noScroll: true
  9361. });
  9362. }
  9363. this._setCurrentPageNumber(pageNumber, true);
  9364. this.update();
  9365. }
  9366. _getPageAdvance(currentPageNumber, previous = false) {
  9367. switch (this._scrollMode) {
  9368. case _ui_utils.ScrollMode.WRAPPED: {
  9369. const { views } = this._getVisiblePages(),
  9370. pageLayout = new Map();
  9371. for (const { id, y, percent, widthPercent } of views) {
  9372. if (percent === 0 || widthPercent < 100) {
  9373. continue;
  9374. }
  9375. let yArray = pageLayout.get(y);
  9376. if (!yArray) {
  9377. pageLayout.set(y, (yArray ||= []));
  9378. }
  9379. yArray.push(id);
  9380. }
  9381. for (const yArray of pageLayout.values()) {
  9382. const currentIndex = yArray.indexOf(currentPageNumber);
  9383. if (currentIndex === -1) {
  9384. continue;
  9385. }
  9386. const numPages = yArray.length;
  9387. if (numPages === 1) {
  9388. break;
  9389. }
  9390. if (previous) {
  9391. for (let i = currentIndex - 1, ii = 0; i >= ii; i--) {
  9392. const currentId = yArray[i],
  9393. expectedId = yArray[i + 1] - 1;
  9394. if (currentId < expectedId) {
  9395. return currentPageNumber - expectedId;
  9396. }
  9397. }
  9398. } else {
  9399. for (let i = currentIndex + 1, ii = numPages; i < ii; i++) {
  9400. const currentId = yArray[i],
  9401. expectedId = yArray[i - 1] + 1;
  9402. if (currentId > expectedId) {
  9403. return expectedId - currentPageNumber;
  9404. }
  9405. }
  9406. }
  9407. if (previous) {
  9408. const firstId = yArray[0];
  9409. if (firstId < currentPageNumber) {
  9410. return currentPageNumber - firstId + 1;
  9411. }
  9412. } else {
  9413. const lastId = yArray[numPages - 1];
  9414. if (lastId > currentPageNumber) {
  9415. return lastId - currentPageNumber + 1;
  9416. }
  9417. }
  9418. break;
  9419. }
  9420. break;
  9421. }
  9422. case _ui_utils.ScrollMode.HORIZONTAL: {
  9423. break;
  9424. }
  9425. case _ui_utils.ScrollMode.PAGE:
  9426. case _ui_utils.ScrollMode.VERTICAL: {
  9427. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  9428. break;
  9429. }
  9430. const parity = this._spreadMode - 1;
  9431. if (previous && currentPageNumber % 2 !== parity) {
  9432. break;
  9433. } else if (!previous && currentPageNumber % 2 === parity) {
  9434. break;
  9435. }
  9436. const { views } = this._getVisiblePages(),
  9437. expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1;
  9438. for (const { id, percent, widthPercent } of views) {
  9439. if (id !== expectedId) {
  9440. continue;
  9441. }
  9442. if (percent > 0 && widthPercent === 100) {
  9443. return 2;
  9444. }
  9445. break;
  9446. }
  9447. break;
  9448. }
  9449. }
  9450. return 1;
  9451. }
  9452. nextPage() {
  9453. const currentPageNumber = this._currentPageNumber,
  9454. pagesCount = this.pagesCount;
  9455. if (currentPageNumber >= pagesCount) {
  9456. return false;
  9457. }
  9458. const advance = this._getPageAdvance(currentPageNumber, false) || 1;
  9459. this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount);
  9460. return true;
  9461. }
  9462. previousPage() {
  9463. const currentPageNumber = this._currentPageNumber;
  9464. if (currentPageNumber <= 1) {
  9465. return false;
  9466. }
  9467. const advance = this._getPageAdvance(currentPageNumber, true) || 1;
  9468. this.currentPageNumber = Math.max(currentPageNumber - advance, 1);
  9469. return true;
  9470. }
  9471. increaseScale({ drawingDelay, scaleFactor, steps } = {}) {
  9472. if (!this.pdfDocument) {
  9473. return;
  9474. }
  9475. let newScale = this._currentScale;
  9476. if (scaleFactor > 1) {
  9477. newScale = Math.round(newScale * scaleFactor * 100) / 100;
  9478. } else {
  9479. steps ??= 1;
  9480. do {
  9481. newScale = Math.ceil((newScale * _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2) * 10) / 10;
  9482. } while (--steps > 0 && newScale < _ui_utils.MAX_SCALE);
  9483. }
  9484. this.#setScale(Math.min(_ui_utils.MAX_SCALE, newScale), {
  9485. noScroll: false,
  9486. drawingDelay
  9487. });
  9488. }
  9489. decreaseScale({ drawingDelay, scaleFactor, steps } = {}) {
  9490. if (!this.pdfDocument) {
  9491. return;
  9492. }
  9493. let newScale = this._currentScale;
  9494. if (scaleFactor > 0 && scaleFactor < 1) {
  9495. newScale = Math.round(newScale * scaleFactor * 100) / 100;
  9496. } else {
  9497. steps ??= 1;
  9498. do {
  9499. newScale = Math.floor((newScale / _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2) * 10) / 10;
  9500. } while (--steps > 0 && newScale > _ui_utils.MIN_SCALE);
  9501. }
  9502. this.#setScale(Math.max(_ui_utils.MIN_SCALE, newScale), {
  9503. noScroll: false,
  9504. drawingDelay
  9505. });
  9506. }
  9507. #updateContainerHeightCss(height = this.container.clientHeight) {
  9508. if (height !== this.#previousContainerHeight) {
  9509. this.#previousContainerHeight = height;
  9510. _ui_utils.docStyle.setProperty('--viewer-container-height', `${height}px`);
  9511. }
  9512. }
  9513. #resizeObserverCallback(entries) {
  9514. for (const entry of entries) {
  9515. if (entry.target === this.container) {
  9516. this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize));
  9517. this.#containerTopLeft = null;
  9518. break;
  9519. }
  9520. }
  9521. }
  9522. get containerTopLeft() {
  9523. return (this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]);
  9524. }
  9525. get annotationEditorMode() {
  9526. return this.#annotationEditorUIManager ? this.#annotationEditorMode : _pdfjsLib.AnnotationEditorType.DISABLE;
  9527. }
  9528. set annotationEditorMode(mode) {
  9529. if (!this.#annotationEditorUIManager) {
  9530. throw new Error(`The AnnotationEditor is not enabled.`);
  9531. }
  9532. if (this.#annotationEditorMode === mode) {
  9533. return;
  9534. }
  9535. if (!isValidAnnotationEditorMode(mode)) {
  9536. throw new Error(`Invalid AnnotationEditor mode: ${mode}`);
  9537. }
  9538. if (!this.pdfDocument) {
  9539. return;
  9540. }
  9541. this.#annotationEditorMode = mode;
  9542. this.eventBus.dispatch('annotationeditormodechanged', {
  9543. source: this,
  9544. mode
  9545. });
  9546. this.#annotationEditorUIManager.updateMode(mode);
  9547. }
  9548. set annotationEditorParams({ type, value }) {
  9549. if (!this.#annotationEditorUIManager) {
  9550. throw new Error(`The AnnotationEditor is not enabled.`);
  9551. }
  9552. this.#annotationEditorUIManager.updateParams(type, value);
  9553. }
  9554. refresh(noUpdate = false, updateArgs = Object.create(null)) {
  9555. if (!this.pdfDocument) {
  9556. return;
  9557. }
  9558. for (const pageView of this._pages) {
  9559. pageView.update(updateArgs);
  9560. }
  9561. if (this.#scaleTimeoutId !== null) {
  9562. clearTimeout(this.#scaleTimeoutId);
  9563. this.#scaleTimeoutId = null;
  9564. }
  9565. if (!noUpdate) {
  9566. this.update();
  9567. }
  9568. }
  9569. }
  9570. exports.PDFViewer = PDFViewer;
  9571. /***/
  9572. },
  9573. /* 29 */
  9574. /***/ (__unused_webpack_module, exports) => {
  9575. Object.defineProperty(exports, '__esModule', {
  9576. value: true
  9577. });
  9578. exports.NullL10n = void 0;
  9579. exports.fixupLangCode = fixupLangCode;
  9580. exports.getL10nFallback = getL10nFallback;
  9581. const DEFAULT_L10N_STRINGS = {
  9582. of_pages: 'of {{pagesCount}}',
  9583. page_of_pages: '({{pageNumber}} of {{pagesCount}})',
  9584. document_properties_kb: '{{size_kb}} KB ({{size_b}} bytes)',
  9585. document_properties_mb: '{{size_mb}} MB ({{size_b}} bytes)',
  9586. document_properties_date_string: '{{date}}, {{time}}',
  9587. document_properties_page_size_unit_inches: 'in',
  9588. document_properties_page_size_unit_millimeters: 'mm',
  9589. document_properties_page_size_orientation_portrait: 'portrait',
  9590. document_properties_page_size_orientation_landscape: 'landscape',
  9591. document_properties_page_size_name_a3: 'A3',
  9592. document_properties_page_size_name_a4: 'A4',
  9593. document_properties_page_size_name_letter: 'Letter',
  9594. document_properties_page_size_name_legal: 'Legal',
  9595. document_properties_page_size_dimension_string: '{{width}} × {{height}} {{unit}} ({{orientation}})',
  9596. document_properties_page_size_dimension_name_string: '{{width}} × {{height}} {{unit}} ({{name}}, {{orientation}})',
  9597. document_properties_linearized_yes: 'Yes',
  9598. document_properties_linearized_no: 'No',
  9599. additional_layers: 'Additional Layers',
  9600. page_landmark: 'Page {{page}}',
  9601. thumb_page_title: 'Page {{page}}',
  9602. thumb_page_canvas: 'Thumbnail of Page {{page}}',
  9603. find_reached_top: 'Reached top of document, continued from bottom',
  9604. find_reached_bottom: 'Reached end of document, continued from top',
  9605. 'find_match_count[one]': '{{current}} of {{total}} match',
  9606. 'find_match_count[other]': '{{current}} of {{total}} matches',
  9607. 'find_match_count_limit[one]': 'More than {{limit}} match',
  9608. 'find_match_count_limit[other]': 'More than {{limit}} matches',
  9609. find_not_found: 'Phrase not found',
  9610. page_scale_width: 'Page Width',
  9611. page_scale_fit: 'Page Fit',
  9612. page_scale_auto: 'Automatic Zoom',
  9613. page_scale_actual: 'Actual Size',
  9614. page_scale_percent: '{{scale}}%',
  9615. loading_error: 'An error occurred while loading the PDF.',
  9616. invalid_file_error: 'Invalid or corrupted PDF file.',
  9617. missing_file_error: 'Missing PDF file.',
  9618. unexpected_response_error: 'Unexpected server response.',
  9619. rendering_error: 'An error occurred while rendering the page.',
  9620. printing_not_supported: 'Warning: Printing is not fully supported by this browser.',
  9621. printing_not_ready: 'Warning: The PDF is not fully loaded for printing.',
  9622. web_fonts_disabled: 'Web fonts are disabled: unable to use embedded PDF fonts.',
  9623. free_text2_default_content: 'Start typing…',
  9624. editor_free_text2_aria_label: 'Text Editor',
  9625. editor_ink2_aria_label: 'Draw Editor',
  9626. editor_ink_canvas_aria_label: 'User-created image'
  9627. };
  9628. {
  9629. DEFAULT_L10N_STRINGS.print_progress_percent = '{{progress}}%';
  9630. }
  9631. function getL10nFallback(key, args) {
  9632. switch (key) {
  9633. case 'find_match_count':
  9634. key = `find_match_count[${args.total === 1 ? 'one' : 'other'}]`;
  9635. break;
  9636. case 'find_match_count_limit':
  9637. key = `find_match_count_limit[${args.limit === 1 ? 'one' : 'other'}]`;
  9638. break;
  9639. }
  9640. return DEFAULT_L10N_STRINGS[key] || '';
  9641. }
  9642. const PARTIAL_LANG_CODES = {
  9643. en: 'en-US',
  9644. es: 'es-ES',
  9645. fy: 'fy-NL',
  9646. ga: 'ga-IE',
  9647. gu: 'gu-IN',
  9648. hi: 'hi-IN',
  9649. hy: 'hy-AM',
  9650. nb: 'nb-NO',
  9651. ne: 'ne-NP',
  9652. nn: 'nn-NO',
  9653. pa: 'pa-IN',
  9654. pt: 'pt-PT',
  9655. sv: 'sv-SE',
  9656. zh: 'zh-CN'
  9657. };
  9658. function fixupLangCode(langCode) {
  9659. return PARTIAL_LANG_CODES[langCode?.toLowerCase()] || langCode;
  9660. }
  9661. function formatL10nValue(text, args) {
  9662. if (!args) {
  9663. return text;
  9664. }
  9665. return text.replaceAll(/\{\{\s*(\w+)\s*\}\}/g, (all, name) => {
  9666. return name in args ? args[name] : '{{' + name + '}}';
  9667. });
  9668. }
  9669. const NullL10n = {
  9670. async getLanguage() {
  9671. return 'en-us';
  9672. },
  9673. async getDirection() {
  9674. return 'ltr';
  9675. },
  9676. async get(key, args = null, fallback = getL10nFallback(key, args)) {
  9677. return formatL10nValue(fallback, args);
  9678. },
  9679. async translate(element) {}
  9680. };
  9681. exports.NullL10n = NullL10n;
  9682. /***/
  9683. },
  9684. /* 30 */
  9685. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  9686. Object.defineProperty(exports, '__esModule', {
  9687. value: true
  9688. });
  9689. exports.PDFPageView = void 0;
  9690. var _pdfjsLib = __webpack_require__(4);
  9691. var _ui_utils = __webpack_require__(3);
  9692. var _annotation_editor_layer_builder = __webpack_require__(31);
  9693. var _annotation_layer_builder = __webpack_require__(32);
  9694. var _app_options = __webpack_require__(5);
  9695. var _l10n_utils = __webpack_require__(29);
  9696. var _pdf_link_service = __webpack_require__(7);
  9697. var _struct_tree_layer_builder = __webpack_require__(33);
  9698. var _text_accessibility = __webpack_require__(34);
  9699. var _text_highlighter = __webpack_require__(35);
  9700. var _text_layer_builder = __webpack_require__(36);
  9701. var _xfa_layer_builder = __webpack_require__(37);
  9702. const MAX_CANVAS_PIXELS = _app_options.compatibilityParams.maxCanvasPixels || 16777216;
  9703. const DEFAULT_LAYER_PROPERTIES = () => {
  9704. return null;
  9705. };
  9706. class PDFPageView {
  9707. #annotationMode = _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  9708. #layerProperties = null;
  9709. #loadingId = null;
  9710. #previousRotation = null;
  9711. #renderError = null;
  9712. #renderingState = _ui_utils.RenderingStates.INITIAL;
  9713. #textLayerMode = _ui_utils.TextLayerMode.ENABLE;
  9714. #useThumbnailCanvas = {
  9715. initialOptionalContent: true,
  9716. regularAnnotations: true
  9717. };
  9718. #viewportMap = new WeakMap();
  9719. constructor(options) {
  9720. const container = options.container;
  9721. const defaultViewport = options.defaultViewport;
  9722. this.id = options.id;
  9723. this.renderingId = 'page' + this.id;
  9724. this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES;
  9725. this.pdfPage = null;
  9726. this.pageLabel = null;
  9727. this.rotation = 0;
  9728. this.scale = options.scale || _ui_utils.DEFAULT_SCALE;
  9729. this.viewport = defaultViewport;
  9730. this.pdfPageRotate = defaultViewport.rotation;
  9731. this._optionalContentConfigPromise = options.optionalContentConfigPromise || null;
  9732. this.hasRestrictedScaling = false;
  9733. this.#textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE;
  9734. this.#annotationMode = options.annotationMode ?? _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  9735. this.imageResourcesPath = options.imageResourcesPath || '';
  9736. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  9737. this.isOffscreenCanvasSupported = options.isOffscreenCanvasSupported ?? true;
  9738. this.maxCanvasPixels = options.maxCanvasPixels || MAX_CANVAS_PIXELS;
  9739. this.pageColors = options.pageColors || null;
  9740. this.eventBus = options.eventBus;
  9741. this.renderingQueue = options.renderingQueue;
  9742. this.l10n = options.l10n || _l10n_utils.NullL10n;
  9743. this.renderTask = null;
  9744. this.resume = null;
  9745. this._isStandalone = !this.renderingQueue?.hasViewer();
  9746. this._annotationCanvasMap = null;
  9747. this.annotationLayer = null;
  9748. this.annotationEditorLayer = null;
  9749. this.textLayer = null;
  9750. this.zoomLayer = null;
  9751. this.xfaLayer = null;
  9752. this.structTreeLayer = null;
  9753. const div = document.createElement('div');
  9754. div.className = 'page';
  9755. div.setAttribute('data-page-number', this.id);
  9756. div.setAttribute('role', 'region');
  9757. this.l10n
  9758. .get('page_landmark', {
  9759. page: this.id
  9760. })
  9761. .then((msg) => {
  9762. div.setAttribute('aria-label', msg);
  9763. });
  9764. this.div = div;
  9765. this.#setDimensions();
  9766. container?.append(div);
  9767. if (this._isStandalone) {
  9768. container?.style.setProperty('--scale-factor', this.scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS);
  9769. const { optionalContentConfigPromise } = options;
  9770. if (optionalContentConfigPromise) {
  9771. optionalContentConfigPromise.then((optionalContentConfig) => {
  9772. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  9773. return;
  9774. }
  9775. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  9776. });
  9777. }
  9778. }
  9779. }
  9780. get renderingState() {
  9781. return this.#renderingState;
  9782. }
  9783. set renderingState(state) {
  9784. if (state === this.#renderingState) {
  9785. return;
  9786. }
  9787. this.#renderingState = state;
  9788. if (this.#loadingId) {
  9789. clearTimeout(this.#loadingId);
  9790. this.#loadingId = null;
  9791. }
  9792. switch (state) {
  9793. case _ui_utils.RenderingStates.PAUSED:
  9794. this.div.classList.remove('loading');
  9795. break;
  9796. case _ui_utils.RenderingStates.RUNNING:
  9797. this.div.classList.add('loadingIcon');
  9798. this.#loadingId = setTimeout(() => {
  9799. this.div.classList.add('loading');
  9800. this.#loadingId = null;
  9801. }, 0);
  9802. break;
  9803. case _ui_utils.RenderingStates.INITIAL:
  9804. case _ui_utils.RenderingStates.FINISHED:
  9805. this.div.classList.remove('loadingIcon', 'loading');
  9806. break;
  9807. }
  9808. }
  9809. #setDimensions() {
  9810. const { viewport } = this;
  9811. if (this.pdfPage) {
  9812. if (this.#previousRotation === viewport.rotation) {
  9813. return;
  9814. }
  9815. this.#previousRotation = viewport.rotation;
  9816. }
  9817. (0, _pdfjsLib.setLayerDimensions)(this.div, viewport, true, false);
  9818. }
  9819. setPdfPage(pdfPage) {
  9820. this.pdfPage = pdfPage;
  9821. this.pdfPageRotate = pdfPage.rotate;
  9822. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  9823. this.viewport = pdfPage.getViewport({
  9824. scale: this.scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS,
  9825. rotation: totalRotation
  9826. });
  9827. this.#setDimensions();
  9828. this.reset();
  9829. }
  9830. destroy() {
  9831. this.reset();
  9832. this.pdfPage?.cleanup();
  9833. }
  9834. get _textHighlighter() {
  9835. return (0, _pdfjsLib.shadow)(
  9836. this,
  9837. '_textHighlighter',
  9838. new _text_highlighter.TextHighlighter({
  9839. pageIndex: this.id - 1,
  9840. eventBus: this.eventBus,
  9841. findController: this.#layerProperties().findController
  9842. })
  9843. );
  9844. }
  9845. async #renderAnnotationLayer() {
  9846. let error = null;
  9847. try {
  9848. await this.annotationLayer.render(this.viewport, 'display');
  9849. } catch (ex) {
  9850. console.error(`#renderAnnotationLayer: "${ex}".`);
  9851. error = ex;
  9852. } finally {
  9853. this.eventBus.dispatch('annotationlayerrendered', {
  9854. source: this,
  9855. pageNumber: this.id,
  9856. error
  9857. });
  9858. }
  9859. }
  9860. async #renderAnnotationEditorLayer() {
  9861. let error = null;
  9862. try {
  9863. await this.annotationEditorLayer.render(this.viewport, 'display');
  9864. } catch (ex) {
  9865. console.error(`#renderAnnotationEditorLayer: "${ex}".`);
  9866. error = ex;
  9867. } finally {
  9868. this.eventBus.dispatch('annotationeditorlayerrendered', {
  9869. source: this,
  9870. pageNumber: this.id,
  9871. error
  9872. });
  9873. }
  9874. }
  9875. async #renderXfaLayer() {
  9876. let error = null;
  9877. try {
  9878. const result = await this.xfaLayer.render(this.viewport, 'display');
  9879. if (result?.textDivs && this._textHighlighter) {
  9880. this.#buildXfaTextContentItems(result.textDivs);
  9881. }
  9882. } catch (ex) {
  9883. console.error(`#renderXfaLayer: "${ex}".`);
  9884. error = ex;
  9885. } finally {
  9886. this.eventBus.dispatch('xfalayerrendered', {
  9887. source: this,
  9888. pageNumber: this.id,
  9889. error
  9890. });
  9891. }
  9892. }
  9893. async #renderTextLayer() {
  9894. const { pdfPage, textLayer, viewport } = this;
  9895. if (!textLayer) {
  9896. return;
  9897. }
  9898. let error = null;
  9899. try {
  9900. if (!textLayer.renderingDone) {
  9901. const readableStream = pdfPage.streamTextContent({
  9902. includeMarkedContent: true,
  9903. disableNormalization: true
  9904. });
  9905. textLayer.setTextContentSource(readableStream);
  9906. }
  9907. await textLayer.render(viewport);
  9908. } catch (ex) {
  9909. if (ex instanceof _pdfjsLib.AbortException) {
  9910. return;
  9911. }
  9912. console.error(`#renderTextLayer: "${ex}".`);
  9913. error = ex;
  9914. }
  9915. this.eventBus.dispatch('textlayerrendered', {
  9916. source: this,
  9917. pageNumber: this.id,
  9918. numTextDivs: textLayer.numTextDivs,
  9919. error
  9920. });
  9921. this.#renderStructTreeLayer();
  9922. }
  9923. async #renderStructTreeLayer() {
  9924. if (!this.textLayer) {
  9925. return;
  9926. }
  9927. this.structTreeLayer ||= new _struct_tree_layer_builder.StructTreeLayerBuilder();
  9928. const tree = await (!this.structTreeLayer.renderingDone ? this.pdfPage.getStructTree() : null);
  9929. const treeDom = this.structTreeLayer?.render(tree);
  9930. if (treeDom) {
  9931. this.canvas?.append(treeDom);
  9932. }
  9933. this.structTreeLayer?.show();
  9934. }
  9935. async #buildXfaTextContentItems(textDivs) {
  9936. const text = await this.pdfPage.getTextContent();
  9937. const items = [];
  9938. for (const item of text.items) {
  9939. items.push(item.str);
  9940. }
  9941. this._textHighlighter.setTextMapping(textDivs, items);
  9942. this._textHighlighter.enable();
  9943. }
  9944. _resetZoomLayer(removeFromDOM = false) {
  9945. if (!this.zoomLayer) {
  9946. return;
  9947. }
  9948. const zoomLayerCanvas = this.zoomLayer.firstChild;
  9949. this.#viewportMap.delete(zoomLayerCanvas);
  9950. zoomLayerCanvas.width = 0;
  9951. zoomLayerCanvas.height = 0;
  9952. if (removeFromDOM) {
  9953. this.zoomLayer.remove();
  9954. }
  9955. this.zoomLayer = null;
  9956. }
  9957. reset({
  9958. keepZoomLayer = false,
  9959. keepAnnotationLayer = false,
  9960. keepAnnotationEditorLayer = false,
  9961. keepXfaLayer = false,
  9962. keepTextLayer = false
  9963. } = {}) {
  9964. this.cancelRendering({
  9965. keepAnnotationLayer,
  9966. keepAnnotationEditorLayer,
  9967. keepXfaLayer,
  9968. keepTextLayer
  9969. });
  9970. this.renderingState = _ui_utils.RenderingStates.INITIAL;
  9971. const div = this.div;
  9972. const childNodes = div.childNodes,
  9973. zoomLayerNode = (keepZoomLayer && this.zoomLayer) || null,
  9974. annotationLayerNode = (keepAnnotationLayer && this.annotationLayer?.div) || null,
  9975. annotationEditorLayerNode = (keepAnnotationEditorLayer && this.annotationEditorLayer?.div) || null,
  9976. xfaLayerNode = (keepXfaLayer && this.xfaLayer?.div) || null,
  9977. textLayerNode = (keepTextLayer && this.textLayer?.div) || null;
  9978. for (let i = childNodes.length - 1; i >= 0; i--) {
  9979. const node = childNodes[i];
  9980. switch (node) {
  9981. case zoomLayerNode:
  9982. case annotationLayerNode:
  9983. case annotationEditorLayerNode:
  9984. case xfaLayerNode:
  9985. case textLayerNode:
  9986. continue;
  9987. }
  9988. node.remove();
  9989. }
  9990. div.removeAttribute('data-loaded');
  9991. if (annotationLayerNode) {
  9992. this.annotationLayer.hide();
  9993. }
  9994. if (annotationEditorLayerNode) {
  9995. this.annotationEditorLayer.hide();
  9996. }
  9997. if (xfaLayerNode) {
  9998. this.xfaLayer.hide();
  9999. }
  10000. if (textLayerNode) {
  10001. this.textLayer.hide();
  10002. }
  10003. this.structTreeLayer?.hide();
  10004. if (!zoomLayerNode) {
  10005. if (this.canvas) {
  10006. this.#viewportMap.delete(this.canvas);
  10007. this.canvas.width = 0;
  10008. this.canvas.height = 0;
  10009. delete this.canvas;
  10010. }
  10011. this._resetZoomLayer();
  10012. }
  10013. }
  10014. update({ scale = 0, rotation = null, optionalContentConfigPromise = null, drawingDelay = -1 }) {
  10015. this.scale = scale || this.scale;
  10016. if (typeof rotation === 'number') {
  10017. this.rotation = rotation;
  10018. }
  10019. if (optionalContentConfigPromise instanceof Promise) {
  10020. this._optionalContentConfigPromise = optionalContentConfigPromise;
  10021. optionalContentConfigPromise.then((optionalContentConfig) => {
  10022. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  10023. return;
  10024. }
  10025. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  10026. });
  10027. }
  10028. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  10029. this.viewport = this.viewport.clone({
  10030. scale: this.scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS,
  10031. rotation: totalRotation
  10032. });
  10033. this.#setDimensions();
  10034. if (this._isStandalone) {
  10035. this.div.parentNode?.style.setProperty('--scale-factor', this.viewport.scale);
  10036. }
  10037. let isScalingRestricted = false;
  10038. if (this.canvas && this.maxCanvasPixels > 0) {
  10039. const { width, height } = this.viewport;
  10040. const { sx, sy } = this.outputScale;
  10041. if (((Math.floor(width) * sx) | 0) * ((Math.floor(height) * sy) | 0) > this.maxCanvasPixels) {
  10042. isScalingRestricted = true;
  10043. }
  10044. }
  10045. const onlyCssZoom = this.useOnlyCssZoom || (this.hasRestrictedScaling && isScalingRestricted);
  10046. const postponeDrawing = !onlyCssZoom && drawingDelay >= 0 && drawingDelay < 1000;
  10047. if (this.canvas) {
  10048. if (postponeDrawing || onlyCssZoom) {
  10049. if (postponeDrawing && this.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  10050. this.cancelRendering({
  10051. keepZoomLayer: true,
  10052. keepAnnotationLayer: true,
  10053. keepAnnotationEditorLayer: true,
  10054. keepXfaLayer: true,
  10055. keepTextLayer: true,
  10056. cancelExtraDelay: drawingDelay
  10057. });
  10058. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  10059. }
  10060. this.cssTransform({
  10061. target: this.canvas,
  10062. redrawAnnotationLayer: true,
  10063. redrawAnnotationEditorLayer: true,
  10064. redrawXfaLayer: true,
  10065. redrawTextLayer: !postponeDrawing,
  10066. hideTextLayer: postponeDrawing
  10067. });
  10068. this.eventBus.dispatch('pagerendered', {
  10069. source: this,
  10070. pageNumber: this.id,
  10071. cssTransform: true,
  10072. timestamp: performance.now(),
  10073. error: this.#renderError
  10074. });
  10075. return;
  10076. }
  10077. if (!this.zoomLayer && !this.canvas.hidden) {
  10078. this.zoomLayer = this.canvas.parentNode;
  10079. this.zoomLayer.style.position = 'absolute';
  10080. }
  10081. }
  10082. if (this.zoomLayer) {
  10083. this.cssTransform({
  10084. target: this.zoomLayer.firstChild
  10085. });
  10086. }
  10087. this.reset({
  10088. keepZoomLayer: true,
  10089. keepAnnotationLayer: true,
  10090. keepAnnotationEditorLayer: true,
  10091. keepXfaLayer: true,
  10092. keepTextLayer: true
  10093. });
  10094. }
  10095. cancelRendering({
  10096. keepAnnotationLayer = false,
  10097. keepAnnotationEditorLayer = false,
  10098. keepXfaLayer = false,
  10099. keepTextLayer = false,
  10100. cancelExtraDelay = 0
  10101. } = {}) {
  10102. if (this.renderTask) {
  10103. this.renderTask.cancel(cancelExtraDelay);
  10104. this.renderTask = null;
  10105. }
  10106. this.resume = null;
  10107. if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) {
  10108. this.textLayer.cancel();
  10109. this.textLayer = null;
  10110. }
  10111. if (this.structTreeLayer && !this.textLayer) {
  10112. this.structTreeLayer = null;
  10113. }
  10114. if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) {
  10115. this.annotationLayer.cancel();
  10116. this.annotationLayer = null;
  10117. this._annotationCanvasMap = null;
  10118. }
  10119. if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) {
  10120. this.annotationEditorLayer.cancel();
  10121. this.annotationEditorLayer = null;
  10122. }
  10123. if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) {
  10124. this.xfaLayer.cancel();
  10125. this.xfaLayer = null;
  10126. this._textHighlighter?.disable();
  10127. }
  10128. }
  10129. cssTransform({
  10130. target,
  10131. redrawAnnotationLayer = false,
  10132. redrawAnnotationEditorLayer = false,
  10133. redrawXfaLayer = false,
  10134. redrawTextLayer = false,
  10135. hideTextLayer = false
  10136. }) {
  10137. if (!target.hasAttribute('zooming')) {
  10138. target.setAttribute('zooming', true);
  10139. const { style } = target;
  10140. style.width = style.height = '';
  10141. }
  10142. const originalViewport = this.#viewportMap.get(target);
  10143. if (this.viewport !== originalViewport) {
  10144. const relativeRotation = this.viewport.rotation - originalViewport.rotation;
  10145. const absRotation = Math.abs(relativeRotation);
  10146. let scaleX = 1,
  10147. scaleY = 1;
  10148. if (absRotation === 90 || absRotation === 270) {
  10149. const { width, height } = this.viewport;
  10150. scaleX = height / width;
  10151. scaleY = width / height;
  10152. }
  10153. target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`;
  10154. }
  10155. if (redrawAnnotationLayer && this.annotationLayer) {
  10156. this.#renderAnnotationLayer();
  10157. }
  10158. if (redrawAnnotationEditorLayer && this.annotationEditorLayer) {
  10159. this.#renderAnnotationEditorLayer();
  10160. }
  10161. if (redrawXfaLayer && this.xfaLayer) {
  10162. this.#renderXfaLayer();
  10163. }
  10164. if (this.textLayer) {
  10165. if (hideTextLayer) {
  10166. this.textLayer.hide();
  10167. this.structTreeLayer?.hide();
  10168. } else if (redrawTextLayer) {
  10169. this.#renderTextLayer();
  10170. }
  10171. }
  10172. }
  10173. get width() {
  10174. return this.viewport.width;
  10175. }
  10176. get height() {
  10177. return this.viewport.height;
  10178. }
  10179. getPagePoint(x, y) {
  10180. return this.viewport.convertToPdfPoint(x, y);
  10181. }
  10182. async #finishRenderTask(renderTask, error = null) {
  10183. if (renderTask === this.renderTask) {
  10184. this.renderTask = null;
  10185. }
  10186. if (error instanceof _pdfjsLib.RenderingCancelledException) {
  10187. this.#renderError = null;
  10188. return;
  10189. }
  10190. this.#renderError = error;
  10191. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  10192. this._resetZoomLayer(true);
  10193. this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots;
  10194. this.eventBus.dispatch('pagerendered', {
  10195. source: this,
  10196. pageNumber: this.id,
  10197. cssTransform: false,
  10198. timestamp: performance.now(),
  10199. error: this.#renderError
  10200. });
  10201. if (error) {
  10202. throw error;
  10203. }
  10204. }
  10205. async draw() {
  10206. if (this.renderingState !== _ui_utils.RenderingStates.INITIAL) {
  10207. console.error('Must be in new state before drawing');
  10208. this.reset();
  10209. }
  10210. const { div, l10n, pageColors, pdfPage, viewport } = this;
  10211. if (!pdfPage) {
  10212. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  10213. throw new Error('pdfPage is not loaded');
  10214. }
  10215. this.renderingState = _ui_utils.RenderingStates.RUNNING;
  10216. const canvasWrapper = document.createElement('div');
  10217. canvasWrapper.classList.add('canvasWrapper');
  10218. div.append(canvasWrapper);
  10219. if (!this.textLayer && this.#textLayerMode !== _ui_utils.TextLayerMode.DISABLE && !pdfPage.isPureXfa) {
  10220. this._accessibilityManager ||= new _text_accessibility.TextAccessibilityManager();
  10221. this.textLayer = new _text_layer_builder.TextLayerBuilder({
  10222. highlighter: this._textHighlighter,
  10223. accessibilityManager: this._accessibilityManager,
  10224. isOffscreenCanvasSupported: this.isOffscreenCanvasSupported,
  10225. enablePermissions: this.#textLayerMode === _ui_utils.TextLayerMode.ENABLE_PERMISSIONS
  10226. });
  10227. div.append(this.textLayer.div);
  10228. }
  10229. if (!this.annotationLayer && this.#annotationMode !== _pdfjsLib.AnnotationMode.DISABLE) {
  10230. const { annotationStorage, downloadManager, enableScripting, fieldObjectsPromise, hasJSActionsPromise, linkService } =
  10231. this.#layerProperties();
  10232. this._annotationCanvasMap ||= new Map();
  10233. this.annotationLayer = new _annotation_layer_builder.AnnotationLayerBuilder({
  10234. pageDiv: div,
  10235. pdfPage,
  10236. annotationStorage,
  10237. imageResourcesPath: this.imageResourcesPath,
  10238. renderForms: this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS,
  10239. linkService,
  10240. downloadManager,
  10241. l10n,
  10242. enableScripting,
  10243. hasJSActionsPromise,
  10244. fieldObjectsPromise,
  10245. annotationCanvasMap: this._annotationCanvasMap,
  10246. accessibilityManager: this._accessibilityManager
  10247. });
  10248. }
  10249. const renderContinueCallback = (cont) => {
  10250. showCanvas?.(false);
  10251. if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) {
  10252. this.renderingState = _ui_utils.RenderingStates.PAUSED;
  10253. this.resume = () => {
  10254. this.renderingState = _ui_utils.RenderingStates.RUNNING;
  10255. cont();
  10256. };
  10257. return;
  10258. }
  10259. cont();
  10260. };
  10261. const { width, height } = viewport;
  10262. const canvas = document.createElement('canvas');
  10263. canvas.setAttribute('role', 'presentation');
  10264. canvas.hidden = true;
  10265. const hasHCM = !!(pageColors?.background && pageColors?.foreground);
  10266. let showCanvas = (isLastShow) => {
  10267. if (!hasHCM || isLastShow) {
  10268. canvas.hidden = false;
  10269. showCanvas = null;
  10270. }
  10271. };
  10272. canvasWrapper.append(canvas);
  10273. this.canvas = canvas;
  10274. const ctx = canvas.getContext('2d', {
  10275. alpha: false
  10276. });
  10277. const outputScale = (this.outputScale = new _ui_utils.OutputScale());
  10278. if (this.useOnlyCssZoom) {
  10279. const actualSizeViewport = viewport.clone({
  10280. scale: _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS
  10281. });
  10282. outputScale.sx *= actualSizeViewport.width / width;
  10283. outputScale.sy *= actualSizeViewport.height / height;
  10284. }
  10285. if (this.maxCanvasPixels > 0) {
  10286. const pixelsInViewport = width * height;
  10287. const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport);
  10288. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  10289. outputScale.sx = maxScale;
  10290. outputScale.sy = maxScale;
  10291. this.hasRestrictedScaling = true;
  10292. } else {
  10293. this.hasRestrictedScaling = false;
  10294. }
  10295. }
  10296. const sfx = (0, _ui_utils.approximateFraction)(outputScale.sx);
  10297. const sfy = (0, _ui_utils.approximateFraction)(outputScale.sy);
  10298. canvas.width = (0, _ui_utils.roundToDivide)(width * outputScale.sx, sfx[0]);
  10299. canvas.height = (0, _ui_utils.roundToDivide)(height * outputScale.sy, sfy[0]);
  10300. const { style } = canvas;
  10301. style.width = (0, _ui_utils.roundToDivide)(width, sfx[1]) + 'px';
  10302. style.height = (0, _ui_utils.roundToDivide)(height, sfy[1]) + 'px';
  10303. this.#viewportMap.set(canvas, viewport);
  10304. const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null;
  10305. const renderContext = {
  10306. canvasContext: ctx,
  10307. transform,
  10308. viewport,
  10309. annotationMode: this.#annotationMode,
  10310. optionalContentConfigPromise: this._optionalContentConfigPromise,
  10311. annotationCanvasMap: this._annotationCanvasMap,
  10312. pageColors
  10313. };
  10314. const renderTask = (this.renderTask = this.pdfPage.render(renderContext));
  10315. renderTask.onContinue = renderContinueCallback;
  10316. const resultPromise = renderTask.promise.then(
  10317. async () => {
  10318. showCanvas?.(true);
  10319. await this.#finishRenderTask(renderTask);
  10320. this.#renderTextLayer();
  10321. if (this.annotationLayer) {
  10322. await this.#renderAnnotationLayer();
  10323. }
  10324. if (!this.annotationEditorLayer) {
  10325. const { annotationEditorUIManager } = this.#layerProperties();
  10326. if (!annotationEditorUIManager) {
  10327. return;
  10328. }
  10329. this.annotationEditorLayer = new _annotation_editor_layer_builder.AnnotationEditorLayerBuilder({
  10330. uiManager: annotationEditorUIManager,
  10331. pageDiv: div,
  10332. pdfPage,
  10333. l10n,
  10334. accessibilityManager: this._accessibilityManager
  10335. });
  10336. }
  10337. this.#renderAnnotationEditorLayer();
  10338. },
  10339. (error) => {
  10340. if (!(error instanceof _pdfjsLib.RenderingCancelledException)) {
  10341. showCanvas?.(true);
  10342. }
  10343. return this.#finishRenderTask(renderTask, error);
  10344. }
  10345. );
  10346. if (pdfPage.isPureXfa) {
  10347. if (!this.xfaLayer) {
  10348. const { annotationStorage, linkService } = this.#layerProperties();
  10349. this.xfaLayer = new _xfa_layer_builder.XfaLayerBuilder({
  10350. pageDiv: div,
  10351. pdfPage,
  10352. annotationStorage,
  10353. linkService
  10354. });
  10355. } else if (this.xfaLayer.div) {
  10356. div.append(this.xfaLayer.div);
  10357. }
  10358. this.#renderXfaLayer();
  10359. }
  10360. div.setAttribute('data-loaded', true);
  10361. this.eventBus.dispatch('pagerender', {
  10362. source: this,
  10363. pageNumber: this.id
  10364. });
  10365. return resultPromise;
  10366. }
  10367. setPageLabel(label) {
  10368. this.pageLabel = typeof label === 'string' ? label : null;
  10369. if (this.pageLabel !== null) {
  10370. this.div.setAttribute('data-page-label', this.pageLabel);
  10371. } else {
  10372. this.div.removeAttribute('data-page-label');
  10373. }
  10374. }
  10375. get thumbnailCanvas() {
  10376. const { initialOptionalContent, regularAnnotations } = this.#useThumbnailCanvas;
  10377. return initialOptionalContent && regularAnnotations ? this.canvas : null;
  10378. }
  10379. }
  10380. exports.PDFPageView = PDFPageView;
  10381. /***/
  10382. },
  10383. /* 31 */
  10384. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  10385. Object.defineProperty(exports, '__esModule', {
  10386. value: true
  10387. });
  10388. exports.AnnotationEditorLayerBuilder = void 0;
  10389. var _pdfjsLib = __webpack_require__(4);
  10390. var _l10n_utils = __webpack_require__(29);
  10391. class AnnotationEditorLayerBuilder {
  10392. #uiManager;
  10393. constructor(options) {
  10394. this.pageDiv = options.pageDiv;
  10395. this.pdfPage = options.pdfPage;
  10396. this.accessibilityManager = options.accessibilityManager;
  10397. this.l10n = options.l10n || _l10n_utils.NullL10n;
  10398. this.annotationEditorLayer = null;
  10399. this.div = null;
  10400. this._cancelled = false;
  10401. this.#uiManager = options.uiManager;
  10402. }
  10403. async render(viewport, intent = 'display') {
  10404. if (intent !== 'display') {
  10405. return;
  10406. }
  10407. if (this._cancelled) {
  10408. return;
  10409. }
  10410. const clonedViewport = viewport.clone({
  10411. dontFlip: true
  10412. });
  10413. if (this.div) {
  10414. this.annotationEditorLayer.update({
  10415. viewport: clonedViewport
  10416. });
  10417. this.show();
  10418. return;
  10419. }
  10420. const div = (this.div = document.createElement('div'));
  10421. div.className = 'annotationEditorLayer';
  10422. div.tabIndex = 0;
  10423. div.hidden = true;
  10424. this.pageDiv.append(div);
  10425. this.annotationEditorLayer = new _pdfjsLib.AnnotationEditorLayer({
  10426. uiManager: this.#uiManager,
  10427. div,
  10428. accessibilityManager: this.accessibilityManager,
  10429. pageIndex: this.pdfPage.pageNumber - 1,
  10430. l10n: this.l10n,
  10431. viewport: clonedViewport
  10432. });
  10433. const parameters = {
  10434. viewport: clonedViewport,
  10435. div,
  10436. annotations: null,
  10437. intent
  10438. };
  10439. this.annotationEditorLayer.render(parameters);
  10440. this.show();
  10441. }
  10442. cancel() {
  10443. this._cancelled = true;
  10444. if (!this.div) {
  10445. return;
  10446. }
  10447. this.pageDiv = null;
  10448. this.annotationEditorLayer.destroy();
  10449. this.div.remove();
  10450. }
  10451. hide() {
  10452. if (!this.div) {
  10453. return;
  10454. }
  10455. this.div.hidden = true;
  10456. }
  10457. show() {
  10458. if (!this.div || this.annotationEditorLayer.isEmpty) {
  10459. return;
  10460. }
  10461. this.div.hidden = false;
  10462. }
  10463. }
  10464. exports.AnnotationEditorLayerBuilder = AnnotationEditorLayerBuilder;
  10465. /***/
  10466. },
  10467. /* 32 */
  10468. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  10469. Object.defineProperty(exports, '__esModule', {
  10470. value: true
  10471. });
  10472. exports.AnnotationLayerBuilder = void 0;
  10473. var _pdfjsLib = __webpack_require__(4);
  10474. var _l10n_utils = __webpack_require__(29);
  10475. var _ui_utils = __webpack_require__(3);
  10476. class AnnotationLayerBuilder {
  10477. #numAnnotations = 0;
  10478. #onPresentationModeChanged = null;
  10479. constructor({
  10480. pageDiv,
  10481. pdfPage,
  10482. linkService,
  10483. downloadManager,
  10484. annotationStorage = null,
  10485. imageResourcesPath = '',
  10486. renderForms = true,
  10487. l10n = _l10n_utils.NullL10n,
  10488. enableScripting = false,
  10489. hasJSActionsPromise = null,
  10490. fieldObjectsPromise = null,
  10491. annotationCanvasMap = null,
  10492. accessibilityManager = null
  10493. }) {
  10494. this.pageDiv = pageDiv;
  10495. this.pdfPage = pdfPage;
  10496. this.linkService = linkService;
  10497. this.downloadManager = downloadManager;
  10498. this.imageResourcesPath = imageResourcesPath;
  10499. this.renderForms = renderForms;
  10500. this.l10n = l10n;
  10501. this.annotationStorage = annotationStorage;
  10502. this.enableScripting = enableScripting;
  10503. this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false);
  10504. this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null);
  10505. this._annotationCanvasMap = annotationCanvasMap;
  10506. this._accessibilityManager = accessibilityManager;
  10507. this.div = null;
  10508. this._cancelled = false;
  10509. this._eventBus = linkService.eventBus;
  10510. }
  10511. async render(viewport, intent = 'display') {
  10512. if (this.div) {
  10513. if (this._cancelled || this.#numAnnotations === 0) {
  10514. return;
  10515. }
  10516. _pdfjsLib.AnnotationLayer.update({
  10517. viewport: viewport.clone({
  10518. dontFlip: true
  10519. }),
  10520. div: this.div,
  10521. annotationCanvasMap: this._annotationCanvasMap
  10522. });
  10523. return;
  10524. }
  10525. const [annotations, hasJSActions, fieldObjects] = await Promise.all([
  10526. this.pdfPage.getAnnotations({
  10527. intent
  10528. }),
  10529. this._hasJSActionsPromise,
  10530. this._fieldObjectsPromise
  10531. ]);
  10532. if (this._cancelled) {
  10533. return;
  10534. }
  10535. this.#numAnnotations = annotations.length;
  10536. this.div = document.createElement('div');
  10537. this.div.className = 'annotationLayer';
  10538. this.pageDiv.append(this.div);
  10539. if (this.#numAnnotations === 0) {
  10540. this.hide();
  10541. return;
  10542. }
  10543. _pdfjsLib.AnnotationLayer.render({
  10544. viewport: viewport.clone({
  10545. dontFlip: true
  10546. }),
  10547. div: this.div,
  10548. annotations,
  10549. page: this.pdfPage,
  10550. imageResourcesPath: this.imageResourcesPath,
  10551. renderForms: this.renderForms,
  10552. linkService: this.linkService,
  10553. downloadManager: this.downloadManager,
  10554. annotationStorage: this.annotationStorage,
  10555. enableScripting: this.enableScripting,
  10556. hasJSActions,
  10557. fieldObjects,
  10558. annotationCanvasMap: this._annotationCanvasMap,
  10559. accessibilityManager: this._accessibilityManager
  10560. });
  10561. this.l10n.translate(this.div);
  10562. if (this.linkService.isInPresentationMode) {
  10563. this.#updatePresentationModeState(_ui_utils.PresentationModeState.FULLSCREEN);
  10564. }
  10565. if (!this.#onPresentationModeChanged) {
  10566. this.#onPresentationModeChanged = (evt) => {
  10567. this.#updatePresentationModeState(evt.state);
  10568. };
  10569. this._eventBus?._on('presentationmodechanged', this.#onPresentationModeChanged);
  10570. }
  10571. }
  10572. cancel() {
  10573. this._cancelled = true;
  10574. if (this.#onPresentationModeChanged) {
  10575. this._eventBus?._off('presentationmodechanged', this.#onPresentationModeChanged);
  10576. this.#onPresentationModeChanged = null;
  10577. }
  10578. }
  10579. hide() {
  10580. if (!this.div) {
  10581. return;
  10582. }
  10583. this.div.hidden = true;
  10584. }
  10585. #updatePresentationModeState(state) {
  10586. if (!this.div) {
  10587. return;
  10588. }
  10589. let disableFormElements = false;
  10590. switch (state) {
  10591. case _ui_utils.PresentationModeState.FULLSCREEN:
  10592. disableFormElements = true;
  10593. break;
  10594. case _ui_utils.PresentationModeState.NORMAL:
  10595. break;
  10596. default:
  10597. return;
  10598. }
  10599. for (const section of this.div.childNodes) {
  10600. if (section.hasAttribute('data-internal-link')) {
  10601. continue;
  10602. }
  10603. section.inert = disableFormElements;
  10604. }
  10605. }
  10606. }
  10607. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  10608. /***/
  10609. },
  10610. /* 33 */
  10611. /***/ (__unused_webpack_module, exports) => {
  10612. Object.defineProperty(exports, '__esModule', {
  10613. value: true
  10614. });
  10615. exports.StructTreeLayerBuilder = void 0;
  10616. const PDF_ROLE_TO_HTML_ROLE = {
  10617. Document: null,
  10618. DocumentFragment: null,
  10619. Part: 'group',
  10620. Sect: 'group',
  10621. Div: 'group',
  10622. Aside: 'note',
  10623. NonStruct: 'none',
  10624. P: null,
  10625. H: 'heading',
  10626. Title: null,
  10627. FENote: 'note',
  10628. Sub: 'group',
  10629. Lbl: null,
  10630. Span: null,
  10631. Em: null,
  10632. Strong: null,
  10633. Link: 'link',
  10634. Annot: 'note',
  10635. Form: 'form',
  10636. Ruby: null,
  10637. RB: null,
  10638. RT: null,
  10639. RP: null,
  10640. Warichu: null,
  10641. WT: null,
  10642. WP: null,
  10643. L: 'list',
  10644. LI: 'listitem',
  10645. LBody: null,
  10646. Table: 'table',
  10647. TR: 'row',
  10648. TH: 'columnheader',
  10649. TD: 'cell',
  10650. THead: 'columnheader',
  10651. TBody: null,
  10652. TFoot: null,
  10653. Caption: null,
  10654. Figure: 'figure',
  10655. Formula: null,
  10656. Artifact: null
  10657. };
  10658. const HEADING_PATTERN = /^H(\d+)$/;
  10659. class StructTreeLayerBuilder {
  10660. #treeDom = undefined;
  10661. get renderingDone() {
  10662. return this.#treeDom !== undefined;
  10663. }
  10664. render(structTree) {
  10665. if (this.#treeDom !== undefined) {
  10666. return this.#treeDom;
  10667. }
  10668. const treeDom = this.#walk(structTree);
  10669. treeDom?.classList.add('structTree');
  10670. return (this.#treeDom = treeDom);
  10671. }
  10672. hide() {
  10673. if (this.#treeDom && !this.#treeDom.hidden) {
  10674. this.#treeDom.hidden = true;
  10675. }
  10676. }
  10677. show() {
  10678. if (this.#treeDom?.hidden) {
  10679. this.#treeDom.hidden = false;
  10680. }
  10681. }
  10682. #setAttributes(structElement, htmlElement) {
  10683. if (structElement.alt !== undefined) {
  10684. htmlElement.setAttribute('aria-label', structElement.alt);
  10685. }
  10686. if (structElement.id !== undefined) {
  10687. htmlElement.setAttribute('aria-owns', structElement.id);
  10688. }
  10689. if (structElement.lang !== undefined) {
  10690. htmlElement.setAttribute('lang', structElement.lang);
  10691. }
  10692. }
  10693. #walk(node) {
  10694. if (!node) {
  10695. return null;
  10696. }
  10697. const element = document.createElement('span');
  10698. if ('role' in node) {
  10699. const { role } = node;
  10700. const match = role.match(HEADING_PATTERN);
  10701. if (match) {
  10702. element.setAttribute('role', 'heading');
  10703. element.setAttribute('aria-level', match[1]);
  10704. } else if (PDF_ROLE_TO_HTML_ROLE[role]) {
  10705. element.setAttribute('role', PDF_ROLE_TO_HTML_ROLE[role]);
  10706. }
  10707. }
  10708. this.#setAttributes(node, element);
  10709. if (node.children) {
  10710. if (node.children.length === 1 && 'id' in node.children[0]) {
  10711. this.#setAttributes(node.children[0], element);
  10712. } else {
  10713. for (const kid of node.children) {
  10714. element.append(this.#walk(kid));
  10715. }
  10716. }
  10717. }
  10718. return element;
  10719. }
  10720. }
  10721. exports.StructTreeLayerBuilder = StructTreeLayerBuilder;
  10722. /***/
  10723. },
  10724. /* 34 */
  10725. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  10726. Object.defineProperty(exports, '__esModule', {
  10727. value: true
  10728. });
  10729. exports.TextAccessibilityManager = void 0;
  10730. var _ui_utils = __webpack_require__(3);
  10731. class TextAccessibilityManager {
  10732. #enabled = false;
  10733. #textChildren = null;
  10734. #textNodes = new Map();
  10735. #waitingElements = new Map();
  10736. setTextMapping(textDivs) {
  10737. this.#textChildren = textDivs;
  10738. }
  10739. static #compareElementPositions(e1, e2) {
  10740. const rect1 = e1.getBoundingClientRect();
  10741. const rect2 = e2.getBoundingClientRect();
  10742. if (rect1.width === 0 && rect1.height === 0) {
  10743. return +1;
  10744. }
  10745. if (rect2.width === 0 && rect2.height === 0) {
  10746. return -1;
  10747. }
  10748. const top1 = rect1.y;
  10749. const bot1 = rect1.y + rect1.height;
  10750. const mid1 = rect1.y + rect1.height / 2;
  10751. const top2 = rect2.y;
  10752. const bot2 = rect2.y + rect2.height;
  10753. const mid2 = rect2.y + rect2.height / 2;
  10754. if (mid1 <= top2 && mid2 >= bot1) {
  10755. return -1;
  10756. }
  10757. if (mid2 <= top1 && mid1 >= bot2) {
  10758. return +1;
  10759. }
  10760. const centerX1 = rect1.x + rect1.width / 2;
  10761. const centerX2 = rect2.x + rect2.width / 2;
  10762. return centerX1 - centerX2;
  10763. }
  10764. enable() {
  10765. if (this.#enabled) {
  10766. throw new Error('TextAccessibilityManager is already enabled.');
  10767. }
  10768. if (!this.#textChildren) {
  10769. throw new Error('Text divs and strings have not been set.');
  10770. }
  10771. this.#enabled = true;
  10772. this.#textChildren = this.#textChildren.slice();
  10773. this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions);
  10774. if (this.#textNodes.size > 0) {
  10775. const textChildren = this.#textChildren;
  10776. for (const [id, nodeIndex] of this.#textNodes) {
  10777. const element = document.getElementById(id);
  10778. if (!element) {
  10779. this.#textNodes.delete(id);
  10780. continue;
  10781. }
  10782. this.#addIdToAriaOwns(id, textChildren[nodeIndex]);
  10783. }
  10784. }
  10785. for (const [element, isRemovable] of this.#waitingElements) {
  10786. this.addPointerInTextLayer(element, isRemovable);
  10787. }
  10788. this.#waitingElements.clear();
  10789. }
  10790. disable() {
  10791. if (!this.#enabled) {
  10792. return;
  10793. }
  10794. this.#waitingElements.clear();
  10795. this.#textChildren = null;
  10796. this.#enabled = false;
  10797. }
  10798. removePointerInTextLayer(element) {
  10799. if (!this.#enabled) {
  10800. this.#waitingElements.delete(element);
  10801. return;
  10802. }
  10803. const children = this.#textChildren;
  10804. if (!children || children.length === 0) {
  10805. return;
  10806. }
  10807. const { id } = element;
  10808. const nodeIndex = this.#textNodes.get(id);
  10809. if (nodeIndex === undefined) {
  10810. return;
  10811. }
  10812. const node = children[nodeIndex];
  10813. this.#textNodes.delete(id);
  10814. let owns = node.getAttribute('aria-owns');
  10815. if (owns?.includes(id)) {
  10816. owns = owns
  10817. .split(' ')
  10818. .filter((x) => x !== id)
  10819. .join(' ');
  10820. if (owns) {
  10821. node.setAttribute('aria-owns', owns);
  10822. } else {
  10823. node.removeAttribute('aria-owns');
  10824. node.setAttribute('role', 'presentation');
  10825. }
  10826. }
  10827. }
  10828. #addIdToAriaOwns(id, node) {
  10829. const owns = node.getAttribute('aria-owns');
  10830. if (!owns?.includes(id)) {
  10831. node.setAttribute('aria-owns', owns ? `${owns} ${id}` : id);
  10832. }
  10833. node.removeAttribute('role');
  10834. }
  10835. addPointerInTextLayer(element, isRemovable) {
  10836. const { id } = element;
  10837. if (!id) {
  10838. return;
  10839. }
  10840. if (!this.#enabled) {
  10841. this.#waitingElements.set(element, isRemovable);
  10842. return;
  10843. }
  10844. if (isRemovable) {
  10845. this.removePointerInTextLayer(element);
  10846. }
  10847. const children = this.#textChildren;
  10848. if (!children || children.length === 0) {
  10849. return;
  10850. }
  10851. const index = (0, _ui_utils.binarySearchFirstItem)(
  10852. children,
  10853. (node) => TextAccessibilityManager.#compareElementPositions(element, node) < 0
  10854. );
  10855. const nodeIndex = Math.max(0, index - 1);
  10856. this.#addIdToAriaOwns(id, children[nodeIndex]);
  10857. this.#textNodes.set(id, nodeIndex);
  10858. }
  10859. moveElementInDOM(container, element, contentElement, isRemovable) {
  10860. this.addPointerInTextLayer(contentElement, isRemovable);
  10861. if (!container.hasChildNodes()) {
  10862. container.append(element);
  10863. return;
  10864. }
  10865. const children = Array.from(container.childNodes).filter((node) => node !== element);
  10866. if (children.length === 0) {
  10867. return;
  10868. }
  10869. const elementToCompare = contentElement || element;
  10870. const index = (0, _ui_utils.binarySearchFirstItem)(
  10871. children,
  10872. (node) => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0
  10873. );
  10874. if (index === 0) {
  10875. children[0].before(element);
  10876. } else {
  10877. children[index - 1].after(element);
  10878. }
  10879. }
  10880. }
  10881. exports.TextAccessibilityManager = TextAccessibilityManager;
  10882. /***/
  10883. },
  10884. /* 35 */
  10885. /***/ (__unused_webpack_module, exports) => {
  10886. Object.defineProperty(exports, '__esModule', {
  10887. value: true
  10888. });
  10889. exports.TextHighlighter = void 0;
  10890. class TextHighlighter {
  10891. constructor({ findController, eventBus, pageIndex }) {
  10892. this.findController = findController;
  10893. this.matches = [];
  10894. this.eventBus = eventBus;
  10895. this.pageIdx = pageIndex;
  10896. this._onUpdateTextLayerMatches = null;
  10897. this.textDivs = null;
  10898. this.textContentItemsStr = null;
  10899. this.enabled = false;
  10900. }
  10901. setTextMapping(divs, texts) {
  10902. this.textDivs = divs;
  10903. this.textContentItemsStr = texts;
  10904. }
  10905. enable() {
  10906. if (!this.textDivs || !this.textContentItemsStr) {
  10907. throw new Error('Text divs and strings have not been set.');
  10908. }
  10909. if (this.enabled) {
  10910. throw new Error('TextHighlighter is already enabled.');
  10911. }
  10912. this.enabled = true;
  10913. if (!this._onUpdateTextLayerMatches) {
  10914. this._onUpdateTextLayerMatches = (evt) => {
  10915. if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) {
  10916. this._updateMatches();
  10917. }
  10918. };
  10919. this.eventBus._on('updatetextlayermatches', this._onUpdateTextLayerMatches);
  10920. }
  10921. this._updateMatches();
  10922. }
  10923. disable() {
  10924. if (!this.enabled) {
  10925. return;
  10926. }
  10927. this.enabled = false;
  10928. if (this._onUpdateTextLayerMatches) {
  10929. this.eventBus._off('updatetextlayermatches', this._onUpdateTextLayerMatches);
  10930. this._onUpdateTextLayerMatches = null;
  10931. }
  10932. this._updateMatches(true);
  10933. }
  10934. _convertMatches(matches, matchesLength) {
  10935. if (!matches) {
  10936. return [];
  10937. }
  10938. const { textContentItemsStr } = this;
  10939. let i = 0,
  10940. iIndex = 0;
  10941. const end = textContentItemsStr.length - 1;
  10942. const result = [];
  10943. for (let m = 0, mm = matches.length; m < mm; m++) {
  10944. let matchIdx = matches[m];
  10945. while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) {
  10946. iIndex += textContentItemsStr[i].length;
  10947. i++;
  10948. }
  10949. if (i === textContentItemsStr.length) {
  10950. console.error('Could not find a matching mapping');
  10951. }
  10952. const match = {
  10953. begin: {
  10954. divIdx: i,
  10955. offset: matchIdx - iIndex
  10956. }
  10957. };
  10958. matchIdx += matchesLength[m];
  10959. while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) {
  10960. iIndex += textContentItemsStr[i].length;
  10961. i++;
  10962. }
  10963. match.end = {
  10964. divIdx: i,
  10965. offset: matchIdx - iIndex
  10966. };
  10967. result.push(match);
  10968. }
  10969. return result;
  10970. }
  10971. _renderMatches(matches) {
  10972. if (matches.length === 0) {
  10973. return;
  10974. }
  10975. const { findController, pageIdx } = this;
  10976. const { textContentItemsStr, textDivs } = this;
  10977. const isSelectedPage = pageIdx === findController.selected.pageIdx;
  10978. const selectedMatchIdx = findController.selected.matchIdx;
  10979. const highlightAll = findController.state.highlightAll;
  10980. let prevEnd = null;
  10981. const infinity = {
  10982. divIdx: -1,
  10983. offset: undefined
  10984. };
  10985. function beginText(begin, className) {
  10986. const divIdx = begin.divIdx;
  10987. textDivs[divIdx].textContent = '';
  10988. return appendTextToDiv(divIdx, 0, begin.offset, className);
  10989. }
  10990. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  10991. let div = textDivs[divIdx];
  10992. if (div.nodeType === Node.TEXT_NODE) {
  10993. const span = document.createElement('span');
  10994. div.before(span);
  10995. span.append(div);
  10996. textDivs[divIdx] = span;
  10997. div = span;
  10998. }
  10999. const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
  11000. const node = document.createTextNode(content);
  11001. if (className) {
  11002. const span = document.createElement('span');
  11003. span.className = `${className} appended`;
  11004. span.append(node);
  11005. div.append(span);
  11006. return className.includes('selected') ? span.offsetLeft : 0;
  11007. }
  11008. div.append(node);
  11009. return 0;
  11010. }
  11011. let i0 = selectedMatchIdx,
  11012. i1 = i0 + 1;
  11013. if (highlightAll) {
  11014. i0 = 0;
  11015. i1 = matches.length;
  11016. } else if (!isSelectedPage) {
  11017. return;
  11018. }
  11019. let lastDivIdx = -1;
  11020. let lastOffset = -1;
  11021. for (let i = i0; i < i1; i++) {
  11022. const match = matches[i];
  11023. const begin = match.begin;
  11024. if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) {
  11025. continue;
  11026. }
  11027. lastDivIdx = begin.divIdx;
  11028. lastOffset = begin.offset;
  11029. const end = match.end;
  11030. const isSelected = isSelectedPage && i === selectedMatchIdx;
  11031. const highlightSuffix = isSelected ? ' selected' : '';
  11032. let selectedLeft = 0;
  11033. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  11034. if (prevEnd !== null) {
  11035. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  11036. }
  11037. beginText(begin);
  11038. } else {
  11039. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  11040. }
  11041. if (begin.divIdx === end.divIdx) {
  11042. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, 'highlight' + highlightSuffix);
  11043. } else {
  11044. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, 'highlight begin' + highlightSuffix);
  11045. for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  11046. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  11047. }
  11048. beginText(end, 'highlight end' + highlightSuffix);
  11049. }
  11050. prevEnd = end;
  11051. if (isSelected) {
  11052. findController.scrollMatchIntoView({
  11053. element: textDivs[begin.divIdx],
  11054. selectedLeft,
  11055. pageIndex: pageIdx,
  11056. matchIndex: selectedMatchIdx
  11057. });
  11058. }
  11059. }
  11060. if (prevEnd) {
  11061. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  11062. }
  11063. }
  11064. _updateMatches(reset = false) {
  11065. if (!this.enabled && !reset) {
  11066. return;
  11067. }
  11068. const { findController, matches, pageIdx } = this;
  11069. const { textContentItemsStr, textDivs } = this;
  11070. let clearedUntilDivIdx = -1;
  11071. for (const match of matches) {
  11072. const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  11073. for (let n = begin, end = match.end.divIdx; n <= end; n++) {
  11074. const div = textDivs[n];
  11075. div.textContent = textContentItemsStr[n];
  11076. div.className = '';
  11077. }
  11078. clearedUntilDivIdx = match.end.divIdx + 1;
  11079. }
  11080. if (!findController?.highlightMatches || reset) {
  11081. return;
  11082. }
  11083. const pageMatches = findController.pageMatches[pageIdx] || null;
  11084. const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null;
  11085. this.matches = this._convertMatches(pageMatches, pageMatchesLength);
  11086. this._renderMatches(this.matches);
  11087. }
  11088. }
  11089. exports.TextHighlighter = TextHighlighter;
  11090. /***/
  11091. },
  11092. /* 36 */
  11093. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  11094. Object.defineProperty(exports, '__esModule', {
  11095. value: true
  11096. });
  11097. exports.TextLayerBuilder = void 0;
  11098. var _pdfjsLib = __webpack_require__(4);
  11099. var _ui_utils = __webpack_require__(3);
  11100. class TextLayerBuilder {
  11101. #enablePermissions = false;
  11102. #rotation = 0;
  11103. #scale = 0;
  11104. #textContentSource = null;
  11105. constructor({ highlighter = null, accessibilityManager = null, isOffscreenCanvasSupported = true, enablePermissions = false }) {
  11106. this.textContentItemsStr = [];
  11107. this.renderingDone = false;
  11108. this.textDivs = [];
  11109. this.textDivProperties = new WeakMap();
  11110. this.textLayerRenderTask = null;
  11111. this.highlighter = highlighter;
  11112. this.accessibilityManager = accessibilityManager;
  11113. this.isOffscreenCanvasSupported = isOffscreenCanvasSupported;
  11114. this.#enablePermissions = enablePermissions === true;
  11115. this.div = document.createElement('div');
  11116. this.div.className = 'textLayer';
  11117. this.hide();
  11118. }
  11119. #finishRendering() {
  11120. this.renderingDone = true;
  11121. const endOfContent = document.createElement('div');
  11122. endOfContent.className = 'endOfContent';
  11123. this.div.append(endOfContent);
  11124. this.#bindMouse();
  11125. }
  11126. get numTextDivs() {
  11127. return this.textDivs.length;
  11128. }
  11129. async render(viewport) {
  11130. if (!this.#textContentSource) {
  11131. throw new Error('No "textContentSource" parameter specified.');
  11132. }
  11133. const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  11134. const { rotation } = viewport;
  11135. if (this.renderingDone) {
  11136. const mustRotate = rotation !== this.#rotation;
  11137. const mustRescale = scale !== this.#scale;
  11138. if (mustRotate || mustRescale) {
  11139. this.hide();
  11140. (0, _pdfjsLib.updateTextLayer)({
  11141. container: this.div,
  11142. viewport,
  11143. textDivs: this.textDivs,
  11144. textDivProperties: this.textDivProperties,
  11145. isOffscreenCanvasSupported: this.isOffscreenCanvasSupported,
  11146. mustRescale,
  11147. mustRotate
  11148. });
  11149. this.#scale = scale;
  11150. this.#rotation = rotation;
  11151. }
  11152. this.show();
  11153. return;
  11154. }
  11155. this.cancel();
  11156. this.highlighter?.setTextMapping(this.textDivs, this.textContentItemsStr);
  11157. this.accessibilityManager?.setTextMapping(this.textDivs);
  11158. this.textLayerRenderTask = (0, _pdfjsLib.renderTextLayer)({
  11159. textContentSource: this.#textContentSource,
  11160. container: this.div,
  11161. viewport,
  11162. textDivs: this.textDivs,
  11163. textDivProperties: this.textDivProperties,
  11164. textContentItemsStr: this.textContentItemsStr,
  11165. isOffscreenCanvasSupported: this.isOffscreenCanvasSupported
  11166. });
  11167. await this.textLayerRenderTask.promise;
  11168. this.#finishRendering();
  11169. this.#scale = scale;
  11170. this.#rotation = rotation;
  11171. this.show();
  11172. this.accessibilityManager?.enable();
  11173. }
  11174. hide() {
  11175. if (!this.div.hidden) {
  11176. this.highlighter?.disable();
  11177. this.div.hidden = true;
  11178. }
  11179. }
  11180. show() {
  11181. if (this.div.hidden && this.renderingDone) {
  11182. this.div.hidden = false;
  11183. this.highlighter?.enable();
  11184. }
  11185. }
  11186. cancel() {
  11187. if (this.textLayerRenderTask) {
  11188. this.textLayerRenderTask.cancel();
  11189. this.textLayerRenderTask = null;
  11190. }
  11191. this.highlighter?.disable();
  11192. this.accessibilityManager?.disable();
  11193. this.textContentItemsStr.length = 0;
  11194. this.textDivs.length = 0;
  11195. this.textDivProperties = new WeakMap();
  11196. }
  11197. setTextContentSource(source) {
  11198. this.cancel();
  11199. this.#textContentSource = source;
  11200. }
  11201. #bindMouse() {
  11202. const { div } = this;
  11203. div.addEventListener('mousedown', (evt) => {
  11204. const end = div.querySelector('.endOfContent');
  11205. if (!end) {
  11206. return;
  11207. }
  11208. let adjustTop = evt.target !== div;
  11209. adjustTop &&= getComputedStyle(end).getPropertyValue('-moz-user-select') !== 'none';
  11210. if (adjustTop) {
  11211. const divBounds = div.getBoundingClientRect();
  11212. const r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
  11213. end.style.top = (r * 100).toFixed(2) + '%';
  11214. }
  11215. end.classList.add('active');
  11216. });
  11217. div.addEventListener('mouseup', () => {
  11218. const end = div.querySelector('.endOfContent');
  11219. if (!end) {
  11220. return;
  11221. }
  11222. end.style.top = '';
  11223. end.classList.remove('active');
  11224. });
  11225. div.addEventListener('copy', (event) => {
  11226. if (!this.#enablePermissions) {
  11227. const selection = document.getSelection();
  11228. event.clipboardData.setData('text/plain', (0, _ui_utils.removeNullCharacters)((0, _pdfjsLib.normalizeUnicode)(selection.toString())));
  11229. }
  11230. event.preventDefault();
  11231. event.stopPropagation();
  11232. });
  11233. }
  11234. }
  11235. exports.TextLayerBuilder = TextLayerBuilder;
  11236. /***/
  11237. },
  11238. /* 37 */
  11239. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  11240. Object.defineProperty(exports, '__esModule', {
  11241. value: true
  11242. });
  11243. exports.XfaLayerBuilder = void 0;
  11244. var _pdfjsLib = __webpack_require__(4);
  11245. class XfaLayerBuilder {
  11246. constructor({ pageDiv, pdfPage, annotationStorage = null, linkService, xfaHtml = null }) {
  11247. this.pageDiv = pageDiv;
  11248. this.pdfPage = pdfPage;
  11249. this.annotationStorage = annotationStorage;
  11250. this.linkService = linkService;
  11251. this.xfaHtml = xfaHtml;
  11252. this.div = null;
  11253. this._cancelled = false;
  11254. }
  11255. async render(viewport, intent = 'display') {
  11256. if (intent === 'print') {
  11257. const parameters = {
  11258. viewport: viewport.clone({
  11259. dontFlip: true
  11260. }),
  11261. div: this.div,
  11262. xfaHtml: this.xfaHtml,
  11263. annotationStorage: this.annotationStorage,
  11264. linkService: this.linkService,
  11265. intent
  11266. };
  11267. const div = document.createElement('div');
  11268. this.pageDiv.append(div);
  11269. parameters.div = div;
  11270. return _pdfjsLib.XfaLayer.render(parameters);
  11271. }
  11272. const xfaHtml = await this.pdfPage.getXfa();
  11273. if (this._cancelled || !xfaHtml) {
  11274. return {
  11275. textDivs: []
  11276. };
  11277. }
  11278. const parameters = {
  11279. viewport: viewport.clone({
  11280. dontFlip: true
  11281. }),
  11282. div: this.div,
  11283. xfaHtml,
  11284. annotationStorage: this.annotationStorage,
  11285. linkService: this.linkService,
  11286. intent
  11287. };
  11288. if (this.div) {
  11289. return _pdfjsLib.XfaLayer.update(parameters);
  11290. }
  11291. this.div = document.createElement('div');
  11292. this.pageDiv.append(this.div);
  11293. parameters.div = this.div;
  11294. return _pdfjsLib.XfaLayer.render(parameters);
  11295. }
  11296. cancel() {
  11297. this._cancelled = true;
  11298. }
  11299. hide() {
  11300. if (!this.div) {
  11301. return;
  11302. }
  11303. this.div.hidden = true;
  11304. }
  11305. }
  11306. exports.XfaLayerBuilder = XfaLayerBuilder;
  11307. /***/
  11308. },
  11309. /* 38 */
  11310. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  11311. Object.defineProperty(exports, '__esModule', {
  11312. value: true
  11313. });
  11314. exports.SecondaryToolbar = void 0;
  11315. var _ui_utils = __webpack_require__(3);
  11316. var _pdf_viewer = __webpack_require__(28);
  11317. class SecondaryToolbar {
  11318. constructor(options, eventBus, externalServices) {
  11319. this.toolbar = options.toolbar;
  11320. this.toggleButton = options.toggleButton;
  11321. this.buttons = [
  11322. {
  11323. element: options.presentationModeButton,
  11324. eventName: 'presentationmode',
  11325. close: true
  11326. },
  11327. {
  11328. element: options.printButton,
  11329. eventName: 'print',
  11330. close: true
  11331. },
  11332. {
  11333. element: options.downloadButton,
  11334. eventName: 'download',
  11335. close: true
  11336. },
  11337. {
  11338. element: options.viewBookmarkButton,
  11339. eventName: null,
  11340. close: true
  11341. },
  11342. {
  11343. element: options.firstPageButton,
  11344. eventName: 'firstpage',
  11345. close: true
  11346. },
  11347. {
  11348. element: options.lastPageButton,
  11349. eventName: 'lastpage',
  11350. close: true
  11351. },
  11352. {
  11353. element: options.pageRotateCwButton,
  11354. eventName: 'rotatecw',
  11355. close: false
  11356. },
  11357. {
  11358. element: options.pageRotateCcwButton,
  11359. eventName: 'rotateccw',
  11360. close: false
  11361. },
  11362. {
  11363. element: options.cursorSelectToolButton,
  11364. eventName: 'switchcursortool',
  11365. eventDetails: {
  11366. tool: _ui_utils.CursorTool.SELECT
  11367. },
  11368. close: true
  11369. },
  11370. {
  11371. element: options.cursorHandToolButton,
  11372. eventName: 'switchcursortool',
  11373. eventDetails: {
  11374. tool: _ui_utils.CursorTool.HAND
  11375. },
  11376. close: true
  11377. },
  11378. {
  11379. element: options.scrollPageButton,
  11380. eventName: 'switchscrollmode',
  11381. eventDetails: {
  11382. mode: _ui_utils.ScrollMode.PAGE
  11383. },
  11384. close: true
  11385. },
  11386. {
  11387. element: options.scrollVerticalButton,
  11388. eventName: 'switchscrollmode',
  11389. eventDetails: {
  11390. mode: _ui_utils.ScrollMode.VERTICAL
  11391. },
  11392. close: true
  11393. },
  11394. {
  11395. element: options.scrollHorizontalButton,
  11396. eventName: 'switchscrollmode',
  11397. eventDetails: {
  11398. mode: _ui_utils.ScrollMode.HORIZONTAL
  11399. },
  11400. close: true
  11401. },
  11402. {
  11403. element: options.scrollWrappedButton,
  11404. eventName: 'switchscrollmode',
  11405. eventDetails: {
  11406. mode: _ui_utils.ScrollMode.WRAPPED
  11407. },
  11408. close: true
  11409. },
  11410. {
  11411. element: options.spreadNoneButton,
  11412. eventName: 'switchspreadmode',
  11413. eventDetails: {
  11414. mode: _ui_utils.SpreadMode.NONE
  11415. },
  11416. close: true
  11417. },
  11418. {
  11419. element: options.spreadOddButton,
  11420. eventName: 'switchspreadmode',
  11421. eventDetails: {
  11422. mode: _ui_utils.SpreadMode.ODD
  11423. },
  11424. close: true
  11425. },
  11426. {
  11427. element: options.spreadEvenButton,
  11428. eventName: 'switchspreadmode',
  11429. eventDetails: {
  11430. mode: _ui_utils.SpreadMode.EVEN
  11431. },
  11432. close: true
  11433. },
  11434. {
  11435. element: options.documentPropertiesButton,
  11436. eventName: 'documentproperties',
  11437. close: true
  11438. }
  11439. ];
  11440. this.buttons.push({
  11441. element: options.openFileButton,
  11442. eventName: 'openfile',
  11443. close: true
  11444. });
  11445. this.items = {
  11446. firstPage: options.firstPageButton,
  11447. lastPage: options.lastPageButton,
  11448. pageRotateCw: options.pageRotateCwButton,
  11449. pageRotateCcw: options.pageRotateCcwButton
  11450. };
  11451. this.eventBus = eventBus;
  11452. this.externalServices = externalServices;
  11453. this.opened = false;
  11454. this.#bindClickListeners();
  11455. this.#bindCursorToolsListener(options);
  11456. this.#bindScrollModeListener(options);
  11457. this.#bindSpreadModeListener(options);
  11458. this.reset();
  11459. }
  11460. get isOpen() {
  11461. return this.opened;
  11462. }
  11463. setPageNumber(pageNumber) {
  11464. this.pageNumber = pageNumber;
  11465. this.#updateUIState();
  11466. }
  11467. setPagesCount(pagesCount) {
  11468. this.pagesCount = pagesCount;
  11469. this.#updateUIState();
  11470. }
  11471. reset() {
  11472. this.pageNumber = 0;
  11473. this.pagesCount = 0;
  11474. this.#updateUIState();
  11475. this.eventBus.dispatch('secondarytoolbarreset', {
  11476. source: this
  11477. });
  11478. }
  11479. #updateUIState() {
  11480. this.items.firstPage.disabled = this.pageNumber <= 1;
  11481. this.items.lastPage.disabled = this.pageNumber >= this.pagesCount;
  11482. this.items.pageRotateCw.disabled = this.pagesCount === 0;
  11483. this.items.pageRotateCcw.disabled = this.pagesCount === 0;
  11484. }
  11485. #bindClickListeners() {
  11486. this.toggleButton.addEventListener('click', this.toggle.bind(this));
  11487. for (const { element, eventName, close, eventDetails } of this.buttons) {
  11488. element.addEventListener('click', (evt) => {
  11489. if (eventName !== null) {
  11490. this.eventBus.dispatch(eventName, {
  11491. source: this,
  11492. ...eventDetails
  11493. });
  11494. }
  11495. if (close) {
  11496. this.close();
  11497. }
  11498. this.externalServices.reportTelemetry({
  11499. type: 'buttons',
  11500. data: {
  11501. id: element.id
  11502. }
  11503. });
  11504. });
  11505. }
  11506. }
  11507. #bindCursorToolsListener({ cursorSelectToolButton, cursorHandToolButton }) {
  11508. this.eventBus._on('cursortoolchanged', ({ tool }) => {
  11509. (0, _ui_utils.toggleCheckedBtn)(cursorSelectToolButton, tool === _ui_utils.CursorTool.SELECT);
  11510. (0, _ui_utils.toggleCheckedBtn)(cursorHandToolButton, tool === _ui_utils.CursorTool.HAND);
  11511. });
  11512. }
  11513. #bindScrollModeListener({
  11514. scrollPageButton,
  11515. scrollVerticalButton,
  11516. scrollHorizontalButton,
  11517. scrollWrappedButton,
  11518. spreadNoneButton,
  11519. spreadOddButton,
  11520. spreadEvenButton
  11521. }) {
  11522. const scrollModeChanged = ({ mode }) => {
  11523. (0, _ui_utils.toggleCheckedBtn)(scrollPageButton, mode === _ui_utils.ScrollMode.PAGE);
  11524. (0, _ui_utils.toggleCheckedBtn)(scrollVerticalButton, mode === _ui_utils.ScrollMode.VERTICAL);
  11525. (0, _ui_utils.toggleCheckedBtn)(scrollHorizontalButton, mode === _ui_utils.ScrollMode.HORIZONTAL);
  11526. (0, _ui_utils.toggleCheckedBtn)(scrollWrappedButton, mode === _ui_utils.ScrollMode.WRAPPED);
  11527. const forceScrollModePage = this.pagesCount > _pdf_viewer.PagesCountLimit.FORCE_SCROLL_MODE_PAGE;
  11528. scrollPageButton.disabled = forceScrollModePage;
  11529. scrollVerticalButton.disabled = forceScrollModePage;
  11530. scrollHorizontalButton.disabled = forceScrollModePage;
  11531. scrollWrappedButton.disabled = forceScrollModePage;
  11532. const isHorizontal = mode === _ui_utils.ScrollMode.HORIZONTAL;
  11533. spreadNoneButton.disabled = isHorizontal;
  11534. spreadOddButton.disabled = isHorizontal;
  11535. spreadEvenButton.disabled = isHorizontal;
  11536. };
  11537. this.eventBus._on('scrollmodechanged', scrollModeChanged);
  11538. this.eventBus._on('secondarytoolbarreset', (evt) => {
  11539. if (evt.source === this) {
  11540. scrollModeChanged({
  11541. mode: _ui_utils.ScrollMode.VERTICAL
  11542. });
  11543. }
  11544. });
  11545. }
  11546. #bindSpreadModeListener({ spreadNoneButton, spreadOddButton, spreadEvenButton }) {
  11547. const spreadModeChanged = ({ mode }) => {
  11548. (0, _ui_utils.toggleCheckedBtn)(spreadNoneButton, mode === _ui_utils.SpreadMode.NONE);
  11549. (0, _ui_utils.toggleCheckedBtn)(spreadOddButton, mode === _ui_utils.SpreadMode.ODD);
  11550. (0, _ui_utils.toggleCheckedBtn)(spreadEvenButton, mode === _ui_utils.SpreadMode.EVEN);
  11551. };
  11552. this.eventBus._on('spreadmodechanged', spreadModeChanged);
  11553. this.eventBus._on('secondarytoolbarreset', (evt) => {
  11554. if (evt.source === this) {
  11555. spreadModeChanged({
  11556. mode: _ui_utils.SpreadMode.NONE
  11557. });
  11558. }
  11559. });
  11560. }
  11561. open() {
  11562. if (this.opened) {
  11563. return;
  11564. }
  11565. this.opened = true;
  11566. (0, _ui_utils.toggleExpandedBtn)(this.toggleButton, true, this.toolbar);
  11567. }
  11568. close() {
  11569. if (!this.opened) {
  11570. return;
  11571. }
  11572. this.opened = false;
  11573. (0, _ui_utils.toggleExpandedBtn)(this.toggleButton, false, this.toolbar);
  11574. }
  11575. toggle() {
  11576. if (this.opened) {
  11577. this.close();
  11578. } else {
  11579. this.open();
  11580. }
  11581. }
  11582. }
  11583. exports.SecondaryToolbar = SecondaryToolbar;
  11584. /***/
  11585. },
  11586. /* 39 */
  11587. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  11588. Object.defineProperty(exports, '__esModule', {
  11589. value: true
  11590. });
  11591. exports.Toolbar = void 0;
  11592. var _ui_utils = __webpack_require__(3);
  11593. var _pdfjsLib = __webpack_require__(4);
  11594. const PAGE_NUMBER_LOADING_INDICATOR = 'visiblePageIsLoading';
  11595. class Toolbar {
  11596. #wasLocalized = false;
  11597. constructor(options, eventBus, l10n) {
  11598. this.toolbar = options.container;
  11599. this.eventBus = eventBus;
  11600. this.l10n = l10n;
  11601. this.buttons = [
  11602. {
  11603. element: options.previous,
  11604. eventName: 'previouspage'
  11605. },
  11606. {
  11607. element: options.next,
  11608. eventName: 'nextpage'
  11609. },
  11610. {
  11611. element: options.zoomIn,
  11612. eventName: 'zoomin'
  11613. },
  11614. {
  11615. element: options.zoomOut,
  11616. eventName: 'zoomout'
  11617. },
  11618. {
  11619. element: options.print,
  11620. eventName: 'print'
  11621. },
  11622. {
  11623. element: options.download,
  11624. eventName: 'download'
  11625. },
  11626. {
  11627. element: options.editorFreeTextButton,
  11628. eventName: 'switchannotationeditormode',
  11629. eventDetails: {
  11630. get mode() {
  11631. const { classList } = options.editorFreeTextButton;
  11632. return classList.contains('toggled') ? _pdfjsLib.AnnotationEditorType.NONE : _pdfjsLib.AnnotationEditorType.FREETEXT;
  11633. }
  11634. }
  11635. },
  11636. {
  11637. element: options.editorInkButton,
  11638. eventName: 'switchannotationeditormode',
  11639. eventDetails: {
  11640. get mode() {
  11641. const { classList } = options.editorInkButton;
  11642. return classList.contains('toggled') ? _pdfjsLib.AnnotationEditorType.NONE : _pdfjsLib.AnnotationEditorType.INK;
  11643. }
  11644. }
  11645. }
  11646. ];
  11647. this.buttons.push({
  11648. element: options.openFile,
  11649. eventName: 'openfile'
  11650. });
  11651. this.items = {
  11652. numPages: options.numPages,
  11653. pageNumber: options.pageNumber,
  11654. scaleSelect: options.scaleSelect,
  11655. customScaleOption: options.customScaleOption,
  11656. previous: options.previous,
  11657. next: options.next,
  11658. zoomIn: options.zoomIn,
  11659. zoomOut: options.zoomOut
  11660. };
  11661. this.#bindListeners(options);
  11662. this.reset();
  11663. }
  11664. setPageNumber(pageNumber, pageLabel) {
  11665. this.pageNumber = pageNumber;
  11666. this.pageLabel = pageLabel;
  11667. this.#updateUIState(false);
  11668. }
  11669. setPagesCount(pagesCount, hasPageLabels) {
  11670. this.pagesCount = pagesCount;
  11671. this.hasPageLabels = hasPageLabels;
  11672. this.#updateUIState(true);
  11673. }
  11674. setPageScale(pageScaleValue, pageScale) {
  11675. this.pageScaleValue = (pageScaleValue || pageScale).toString();
  11676. this.pageScale = pageScale;
  11677. this.#updateUIState(false);
  11678. }
  11679. reset() {
  11680. this.pageNumber = 0;
  11681. this.pageLabel = null;
  11682. this.hasPageLabels = false;
  11683. this.pagesCount = 0;
  11684. this.pageScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  11685. this.pageScale = _ui_utils.DEFAULT_SCALE;
  11686. this.#updateUIState(true);
  11687. this.updateLoadingIndicatorState();
  11688. this.eventBus.dispatch('toolbarreset', {
  11689. source: this
  11690. });
  11691. }
  11692. #bindListeners(options) {
  11693. const { pageNumber, scaleSelect } = this.items;
  11694. const self = this;
  11695. for (const { element, eventName, eventDetails } of this.buttons) {
  11696. element.addEventListener('click', (evt) => {
  11697. if (eventName !== null) {
  11698. this.eventBus.dispatch(eventName, {
  11699. source: this,
  11700. ...eventDetails
  11701. });
  11702. }
  11703. });
  11704. }
  11705. pageNumber.addEventListener('click', function () {
  11706. this.select();
  11707. });
  11708. pageNumber.addEventListener('change', function () {
  11709. self.eventBus.dispatch('pagenumberchanged', {
  11710. source: self,
  11711. value: this.value
  11712. });
  11713. });
  11714. scaleSelect.addEventListener('change', function () {
  11715. if (this.value === 'custom') {
  11716. return;
  11717. }
  11718. self.eventBus.dispatch('scalechanged', {
  11719. source: self,
  11720. value: this.value
  11721. });
  11722. });
  11723. scaleSelect.addEventListener('click', function (evt) {
  11724. const target = evt.target;
  11725. if (this.value === self.pageScaleValue && target.tagName.toUpperCase() === 'OPTION') {
  11726. this.blur();
  11727. }
  11728. });
  11729. scaleSelect.oncontextmenu = _ui_utils.noContextMenuHandler;
  11730. this.eventBus._on('localized', () => {
  11731. this.#wasLocalized = true;
  11732. this.#adjustScaleWidth();
  11733. this.#updateUIState(true);
  11734. });
  11735. this.#bindEditorToolsListener(options);
  11736. }
  11737. #bindEditorToolsListener({ editorFreeTextButton, editorFreeTextParamsToolbar, editorInkButton, editorInkParamsToolbar }) {
  11738. const editorModeChanged = ({ mode }) => {
  11739. (0, _ui_utils.toggleCheckedBtn)(editorFreeTextButton, mode === _pdfjsLib.AnnotationEditorType.FREETEXT, editorFreeTextParamsToolbar);
  11740. (0, _ui_utils.toggleCheckedBtn)(editorInkButton, mode === _pdfjsLib.AnnotationEditorType.INK, editorInkParamsToolbar);
  11741. const isDisable = mode === _pdfjsLib.AnnotationEditorType.DISABLE;
  11742. editorFreeTextButton.disabled = isDisable;
  11743. editorInkButton.disabled = isDisable;
  11744. };
  11745. this.eventBus._on('annotationeditormodechanged', editorModeChanged);
  11746. this.eventBus._on('toolbarreset', (evt) => {
  11747. if (evt.source === this) {
  11748. editorModeChanged({
  11749. mode: _pdfjsLib.AnnotationEditorType.DISABLE
  11750. });
  11751. }
  11752. });
  11753. }
  11754. #updateUIState(resetNumPages = false) {
  11755. if (!this.#wasLocalized) {
  11756. return;
  11757. }
  11758. const { pageNumber, pagesCount, pageScaleValue, pageScale, items } = this;
  11759. if (resetNumPages) {
  11760. if (this.hasPageLabels) {
  11761. items.pageNumber.type = 'text';
  11762. } else {
  11763. items.pageNumber.type = 'number';
  11764. this.l10n
  11765. .get('of_pages', {
  11766. pagesCount
  11767. })
  11768. .then((msg) => {
  11769. items.numPages.textContent = msg;
  11770. });
  11771. }
  11772. items.pageNumber.max = pagesCount;
  11773. }
  11774. if (this.hasPageLabels) {
  11775. items.pageNumber.value = this.pageLabel;
  11776. this.l10n
  11777. .get('page_of_pages', {
  11778. pageNumber,
  11779. pagesCount
  11780. })
  11781. .then((msg) => {
  11782. items.numPages.textContent = msg;
  11783. });
  11784. } else {
  11785. items.pageNumber.value = pageNumber;
  11786. }
  11787. items.previous.disabled = pageNumber <= 1;
  11788. items.next.disabled = pageNumber >= pagesCount;
  11789. items.zoomOut.disabled = pageScale <= _ui_utils.MIN_SCALE;
  11790. items.zoomIn.disabled = pageScale >= _ui_utils.MAX_SCALE;
  11791. this.l10n
  11792. .get('page_scale_percent', {
  11793. scale: Math.round(pageScale * 10000) / 100
  11794. })
  11795. .then((msg) => {
  11796. let predefinedValueFound = false;
  11797. for (const option of items.scaleSelect.options) {
  11798. if (option.value !== pageScaleValue) {
  11799. option.selected = false;
  11800. continue;
  11801. }
  11802. option.selected = true;
  11803. predefinedValueFound = true;
  11804. }
  11805. if (!predefinedValueFound) {
  11806. items.customScaleOption.textContent = msg;
  11807. items.customScaleOption.selected = true;
  11808. }
  11809. });
  11810. }
  11811. updateLoadingIndicatorState(loading = false) {
  11812. const { pageNumber } = this.items;
  11813. pageNumber.classList.toggle(PAGE_NUMBER_LOADING_INDICATOR, loading);
  11814. }
  11815. async #adjustScaleWidth() {
  11816. const { items, l10n } = this;
  11817. const predefinedValuesPromise = Promise.all([
  11818. l10n.get('page_scale_auto'),
  11819. l10n.get('page_scale_actual'),
  11820. l10n.get('page_scale_fit'),
  11821. l10n.get('page_scale_width')
  11822. ]);
  11823. await _ui_utils.animationStarted;
  11824. const style = getComputedStyle(items.scaleSelect);
  11825. const scaleSelectWidth = parseFloat(style.getPropertyValue('--scale-select-width'));
  11826. const canvas = document.createElement('canvas');
  11827. const ctx = canvas.getContext('2d', {
  11828. alpha: false
  11829. });
  11830. ctx.font = `${style.fontSize} ${style.fontFamily}`;
  11831. let maxWidth = 0;
  11832. for (const predefinedValue of await predefinedValuesPromise) {
  11833. const { width } = ctx.measureText(predefinedValue);
  11834. if (width > maxWidth) {
  11835. maxWidth = width;
  11836. }
  11837. }
  11838. maxWidth += 0.3 * scaleSelectWidth;
  11839. if (maxWidth > scaleSelectWidth) {
  11840. const container = items.scaleSelect.parentNode;
  11841. container.style.setProperty('--scale-select-width', `${maxWidth}px`);
  11842. }
  11843. canvas.width = 0;
  11844. canvas.height = 0;
  11845. }
  11846. }
  11847. exports.Toolbar = Toolbar;
  11848. /***/
  11849. },
  11850. /* 40 */
  11851. /***/ (__unused_webpack_module, exports) => {
  11852. Object.defineProperty(exports, '__esModule', {
  11853. value: true
  11854. });
  11855. exports.ViewHistory = void 0;
  11856. const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;
  11857. class ViewHistory {
  11858. constructor(fingerprint, cacheSize = DEFAULT_VIEW_HISTORY_CACHE_SIZE) {
  11859. this.fingerprint = fingerprint;
  11860. this.cacheSize = cacheSize;
  11861. this._initializedPromise = this._readFromStorage().then((databaseStr) => {
  11862. const database = JSON.parse(databaseStr || '{}');
  11863. let index = -1;
  11864. if (!Array.isArray(database.files)) {
  11865. database.files = [];
  11866. } else {
  11867. while (database.files.length >= this.cacheSize) {
  11868. database.files.shift();
  11869. }
  11870. for (let i = 0, ii = database.files.length; i < ii; i++) {
  11871. const branch = database.files[i];
  11872. if (branch.fingerprint === this.fingerprint) {
  11873. index = i;
  11874. break;
  11875. }
  11876. }
  11877. }
  11878. if (index === -1) {
  11879. index =
  11880. database.files.push({
  11881. fingerprint: this.fingerprint
  11882. }) - 1;
  11883. }
  11884. this.file = database.files[index];
  11885. this.database = database;
  11886. });
  11887. }
  11888. async _writeToStorage() {
  11889. const databaseStr = JSON.stringify(this.database);
  11890. localStorage.setItem('pdfjs.history', databaseStr);
  11891. }
  11892. async _readFromStorage() {
  11893. return localStorage.getItem('pdfjs.history');
  11894. }
  11895. async set(name, val) {
  11896. await this._initializedPromise;
  11897. this.file[name] = val;
  11898. return this._writeToStorage();
  11899. }
  11900. async setMultiple(properties) {
  11901. await this._initializedPromise;
  11902. for (const name in properties) {
  11903. this.file[name] = properties[name];
  11904. }
  11905. return this._writeToStorage();
  11906. }
  11907. async get(name, defaultValue) {
  11908. await this._initializedPromise;
  11909. const val = this.file[name];
  11910. return val !== undefined ? val : defaultValue;
  11911. }
  11912. async getMultiple(properties) {
  11913. await this._initializedPromise;
  11914. const values = Object.create(null);
  11915. for (const name in properties) {
  11916. const val = this.file[name];
  11917. values[name] = val !== undefined ? val : properties[name];
  11918. }
  11919. return values;
  11920. }
  11921. }
  11922. exports.ViewHistory = ViewHistory;
  11923. /***/
  11924. },
  11925. /* 41 */
  11926. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  11927. Object.defineProperty(exports, '__esModule', {
  11928. value: true
  11929. });
  11930. exports.BasePreferences = void 0;
  11931. var _app_options = __webpack_require__(5);
  11932. class BasePreferences {
  11933. #defaults = Object.freeze({
  11934. annotationEditorMode: 0,
  11935. annotationMode: 2,
  11936. cursorToolOnLoad: 0,
  11937. defaultZoomDelay: 400,
  11938. defaultZoomValue: '',
  11939. disablePageLabels: false,
  11940. enableFloatingToolbar: false,
  11941. enablePermissions: false,
  11942. enablePrintAutoRotate: true,
  11943. enableScripting: true,
  11944. externalLinkTarget: 0,
  11945. historyUpdateUrl: false,
  11946. ignoreDestinationZoom: false,
  11947. forcePageColors: false,
  11948. pageColorsBackground: 'Canvas',
  11949. pageColorsForeground: 'CanvasText',
  11950. pdfBugEnabled: false,
  11951. sidebarViewOnLoad: -1,
  11952. scrollModeOnLoad: -1,
  11953. spreadModeOnLoad: -1,
  11954. textLayerMode: 1,
  11955. useOnlyCssZoom: false,
  11956. viewerCssTheme: 0,
  11957. viewOnLoad: 0,
  11958. disableAutoFetch: false,
  11959. disableFontFace: false,
  11960. disableRange: false,
  11961. disableStream: false,
  11962. enableXfa: true
  11963. });
  11964. #prefs = Object.create(null);
  11965. #initializedPromise = null;
  11966. constructor() {
  11967. if (this.constructor === BasePreferences) {
  11968. throw new Error('Cannot initialize BasePreferences.');
  11969. }
  11970. this.#initializedPromise = this._readFromStorage(this.#defaults).then((prefs) => {
  11971. for (const name in this.#defaults) {
  11972. const prefValue = prefs?.[name];
  11973. if (typeof prefValue === typeof this.#defaults[name]) {
  11974. this.#prefs[name] = prefValue;
  11975. }
  11976. }
  11977. });
  11978. }
  11979. async _writeToStorage(prefObj) {
  11980. throw new Error('Not implemented: _writeToStorage');
  11981. }
  11982. async _readFromStorage(prefObj) {
  11983. throw new Error('Not implemented: _readFromStorage');
  11984. }
  11985. async reset() {
  11986. await this.#initializedPromise;
  11987. const prefs = this.#prefs;
  11988. this.#prefs = Object.create(null);
  11989. return this._writeToStorage(this.#defaults).catch((reason) => {
  11990. this.#prefs = prefs;
  11991. throw reason;
  11992. });
  11993. }
  11994. async set(name, value) {
  11995. await this.#initializedPromise;
  11996. const defaultValue = this.#defaults[name],
  11997. prefs = this.#prefs;
  11998. if (defaultValue === undefined) {
  11999. throw new Error(`Set preference: "${name}" is undefined.`);
  12000. } else if (value === undefined) {
  12001. throw new Error('Set preference: no value is specified.');
  12002. }
  12003. const valueType = typeof value,
  12004. defaultType = typeof defaultValue;
  12005. if (valueType !== defaultType) {
  12006. if (valueType === 'number' && defaultType === 'string') {
  12007. value = value.toString();
  12008. } else {
  12009. throw new Error(`Set preference: "${value}" is a ${valueType}, expected a ${defaultType}.`);
  12010. }
  12011. } else {
  12012. if (valueType === 'number' && !Number.isInteger(value)) {
  12013. throw new Error(`Set preference: "${value}" must be an integer.`);
  12014. }
  12015. }
  12016. this.#prefs[name] = value;
  12017. return this._writeToStorage(this.#prefs).catch((reason) => {
  12018. this.#prefs = prefs;
  12019. throw reason;
  12020. });
  12021. }
  12022. async get(name) {
  12023. await this.#initializedPromise;
  12024. const defaultValue = this.#defaults[name];
  12025. if (defaultValue === undefined) {
  12026. throw new Error(`Get preference: "${name}" is undefined.`);
  12027. }
  12028. return this.#prefs[name] ?? defaultValue;
  12029. }
  12030. async getAll() {
  12031. await this.#initializedPromise;
  12032. const obj = Object.create(null);
  12033. for (const name in this.#defaults) {
  12034. obj[name] = this.#prefs[name] ?? this.#defaults[name];
  12035. }
  12036. return obj;
  12037. }
  12038. }
  12039. exports.BasePreferences = BasePreferences;
  12040. /***/
  12041. },
  12042. /* 42 */
  12043. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  12044. Object.defineProperty(exports, '__esModule', {
  12045. value: true
  12046. });
  12047. exports.DownloadManager = void 0;
  12048. var _pdfjsLib = __webpack_require__(4);
  12049. function download(blobUrl, filename) {
  12050. const a = document.createElement('a');
  12051. if (!a.click) {
  12052. throw new Error('DownloadManager: "a.click()" is not supported.');
  12053. }
  12054. a.href = blobUrl;
  12055. a.target = '_parent';
  12056. if ('download' in a) {
  12057. a.download = filename;
  12058. }
  12059. (document.body || document.documentElement).append(a);
  12060. a.click();
  12061. a.remove();
  12062. }
  12063. class DownloadManager {
  12064. #openBlobUrls = new WeakMap();
  12065. downloadUrl(url, filename, _options) {
  12066. if (!(0, _pdfjsLib.createValidAbsoluteUrl)(url, 'http://example.com')) {
  12067. console.error(`downloadUrl - not a valid URL: ${url}`);
  12068. return;
  12069. }
  12070. download(url + '#pdfjs.action=download', filename);
  12071. }
  12072. downloadData(data, filename, contentType) {
  12073. const blobUrl = URL.createObjectURL(
  12074. new Blob([data], {
  12075. type: contentType
  12076. })
  12077. );
  12078. download(blobUrl, filename);
  12079. }
  12080. openOrDownloadData(element, data, filename) {
  12081. const isPdfData = (0, _pdfjsLib.isPdfFile)(filename);
  12082. const contentType = isPdfData ? 'application/pdf' : '';
  12083. if (isPdfData) {
  12084. let blobUrl = this.#openBlobUrls.get(element);
  12085. if (!blobUrl) {
  12086. blobUrl = URL.createObjectURL(
  12087. new Blob([data], {
  12088. type: contentType
  12089. })
  12090. );
  12091. this.#openBlobUrls.set(element, blobUrl);
  12092. }
  12093. let viewerUrl;
  12094. viewerUrl = '?file=' + encodeURIComponent(blobUrl + '#' + filename);
  12095. try {
  12096. window.open(viewerUrl);
  12097. return true;
  12098. } catch (ex) {
  12099. console.error(`openOrDownloadData: ${ex}`);
  12100. URL.revokeObjectURL(blobUrl);
  12101. this.#openBlobUrls.delete(element);
  12102. }
  12103. }
  12104. this.downloadData(data, filename, contentType);
  12105. return false;
  12106. }
  12107. download(blob, url, filename, _options) {
  12108. const blobUrl = URL.createObjectURL(blob);
  12109. download(blobUrl, filename);
  12110. }
  12111. }
  12112. exports.DownloadManager = DownloadManager;
  12113. /***/
  12114. },
  12115. /* 43 */
  12116. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  12117. Object.defineProperty(exports, '__esModule', {
  12118. value: true
  12119. });
  12120. exports.GenericL10n = void 0;
  12121. __webpack_require__(44);
  12122. var _l10n_utils = __webpack_require__(29);
  12123. const webL10n = document.webL10n;
  12124. class GenericL10n {
  12125. constructor(lang) {
  12126. this._lang = lang;
  12127. this._ready = new Promise((resolve, reject) => {
  12128. webL10n.setLanguage((0, _l10n_utils.fixupLangCode)(lang), () => {
  12129. resolve(webL10n);
  12130. });
  12131. });
  12132. }
  12133. async getLanguage() {
  12134. const l10n = await this._ready;
  12135. return l10n.getLanguage();
  12136. }
  12137. async getDirection() {
  12138. const l10n = await this._ready;
  12139. return l10n.getDirection();
  12140. }
  12141. async get(key, args = null, fallback = (0, _l10n_utils.getL10nFallback)(key, args)) {
  12142. const l10n = await this._ready;
  12143. return l10n.get(key, args, fallback);
  12144. }
  12145. async translate(element) {
  12146. const l10n = await this._ready;
  12147. return l10n.translate(element);
  12148. }
  12149. }
  12150. exports.GenericL10n = GenericL10n;
  12151. /***/
  12152. },
  12153. /* 44 */
  12154. /***/ () => {
  12155. document.webL10n = (function (window, document, undefined) {
  12156. var gL10nData = {};
  12157. var gTextData = '';
  12158. var gTextProp = 'textContent';
  12159. var gLanguage = '';
  12160. var gMacros = {};
  12161. var gReadyState = 'loading';
  12162. var gAsyncResourceLoading = true;
  12163. function getL10nResourceLinks() {
  12164. return document.querySelectorAll('link[type="application/l10n"]');
  12165. }
  12166. function getL10nDictionary() {
  12167. var script = document.querySelector('script[type="application/l10n"]');
  12168. return script ? JSON.parse(script.innerHTML) : null;
  12169. }
  12170. function getTranslatableChildren(element) {
  12171. return element ? element.querySelectorAll('*[data-l10n-id]') : [];
  12172. }
  12173. function getL10nAttributes(element) {
  12174. if (!element) return {};
  12175. var l10nId = element.getAttribute('data-l10n-id');
  12176. var l10nArgs = element.getAttribute('data-l10n-args');
  12177. var args = {};
  12178. if (l10nArgs) {
  12179. try {
  12180. args = JSON.parse(l10nArgs);
  12181. } catch (e) {
  12182. console.warn('could not parse arguments for #' + l10nId);
  12183. }
  12184. }
  12185. return {
  12186. id: l10nId,
  12187. args: args
  12188. };
  12189. }
  12190. function xhrLoadText(url, onSuccess, onFailure) {
  12191. onSuccess = onSuccess || function _onSuccess(data) {};
  12192. onFailure = onFailure || function _onFailure() {};
  12193. var xhr = new XMLHttpRequest();
  12194. xhr.open('GET', url, gAsyncResourceLoading);
  12195. if (xhr.overrideMimeType) {
  12196. xhr.overrideMimeType('text/plain; charset=utf-8');
  12197. }
  12198. xhr.onreadystatechange = function () {
  12199. if (xhr.readyState == 4) {
  12200. if (xhr.status == 200 || xhr.status === 0) {
  12201. onSuccess(xhr.responseText);
  12202. } else {
  12203. onFailure();
  12204. }
  12205. }
  12206. };
  12207. xhr.onerror = onFailure;
  12208. xhr.ontimeout = onFailure;
  12209. try {
  12210. xhr.send(null);
  12211. } catch (e) {
  12212. onFailure();
  12213. }
  12214. }
  12215. function parseResource(href, lang, successCallback, failureCallback) {
  12216. var baseURL = href.replace(/[^\/]*$/, '') || './';
  12217. function evalString(text) {
  12218. if (text.lastIndexOf('\\') < 0) return text;
  12219. return text
  12220. .replace(/\\\\/g, '\\')
  12221. .replace(/\\n/g, '\n')
  12222. .replace(/\\r/g, '\r')
  12223. .replace(/\\t/g, '\t')
  12224. .replace(/\\b/g, '\b')
  12225. .replace(/\\f/g, '\f')
  12226. .replace(/\\{/g, '{')
  12227. .replace(/\\}/g, '}')
  12228. .replace(/\\"/g, '"')
  12229. .replace(/\\'/g, "'");
  12230. }
  12231. function parseProperties(text, parsedPropertiesCallback) {
  12232. var dictionary = {};
  12233. var reBlank = /^\s*|\s*$/;
  12234. var reComment = /^\s*#|^\s*$/;
  12235. var reSection = /^\s*\[(.*)\]\s*$/;
  12236. var reImport = /^\s*@import\s+url\((.*)\)\s*$/i;
  12237. var reSplit = /^([^=\s]*)\s*=\s*(.+)$/;
  12238. function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) {
  12239. var entries = rawText.replace(reBlank, '').split(/[\r\n]+/);
  12240. var currentLang = '*';
  12241. var genericLang = lang.split('-', 1)[0];
  12242. var skipLang = false;
  12243. var match = '';
  12244. function nextEntry() {
  12245. while (true) {
  12246. if (!entries.length) {
  12247. parsedRawLinesCallback();
  12248. return;
  12249. }
  12250. var line = entries.shift();
  12251. if (reComment.test(line)) continue;
  12252. if (extendedSyntax) {
  12253. match = reSection.exec(line);
  12254. if (match) {
  12255. currentLang = match[1].toLowerCase();
  12256. skipLang = currentLang !== '*' && currentLang !== lang && currentLang !== genericLang;
  12257. continue;
  12258. } else if (skipLang) {
  12259. continue;
  12260. }
  12261. match = reImport.exec(line);
  12262. if (match) {
  12263. loadImport(baseURL + match[1], nextEntry);
  12264. return;
  12265. }
  12266. }
  12267. var tmp = line.match(reSplit);
  12268. if (tmp && tmp.length == 3) {
  12269. dictionary[tmp[1]] = evalString(tmp[2]);
  12270. }
  12271. }
  12272. }
  12273. nextEntry();
  12274. }
  12275. function loadImport(url, callback) {
  12276. xhrLoadText(
  12277. url,
  12278. function (content) {
  12279. parseRawLines(content, false, callback);
  12280. },
  12281. function () {
  12282. console.warn(url + ' not found.');
  12283. callback();
  12284. }
  12285. );
  12286. }
  12287. parseRawLines(text, true, function () {
  12288. parsedPropertiesCallback(dictionary);
  12289. });
  12290. }
  12291. xhrLoadText(
  12292. href,
  12293. function (response) {
  12294. gTextData += response;
  12295. parseProperties(response, function (data) {
  12296. for (var key in data) {
  12297. var id,
  12298. prop,
  12299. index = key.lastIndexOf('.');
  12300. if (index > 0) {
  12301. id = key.substring(0, index);
  12302. prop = key.substring(index + 1);
  12303. } else {
  12304. id = key;
  12305. prop = gTextProp;
  12306. }
  12307. if (!gL10nData[id]) {
  12308. gL10nData[id] = {};
  12309. }
  12310. gL10nData[id][prop] = data[key];
  12311. }
  12312. if (successCallback) {
  12313. successCallback();
  12314. }
  12315. });
  12316. },
  12317. failureCallback
  12318. );
  12319. }
  12320. function loadLocale(lang, callback) {
  12321. if (lang) {
  12322. lang = lang.toLowerCase();
  12323. }
  12324. callback = callback || function _callback() {};
  12325. clear();
  12326. gLanguage = lang;
  12327. var langLinks = getL10nResourceLinks();
  12328. var langCount = langLinks.length;
  12329. if (langCount === 0) {
  12330. var dict = getL10nDictionary();
  12331. if (dict && dict.locales && dict.default_locale) {
  12332. console.log('using the embedded JSON directory, early way out');
  12333. gL10nData = dict.locales[lang];
  12334. if (!gL10nData) {
  12335. var defaultLocale = dict.default_locale.toLowerCase();
  12336. for (var anyCaseLang in dict.locales) {
  12337. anyCaseLang = anyCaseLang.toLowerCase();
  12338. if (anyCaseLang === lang) {
  12339. gL10nData = dict.locales[lang];
  12340. break;
  12341. } else if (anyCaseLang === defaultLocale) {
  12342. gL10nData = dict.locales[defaultLocale];
  12343. }
  12344. }
  12345. }
  12346. callback();
  12347. } else {
  12348. console.log('no resource to load, early way out');
  12349. }
  12350. gReadyState = 'complete';
  12351. return;
  12352. }
  12353. var onResourceLoaded = null;
  12354. var gResourceCount = 0;
  12355. onResourceLoaded = function () {
  12356. gResourceCount++;
  12357. if (gResourceCount >= langCount) {
  12358. callback();
  12359. gReadyState = 'complete';
  12360. }
  12361. };
  12362. function L10nResourceLink(link) {
  12363. var href = link.href;
  12364. this.load = function (lang, callback) {
  12365. parseResource(href, lang, callback, function () {
  12366. console.warn(href + ' not found.');
  12367. console.warn('"' + lang + '" resource not found');
  12368. gLanguage = '';
  12369. callback();
  12370. });
  12371. };
  12372. }
  12373. for (var i = 0; i < langCount; i++) {
  12374. var resource = new L10nResourceLink(langLinks[i]);
  12375. resource.load(lang, onResourceLoaded);
  12376. }
  12377. }
  12378. function clear() {
  12379. gL10nData = {};
  12380. gTextData = '';
  12381. gLanguage = '';
  12382. }
  12383. function getPluralRules(lang) {
  12384. var locales2rules = {
  12385. af: 3,
  12386. ak: 4,
  12387. am: 4,
  12388. ar: 1,
  12389. asa: 3,
  12390. az: 0,
  12391. be: 11,
  12392. bem: 3,
  12393. bez: 3,
  12394. bg: 3,
  12395. bh: 4,
  12396. bm: 0,
  12397. bn: 3,
  12398. bo: 0,
  12399. br: 20,
  12400. brx: 3,
  12401. bs: 11,
  12402. ca: 3,
  12403. cgg: 3,
  12404. chr: 3,
  12405. cs: 12,
  12406. cy: 17,
  12407. da: 3,
  12408. de: 3,
  12409. dv: 3,
  12410. dz: 0,
  12411. ee: 3,
  12412. el: 3,
  12413. en: 3,
  12414. eo: 3,
  12415. es: 3,
  12416. et: 3,
  12417. eu: 3,
  12418. fa: 0,
  12419. ff: 5,
  12420. fi: 3,
  12421. fil: 4,
  12422. fo: 3,
  12423. fr: 5,
  12424. fur: 3,
  12425. fy: 3,
  12426. ga: 8,
  12427. gd: 24,
  12428. gl: 3,
  12429. gsw: 3,
  12430. gu: 3,
  12431. guw: 4,
  12432. gv: 23,
  12433. ha: 3,
  12434. haw: 3,
  12435. he: 2,
  12436. hi: 4,
  12437. hr: 11,
  12438. hu: 0,
  12439. id: 0,
  12440. ig: 0,
  12441. ii: 0,
  12442. is: 3,
  12443. it: 3,
  12444. iu: 7,
  12445. ja: 0,
  12446. jmc: 3,
  12447. jv: 0,
  12448. ka: 0,
  12449. kab: 5,
  12450. kaj: 3,
  12451. kcg: 3,
  12452. kde: 0,
  12453. kea: 0,
  12454. kk: 3,
  12455. kl: 3,
  12456. km: 0,
  12457. kn: 0,
  12458. ko: 0,
  12459. ksb: 3,
  12460. ksh: 21,
  12461. ku: 3,
  12462. kw: 7,
  12463. lag: 18,
  12464. lb: 3,
  12465. lg: 3,
  12466. ln: 4,
  12467. lo: 0,
  12468. lt: 10,
  12469. lv: 6,
  12470. mas: 3,
  12471. mg: 4,
  12472. mk: 16,
  12473. ml: 3,
  12474. mn: 3,
  12475. mo: 9,
  12476. mr: 3,
  12477. ms: 0,
  12478. mt: 15,
  12479. my: 0,
  12480. nah: 3,
  12481. naq: 7,
  12482. nb: 3,
  12483. nd: 3,
  12484. ne: 3,
  12485. nl: 3,
  12486. nn: 3,
  12487. no: 3,
  12488. nr: 3,
  12489. nso: 4,
  12490. ny: 3,
  12491. nyn: 3,
  12492. om: 3,
  12493. or: 3,
  12494. pa: 3,
  12495. pap: 3,
  12496. pl: 13,
  12497. ps: 3,
  12498. pt: 3,
  12499. rm: 3,
  12500. ro: 9,
  12501. rof: 3,
  12502. ru: 11,
  12503. rwk: 3,
  12504. sah: 0,
  12505. saq: 3,
  12506. se: 7,
  12507. seh: 3,
  12508. ses: 0,
  12509. sg: 0,
  12510. sh: 11,
  12511. shi: 19,
  12512. sk: 12,
  12513. sl: 14,
  12514. sma: 7,
  12515. smi: 7,
  12516. smj: 7,
  12517. smn: 7,
  12518. sms: 7,
  12519. sn: 3,
  12520. so: 3,
  12521. sq: 3,
  12522. sr: 11,
  12523. ss: 3,
  12524. ssy: 3,
  12525. st: 3,
  12526. sv: 3,
  12527. sw: 3,
  12528. syr: 3,
  12529. ta: 3,
  12530. te: 3,
  12531. teo: 3,
  12532. th: 0,
  12533. ti: 4,
  12534. tig: 3,
  12535. tk: 3,
  12536. tl: 4,
  12537. tn: 3,
  12538. to: 0,
  12539. tr: 0,
  12540. ts: 3,
  12541. tzm: 22,
  12542. uk: 11,
  12543. ur: 3,
  12544. ve: 3,
  12545. vi: 0,
  12546. vun: 3,
  12547. wa: 4,
  12548. wae: 3,
  12549. wo: 0,
  12550. xh: 3,
  12551. xog: 3,
  12552. yo: 0,
  12553. zh: 0,
  12554. zu: 3
  12555. };
  12556. function isIn(n, list) {
  12557. return list.indexOf(n) !== -1;
  12558. }
  12559. function isBetween(n, start, end) {
  12560. return start <= n && n <= end;
  12561. }
  12562. var pluralRules = {
  12563. 0: function (n) {
  12564. return 'other';
  12565. },
  12566. 1: function (n) {
  12567. if (isBetween(n % 100, 3, 10)) return 'few';
  12568. if (n === 0) return 'zero';
  12569. if (isBetween(n % 100, 11, 99)) return 'many';
  12570. if (n == 2) return 'two';
  12571. if (n == 1) return 'one';
  12572. return 'other';
  12573. },
  12574. 2: function (n) {
  12575. if (n !== 0 && n % 10 === 0) return 'many';
  12576. if (n == 2) return 'two';
  12577. if (n == 1) return 'one';
  12578. return 'other';
  12579. },
  12580. 3: function (n) {
  12581. if (n == 1) return 'one';
  12582. return 'other';
  12583. },
  12584. 4: function (n) {
  12585. if (isBetween(n, 0, 1)) return 'one';
  12586. return 'other';
  12587. },
  12588. 5: function (n) {
  12589. if (isBetween(n, 0, 2) && n != 2) return 'one';
  12590. return 'other';
  12591. },
  12592. 6: function (n) {
  12593. if (n === 0) return 'zero';
  12594. if (n % 10 == 1 && n % 100 != 11) return 'one';
  12595. return 'other';
  12596. },
  12597. 7: function (n) {
  12598. if (n == 2) return 'two';
  12599. if (n == 1) return 'one';
  12600. return 'other';
  12601. },
  12602. 8: function (n) {
  12603. if (isBetween(n, 3, 6)) return 'few';
  12604. if (isBetween(n, 7, 10)) return 'many';
  12605. if (n == 2) return 'two';
  12606. if (n == 1) return 'one';
  12607. return 'other';
  12608. },
  12609. 9: function (n) {
  12610. if (n === 0 || (n != 1 && isBetween(n % 100, 1, 19))) return 'few';
  12611. if (n == 1) return 'one';
  12612. return 'other';
  12613. },
  12614. 10: function (n) {
  12615. if (isBetween(n % 10, 2, 9) && !isBetween(n % 100, 11, 19)) return 'few';
  12616. if (n % 10 == 1 && !isBetween(n % 100, 11, 19)) return 'one';
  12617. return 'other';
  12618. },
  12619. 11: function (n) {
  12620. if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few';
  12621. if (n % 10 === 0 || isBetween(n % 10, 5, 9) || isBetween(n % 100, 11, 14)) return 'many';
  12622. if (n % 10 == 1 && n % 100 != 11) return 'one';
  12623. return 'other';
  12624. },
  12625. 12: function (n) {
  12626. if (isBetween(n, 2, 4)) return 'few';
  12627. if (n == 1) return 'one';
  12628. return 'other';
  12629. },
  12630. 13: function (n) {
  12631. if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few';
  12632. if ((n != 1 && isBetween(n % 10, 0, 1)) || isBetween(n % 10, 5, 9) || isBetween(n % 100, 12, 14)) return 'many';
  12633. if (n == 1) return 'one';
  12634. return 'other';
  12635. },
  12636. 14: function (n) {
  12637. if (isBetween(n % 100, 3, 4)) return 'few';
  12638. if (n % 100 == 2) return 'two';
  12639. if (n % 100 == 1) return 'one';
  12640. return 'other';
  12641. },
  12642. 15: function (n) {
  12643. if (n === 0 || isBetween(n % 100, 2, 10)) return 'few';
  12644. if (isBetween(n % 100, 11, 19)) return 'many';
  12645. if (n == 1) return 'one';
  12646. return 'other';
  12647. },
  12648. 16: function (n) {
  12649. if (n % 10 == 1 && n != 11) return 'one';
  12650. return 'other';
  12651. },
  12652. 17: function (n) {
  12653. if (n == 3) return 'few';
  12654. if (n === 0) return 'zero';
  12655. if (n == 6) return 'many';
  12656. if (n == 2) return 'two';
  12657. if (n == 1) return 'one';
  12658. return 'other';
  12659. },
  12660. 18: function (n) {
  12661. if (n === 0) return 'zero';
  12662. if (isBetween(n, 0, 2) && n !== 0 && n != 2) return 'one';
  12663. return 'other';
  12664. },
  12665. 19: function (n) {
  12666. if (isBetween(n, 2, 10)) return 'few';
  12667. if (isBetween(n, 0, 1)) return 'one';
  12668. return 'other';
  12669. },
  12670. 20: function (n) {
  12671. if (
  12672. (isBetween(n % 10, 3, 4) || n % 10 == 9) &&
  12673. !(isBetween(n % 100, 10, 19) || isBetween(n % 100, 70, 79) || isBetween(n % 100, 90, 99))
  12674. )
  12675. return 'few';
  12676. if (n % 1000000 === 0 && n !== 0) return 'many';
  12677. if (n % 10 == 2 && !isIn(n % 100, [12, 72, 92])) return 'two';
  12678. if (n % 10 == 1 && !isIn(n % 100, [11, 71, 91])) return 'one';
  12679. return 'other';
  12680. },
  12681. 21: function (n) {
  12682. if (n === 0) return 'zero';
  12683. if (n == 1) return 'one';
  12684. return 'other';
  12685. },
  12686. 22: function (n) {
  12687. if (isBetween(n, 0, 1) || isBetween(n, 11, 99)) return 'one';
  12688. return 'other';
  12689. },
  12690. 23: function (n) {
  12691. if (isBetween(n % 10, 1, 2) || n % 20 === 0) return 'one';
  12692. return 'other';
  12693. },
  12694. 24: function (n) {
  12695. if (isBetween(n, 3, 10) || isBetween(n, 13, 19)) return 'few';
  12696. if (isIn(n, [2, 12])) return 'two';
  12697. if (isIn(n, [1, 11])) return 'one';
  12698. return 'other';
  12699. }
  12700. };
  12701. var index = locales2rules[lang.replace(/-.*$/, '')];
  12702. if (!(index in pluralRules)) {
  12703. console.warn('plural form unknown for [' + lang + ']');
  12704. return function () {
  12705. return 'other';
  12706. };
  12707. }
  12708. return pluralRules[index];
  12709. }
  12710. gMacros.plural = function (str, param, key, prop) {
  12711. var n = parseFloat(param);
  12712. if (isNaN(n)) return str;
  12713. if (prop != gTextProp) return str;
  12714. if (!gMacros._pluralRules) {
  12715. gMacros._pluralRules = getPluralRules(gLanguage);
  12716. }
  12717. var index = '[' + gMacros._pluralRules(n) + ']';
  12718. if (n === 0 && key + '[zero]' in gL10nData) {
  12719. str = gL10nData[key + '[zero]'][prop];
  12720. } else if (n == 1 && key + '[one]' in gL10nData) {
  12721. str = gL10nData[key + '[one]'][prop];
  12722. } else if (n == 2 && key + '[two]' in gL10nData) {
  12723. str = gL10nData[key + '[two]'][prop];
  12724. } else if (key + index in gL10nData) {
  12725. str = gL10nData[key + index][prop];
  12726. } else if (key + '[other]' in gL10nData) {
  12727. str = gL10nData[key + '[other]'][prop];
  12728. }
  12729. return str;
  12730. };
  12731. function getL10nData(key, args, fallback) {
  12732. var data = gL10nData[key];
  12733. if (!data) {
  12734. console.warn('#' + key + ' is undefined.');
  12735. if (!fallback) {
  12736. return null;
  12737. }
  12738. data = fallback;
  12739. }
  12740. var rv = {};
  12741. for (var prop in data) {
  12742. var str = data[prop];
  12743. str = substIndexes(str, args, key, prop);
  12744. str = substArguments(str, args, key);
  12745. rv[prop] = str;
  12746. }
  12747. return rv;
  12748. }
  12749. function substIndexes(str, args, key, prop) {
  12750. var reIndex = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/;
  12751. var reMatch = reIndex.exec(str);
  12752. if (!reMatch || !reMatch.length) return str;
  12753. var macroName = reMatch[1];
  12754. var paramName = reMatch[2];
  12755. var param;
  12756. if (args && paramName in args) {
  12757. param = args[paramName];
  12758. } else if (paramName in gL10nData) {
  12759. param = gL10nData[paramName];
  12760. }
  12761. if (macroName in gMacros) {
  12762. var macro = gMacros[macroName];
  12763. str = macro(str, param, key, prop);
  12764. }
  12765. return str;
  12766. }
  12767. function substArguments(str, args, key) {
  12768. var reArgs = /\{\{\s*(.+?)\s*\}\}/g;
  12769. return str.replace(reArgs, function (matched_text, arg) {
  12770. if (args && arg in args) {
  12771. return args[arg];
  12772. }
  12773. if (arg in gL10nData) {
  12774. return gL10nData[arg];
  12775. }
  12776. console.log('argument {{' + arg + '}} for #' + key + ' is undefined.');
  12777. return matched_text;
  12778. });
  12779. }
  12780. function translateElement(element) {
  12781. var l10n = getL10nAttributes(element);
  12782. if (!l10n.id) return;
  12783. var data = getL10nData(l10n.id, l10n.args);
  12784. if (!data) {
  12785. console.warn('#' + l10n.id + ' is undefined.');
  12786. return;
  12787. }
  12788. if (data[gTextProp]) {
  12789. if (getChildElementCount(element) === 0) {
  12790. element[gTextProp] = data[gTextProp];
  12791. } else {
  12792. var children = element.childNodes;
  12793. var found = false;
  12794. for (var i = 0, l = children.length; i < l; i++) {
  12795. if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {
  12796. if (found) {
  12797. children[i].nodeValue = '';
  12798. } else {
  12799. children[i].nodeValue = data[gTextProp];
  12800. found = true;
  12801. }
  12802. }
  12803. }
  12804. if (!found) {
  12805. var textNode = document.createTextNode(data[gTextProp]);
  12806. element.prepend(textNode);
  12807. }
  12808. }
  12809. delete data[gTextProp];
  12810. }
  12811. for (var k in data) {
  12812. element[k] = data[k];
  12813. }
  12814. }
  12815. function getChildElementCount(element) {
  12816. if (element.children) {
  12817. return element.children.length;
  12818. }
  12819. if (typeof element.childElementCount !== 'undefined') {
  12820. return element.childElementCount;
  12821. }
  12822. var count = 0;
  12823. for (var i = 0; i < element.childNodes.length; i++) {
  12824. count += element.nodeType === 1 ? 1 : 0;
  12825. }
  12826. return count;
  12827. }
  12828. function translateFragment(element) {
  12829. element = element || document.documentElement;
  12830. var children = getTranslatableChildren(element);
  12831. var elementCount = children.length;
  12832. for (var i = 0; i < elementCount; i++) {
  12833. translateElement(children[i]);
  12834. }
  12835. translateElement(element);
  12836. }
  12837. return {
  12838. get: function (key, args, fallbackString) {
  12839. var index = key.lastIndexOf('.');
  12840. var prop = gTextProp;
  12841. if (index > 0) {
  12842. prop = key.substring(index + 1);
  12843. key = key.substring(0, index);
  12844. }
  12845. var fallback;
  12846. if (fallbackString) {
  12847. fallback = {};
  12848. fallback[prop] = fallbackString;
  12849. }
  12850. var data = getL10nData(key, args, fallback);
  12851. if (data && prop in data) {
  12852. return data[prop];
  12853. }
  12854. return '{{' + key + '}}';
  12855. },
  12856. getData: function () {
  12857. return gL10nData;
  12858. },
  12859. getText: function () {
  12860. return gTextData;
  12861. },
  12862. getLanguage: function () {
  12863. return gLanguage;
  12864. },
  12865. setLanguage: function (lang, callback) {
  12866. loadLocale(lang, function () {
  12867. if (callback) callback();
  12868. });
  12869. },
  12870. getDirection: function () {
  12871. var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
  12872. var shortCode = gLanguage.split('-', 1)[0];
  12873. return rtlList.indexOf(shortCode) >= 0 ? 'rtl' : 'ltr';
  12874. },
  12875. translate: translateFragment,
  12876. getReadyState: function () {
  12877. return gReadyState;
  12878. },
  12879. ready: function (callback) {
  12880. if (!callback) {
  12881. return;
  12882. } else if (gReadyState == 'complete' || gReadyState == 'interactive') {
  12883. window.setTimeout(function () {
  12884. callback();
  12885. });
  12886. } else if (document.addEventListener) {
  12887. document.addEventListener('localized', function once() {
  12888. document.removeEventListener('localized', once);
  12889. callback();
  12890. });
  12891. }
  12892. }
  12893. };
  12894. })(window, document);
  12895. /***/
  12896. },
  12897. /* 45 */
  12898. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  12899. Object.defineProperty(exports, '__esModule', {
  12900. value: true
  12901. });
  12902. exports.GenericScripting = void 0;
  12903. exports.docPropertiesLookup = docPropertiesLookup;
  12904. var _pdfjsLib = __webpack_require__(4);
  12905. async function docPropertiesLookup(pdfDocument) {
  12906. const url = '',
  12907. baseUrl = url.split('#')[0];
  12908. let { info, metadata, contentDispositionFilename, contentLength } = await pdfDocument.getMetadata();
  12909. if (!contentLength) {
  12910. const { length } = await pdfDocument.getDownloadInfo();
  12911. contentLength = length;
  12912. }
  12913. return {
  12914. ...info,
  12915. baseURL: baseUrl,
  12916. filesize: contentLength,
  12917. filename: contentDispositionFilename || (0, _pdfjsLib.getPdfFilenameFromUrl)(url),
  12918. metadata: metadata?.getRaw(),
  12919. authors: metadata?.get('dc:creator'),
  12920. numPages: pdfDocument.numPages,
  12921. URL: url
  12922. };
  12923. }
  12924. class GenericScripting {
  12925. constructor(sandboxBundleSrc) {
  12926. this._ready = (0, _pdfjsLib.loadScript)(sandboxBundleSrc, true).then(() => {
  12927. return window.pdfjsSandbox.QuickJSSandbox();
  12928. });
  12929. }
  12930. async createSandbox(data) {
  12931. const sandbox = await this._ready;
  12932. sandbox.create(data);
  12933. }
  12934. async dispatchEventInSandbox(event) {
  12935. const sandbox = await this._ready;
  12936. setTimeout(() => sandbox.dispatchEvent(event), 0);
  12937. }
  12938. async destroySandbox() {
  12939. const sandbox = await this._ready;
  12940. sandbox.nukeSandbox();
  12941. }
  12942. }
  12943. exports.GenericScripting = GenericScripting;
  12944. /***/
  12945. },
  12946. /* 46 */
  12947. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  12948. Object.defineProperty(exports, '__esModule', {
  12949. value: true
  12950. });
  12951. exports.PDFPrintService = void 0;
  12952. var _pdfjsLib = __webpack_require__(4);
  12953. var _app = __webpack_require__(2);
  12954. var _print_utils = __webpack_require__(47);
  12955. let activeService = null;
  12956. let dialog = null;
  12957. let overlayManager = null;
  12958. function renderPage(
  12959. activeServiceOnEntry,
  12960. pdfDocument,
  12961. pageNumber,
  12962. size,
  12963. printResolution,
  12964. optionalContentConfigPromise,
  12965. printAnnotationStoragePromise
  12966. ) {
  12967. const scratchCanvas = activeService.scratchCanvas;
  12968. const PRINT_UNITS = printResolution / _pdfjsLib.PixelsPerInch.PDF;
  12969. scratchCanvas.width = Math.floor(size.width * PRINT_UNITS);
  12970. scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);
  12971. const ctx = scratchCanvas.getContext('2d');
  12972. ctx.save();
  12973. ctx.fillStyle = 'rgb(255, 255, 255)';
  12974. ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
  12975. ctx.restore();
  12976. return Promise.all([pdfDocument.getPage(pageNumber), printAnnotationStoragePromise]).then(function ([pdfPage, printAnnotationStorage]) {
  12977. const renderContext = {
  12978. canvasContext: ctx,
  12979. transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0],
  12980. viewport: pdfPage.getViewport({
  12981. scale: 1,
  12982. rotation: size.rotation
  12983. }),
  12984. intent: 'print',
  12985. annotationMode: _pdfjsLib.AnnotationMode.ENABLE_STORAGE,
  12986. optionalContentConfigPromise,
  12987. printAnnotationStorage
  12988. };
  12989. return pdfPage.render(renderContext).promise;
  12990. });
  12991. }
  12992. class PDFPrintService {
  12993. constructor(
  12994. pdfDocument,
  12995. pagesOverview,
  12996. printContainer,
  12997. printResolution,
  12998. optionalContentConfigPromise = null,
  12999. printAnnotationStoragePromise = null,
  13000. l10n
  13001. ) {
  13002. this.pdfDocument = pdfDocument;
  13003. this.pagesOverview = pagesOverview;
  13004. this.printContainer = printContainer;
  13005. this._printResolution = printResolution || 150;
  13006. this._optionalContentConfigPromise = optionalContentConfigPromise || pdfDocument.getOptionalContentConfig();
  13007. this._printAnnotationStoragePromise = printAnnotationStoragePromise || Promise.resolve();
  13008. this.l10n = l10n;
  13009. this.currentPage = -1;
  13010. this.scratchCanvas = document.createElement('canvas');
  13011. }
  13012. layout() {
  13013. this.throwIfInactive();
  13014. const body = document.querySelector('body');
  13015. body.setAttribute('data-pdfjsprinting', true);
  13016. const { width, height } = this.pagesOverview[0];
  13017. const hasEqualPageSizes = this.pagesOverview.every((size) => size.width === width && size.height === height);
  13018. if (!hasEqualPageSizes) {
  13019. console.warn('Not all pages have the same size. The printed result may be incorrect!');
  13020. }
  13021. this.pageStyleSheet = document.createElement('style');
  13022. this.pageStyleSheet.textContent = `@page { size: ${width}pt ${height}pt;}`;
  13023. body.append(this.pageStyleSheet);
  13024. }
  13025. destroy() {
  13026. if (activeService !== this) {
  13027. return;
  13028. }
  13029. this.printContainer.textContent = '';
  13030. const body = document.querySelector('body');
  13031. body.removeAttribute('data-pdfjsprinting');
  13032. if (this.pageStyleSheet) {
  13033. this.pageStyleSheet.remove();
  13034. this.pageStyleSheet = null;
  13035. }
  13036. this.scratchCanvas.width = this.scratchCanvas.height = 0;
  13037. this.scratchCanvas = null;
  13038. activeService = null;
  13039. ensureOverlay().then(function () {
  13040. if (overlayManager.active === dialog) {
  13041. overlayManager.close(dialog);
  13042. }
  13043. });
  13044. }
  13045. renderPages() {
  13046. if (this.pdfDocument.isPureXfa) {
  13047. (0, _print_utils.getXfaHtmlForPrinting)(this.printContainer, this.pdfDocument);
  13048. return Promise.resolve();
  13049. }
  13050. const pageCount = this.pagesOverview.length;
  13051. const renderNextPage = (resolve, reject) => {
  13052. this.throwIfInactive();
  13053. if (++this.currentPage >= pageCount) {
  13054. renderProgress(pageCount, pageCount, this.l10n);
  13055. resolve();
  13056. return;
  13057. }
  13058. const index = this.currentPage;
  13059. renderProgress(index, pageCount, this.l10n);
  13060. renderPage(
  13061. this,
  13062. this.pdfDocument,
  13063. index + 1,
  13064. this.pagesOverview[index],
  13065. this._printResolution,
  13066. this._optionalContentConfigPromise,
  13067. this._printAnnotationStoragePromise
  13068. )
  13069. .then(this.useRenderedPage.bind(this))
  13070. .then(function () {
  13071. renderNextPage(resolve, reject);
  13072. }, reject);
  13073. };
  13074. return new Promise(renderNextPage);
  13075. }
  13076. useRenderedPage() {
  13077. this.throwIfInactive();
  13078. const img = document.createElement('img');
  13079. const scratchCanvas = this.scratchCanvas;
  13080. if ('toBlob' in scratchCanvas) {
  13081. scratchCanvas.toBlob(function (blob) {
  13082. img.src = URL.createObjectURL(blob);
  13083. });
  13084. } else {
  13085. img.src = scratchCanvas.toDataURL();
  13086. }
  13087. const wrapper = document.createElement('div');
  13088. wrapper.className = 'printedPage';
  13089. wrapper.append(img);
  13090. this.printContainer.append(wrapper);
  13091. return new Promise(function (resolve, reject) {
  13092. img.onload = resolve;
  13093. img.onerror = reject;
  13094. });
  13095. }
  13096. performPrint() {
  13097. this.throwIfInactive();
  13098. return new Promise((resolve) => {
  13099. setTimeout(() => {
  13100. if (!this.active) {
  13101. resolve();
  13102. return;
  13103. }
  13104. print.call(window);
  13105. setTimeout(resolve, 20);
  13106. }, 0);
  13107. });
  13108. }
  13109. get active() {
  13110. return this === activeService;
  13111. }
  13112. throwIfInactive() {
  13113. if (!this.active) {
  13114. throw new Error('This print request was cancelled or completed.');
  13115. }
  13116. }
  13117. }
  13118. exports.PDFPrintService = PDFPrintService;
  13119. const print = window.print;
  13120. window.print = function () {
  13121. if (activeService) {
  13122. console.warn('Ignored window.print() because of a pending print job.');
  13123. return;
  13124. }
  13125. ensureOverlay().then(function () {
  13126. if (activeService) {
  13127. overlayManager.open(dialog);
  13128. }
  13129. });
  13130. try {
  13131. dispatchEvent('beforeprint');
  13132. } finally {
  13133. if (!activeService) {
  13134. console.error('Expected print service to be initialized.');
  13135. ensureOverlay().then(function () {
  13136. if (overlayManager.active === dialog) {
  13137. overlayManager.close(dialog);
  13138. }
  13139. });
  13140. return;
  13141. }
  13142. const activeServiceOnEntry = activeService;
  13143. activeService
  13144. .renderPages()
  13145. .then(function () {
  13146. return activeServiceOnEntry.performPrint();
  13147. })
  13148. .catch(function () {})
  13149. .then(function () {
  13150. if (activeServiceOnEntry.active) {
  13151. abort();
  13152. }
  13153. });
  13154. }
  13155. };
  13156. function dispatchEvent(eventType) {
  13157. const event = new CustomEvent(eventType, {
  13158. bubbles: false,
  13159. cancelable: false,
  13160. detail: 'custom'
  13161. });
  13162. window.dispatchEvent(event);
  13163. }
  13164. function abort() {
  13165. if (activeService) {
  13166. activeService.destroy();
  13167. dispatchEvent('afterprint');
  13168. }
  13169. }
  13170. function renderProgress(index, total, l10n) {
  13171. dialog ||= document.getElementById('printServiceDialog');
  13172. const progress = Math.round((100 * index) / total);
  13173. const progressBar = dialog.querySelector('progress');
  13174. const progressPerc = dialog.querySelector('.relative-progress');
  13175. progressBar.value = progress;
  13176. l10n
  13177. .get('print_progress_percent', {
  13178. progress
  13179. })
  13180. .then((msg) => {
  13181. progressPerc.textContent = msg;
  13182. });
  13183. }
  13184. window.addEventListener(
  13185. 'keydown',
  13186. function (event) {
  13187. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  13188. window.print();
  13189. event.preventDefault();
  13190. event.stopImmediatePropagation();
  13191. }
  13192. },
  13193. true
  13194. );
  13195. if ('onbeforeprint' in window) {
  13196. const stopPropagationIfNeeded = function (event) {
  13197. if (event.detail !== 'custom') {
  13198. event.stopImmediatePropagation();
  13199. }
  13200. };
  13201. window.addEventListener('beforeprint', stopPropagationIfNeeded);
  13202. window.addEventListener('afterprint', stopPropagationIfNeeded);
  13203. }
  13204. let overlayPromise;
  13205. function ensureOverlay() {
  13206. if (!overlayPromise) {
  13207. overlayManager = _app.PDFViewerApplication.overlayManager;
  13208. if (!overlayManager) {
  13209. throw new Error('The overlay manager has not yet been initialized.');
  13210. }
  13211. dialog ||= document.getElementById('printServiceDialog');
  13212. overlayPromise = overlayManager.register(dialog, true);
  13213. document.getElementById('printCancel').onclick = abort;
  13214. dialog.addEventListener('close', abort);
  13215. }
  13216. return overlayPromise;
  13217. }
  13218. _app.PDFPrintServiceFactory.instance = {
  13219. supportsPrinting: true,
  13220. createPrintService(
  13221. pdfDocument,
  13222. pagesOverview,
  13223. printContainer,
  13224. printResolution,
  13225. optionalContentConfigPromise,
  13226. printAnnotationStoragePromise,
  13227. l10n
  13228. ) {
  13229. if (activeService) {
  13230. throw new Error('The print service is created and active.');
  13231. }
  13232. activeService = new PDFPrintService(
  13233. pdfDocument,
  13234. pagesOverview,
  13235. printContainer,
  13236. printResolution,
  13237. optionalContentConfigPromise,
  13238. printAnnotationStoragePromise,
  13239. l10n
  13240. );
  13241. return activeService;
  13242. }
  13243. };
  13244. /***/
  13245. },
  13246. /* 47 */
  13247. /***/ (__unused_webpack_module, exports, __webpack_require__) => {
  13248. Object.defineProperty(exports, '__esModule', {
  13249. value: true
  13250. });
  13251. exports.getXfaHtmlForPrinting = getXfaHtmlForPrinting;
  13252. var _pdfjsLib = __webpack_require__(4);
  13253. var _pdf_link_service = __webpack_require__(7);
  13254. var _xfa_layer_builder = __webpack_require__(37);
  13255. function getXfaHtmlForPrinting(printContainer, pdfDocument) {
  13256. const xfaHtml = pdfDocument.allXfaHtml;
  13257. const linkService = new _pdf_link_service.SimpleLinkService();
  13258. const scale = Math.round(_pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS * 100) / 100;
  13259. for (const xfaPage of xfaHtml.children) {
  13260. const page = document.createElement('div');
  13261. page.className = 'xfaPrintedPage';
  13262. printContainer.append(page);
  13263. const builder = new _xfa_layer_builder.XfaLayerBuilder({
  13264. pageDiv: page,
  13265. pdfPage: null,
  13266. annotationStorage: pdfDocument.annotationStorage,
  13267. linkService,
  13268. xfaHtml: xfaPage
  13269. });
  13270. const viewport = (0, _pdfjsLib.getXfaPageViewport)(xfaPage, {
  13271. scale
  13272. });
  13273. builder.render(viewport, 'print');
  13274. }
  13275. }
  13276. /***/
  13277. }
  13278. /******/
  13279. ];
  13280. /************************************************************************/
  13281. /******/ // The module cache
  13282. /******/ var __webpack_module_cache__ = {};
  13283. /******/
  13284. /******/ // The require function
  13285. /******/ function __webpack_require__(moduleId) {
  13286. /******/ // Check if module is in cache
  13287. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  13288. /******/ if (cachedModule !== undefined) {
  13289. /******/ return cachedModule.exports;
  13290. /******/
  13291. }
  13292. /******/ // Create a new module (and put it into the cache)
  13293. /******/ var module = (__webpack_module_cache__[moduleId] = {
  13294. /******/ // no module.id needed
  13295. /******/ // no module.loaded needed
  13296. /******/ exports: {}
  13297. /******/
  13298. });
  13299. /******/
  13300. /******/ // Execute the module function
  13301. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  13302. /******/
  13303. /******/ // Return the exports of the module
  13304. /******/ return module.exports;
  13305. /******/
  13306. }
  13307. /******/
  13308. /************************************************************************/
  13309. var __webpack_exports__ = {};
  13310. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  13311. (() => {
  13312. var exports = __webpack_exports__;
  13313. Object.defineProperty(exports, '__esModule', {
  13314. value: true
  13315. });
  13316. Object.defineProperty(exports, 'PDFViewerApplication', {
  13317. enumerable: true,
  13318. get: function () {
  13319. return _app.PDFViewerApplication;
  13320. }
  13321. });
  13322. exports.PDFViewerApplicationConstants = void 0;
  13323. Object.defineProperty(exports, 'PDFViewerApplicationOptions', {
  13324. enumerable: true,
  13325. get: function () {
  13326. return _app_options.AppOptions;
  13327. }
  13328. });
  13329. __webpack_require__(1);
  13330. __webpack_require__(46);
  13331. var _ui_utils = __webpack_require__(3);
  13332. var _app_options = __webpack_require__(5);
  13333. var _pdf_link_service = __webpack_require__(7);
  13334. var _app = __webpack_require__(2);
  13335. const pdfjsVersion = '3.7.107';
  13336. const pdfjsBuild = '036f855dc';
  13337. const AppConstants = {
  13338. LinkTarget: _pdf_link_service.LinkTarget,
  13339. RenderingStates: _ui_utils.RenderingStates,
  13340. ScrollMode: _ui_utils.ScrollMode,
  13341. SpreadMode: _ui_utils.SpreadMode
  13342. };
  13343. exports.PDFViewerApplicationConstants = AppConstants;
  13344. window.PDFViewerApplication = _app.PDFViewerApplication;
  13345. window.PDFViewerApplicationConstants = AppConstants;
  13346. window.PDFViewerApplicationOptions = _app_options.AppOptions;
  13347. function getViewerConfiguration() {
  13348. return {
  13349. appContainer: document.body,
  13350. mainContainer: document.getElementById('viewerContainer'),
  13351. viewerContainer: document.getElementById('viewer'),
  13352. toolbar: {
  13353. container: document.getElementById('toolbarViewer'),
  13354. numPages: document.getElementById('numPages'),
  13355. pageNumber: document.getElementById('pageNumber'),
  13356. scaleSelect: document.getElementById('scaleSelect'),
  13357. customScaleOption: document.getElementById('customScaleOption'),
  13358. previous: document.getElementById('previous'),
  13359. next: document.getElementById('next'),
  13360. zoomIn: document.getElementById('zoomIn'),
  13361. zoomOut: document.getElementById('zoomOut'),
  13362. viewFind: document.getElementById('viewFind'),
  13363. openFile: document.getElementById('openFile'),
  13364. print: document.getElementById('print'),
  13365. editorFreeTextButton: document.getElementById('editorFreeText'),
  13366. editorFreeTextParamsToolbar: document.getElementById('editorFreeTextParamsToolbar'),
  13367. editorInkButton: document.getElementById('editorInk'),
  13368. editorInkParamsToolbar: document.getElementById('editorInkParamsToolbar'),
  13369. download: document.getElementById('download')
  13370. },
  13371. secondaryToolbar: {
  13372. toolbar: document.getElementById('secondaryToolbar'),
  13373. toggleButton: document.getElementById('secondaryToolbarToggle'),
  13374. presentationModeButton: document.getElementById('presentationMode'),
  13375. openFileButton: document.getElementById('secondaryOpenFile'),
  13376. printButton: document.getElementById('secondaryPrint'),
  13377. downloadButton: document.getElementById('secondaryDownload'),
  13378. viewBookmarkButton: document.getElementById('viewBookmark'),
  13379. firstPageButton: document.getElementById('firstPage'),
  13380. lastPageButton: document.getElementById('lastPage'),
  13381. pageRotateCwButton: document.getElementById('pageRotateCw'),
  13382. pageRotateCcwButton: document.getElementById('pageRotateCcw'),
  13383. cursorSelectToolButton: document.getElementById('cursorSelectTool'),
  13384. cursorHandToolButton: document.getElementById('cursorHandTool'),
  13385. scrollPageButton: document.getElementById('scrollPage'),
  13386. scrollVerticalButton: document.getElementById('scrollVertical'),
  13387. scrollHorizontalButton: document.getElementById('scrollHorizontal'),
  13388. scrollWrappedButton: document.getElementById('scrollWrapped'),
  13389. spreadNoneButton: document.getElementById('spreadNone'),
  13390. spreadOddButton: document.getElementById('spreadOdd'),
  13391. spreadEvenButton: document.getElementById('spreadEven'),
  13392. documentPropertiesButton: document.getElementById('documentProperties')
  13393. },
  13394. sidebar: {
  13395. outerContainer: document.getElementById('outerContainer'),
  13396. sidebarContainer: document.getElementById('sidebarContainer'),
  13397. toggleButton: document.getElementById('sidebarToggle'),
  13398. resizer: document.getElementById('sidebarResizer'),
  13399. thumbnailButton: document.getElementById('viewThumbnail'),
  13400. outlineButton: document.getElementById('viewOutline'),
  13401. attachmentsButton: document.getElementById('viewAttachments'),
  13402. layersButton: document.getElementById('viewLayers'),
  13403. thumbnailView: document.getElementById('thumbnailView'),
  13404. outlineView: document.getElementById('outlineView'),
  13405. attachmentsView: document.getElementById('attachmentsView'),
  13406. layersView: document.getElementById('layersView'),
  13407. outlineOptionsContainer: document.getElementById('outlineOptionsContainer'),
  13408. currentOutlineItemButton: document.getElementById('currentOutlineItem')
  13409. },
  13410. findBar: {
  13411. bar: document.getElementById('findbar'),
  13412. toggleButton: document.getElementById('viewFind'),
  13413. findField: document.getElementById('findInput'),
  13414. highlightAllCheckbox: document.getElementById('findHighlightAll'),
  13415. caseSensitiveCheckbox: document.getElementById('findMatchCase'),
  13416. matchDiacriticsCheckbox: document.getElementById('findMatchDiacritics'),
  13417. entireWordCheckbox: document.getElementById('findEntireWord'),
  13418. findMsg: document.getElementById('findMsg'),
  13419. findResultsCount: document.getElementById('findResultsCount'),
  13420. findPreviousButton: document.getElementById('findPrevious'),
  13421. findNextButton: document.getElementById('findNext')
  13422. },
  13423. passwordOverlay: {
  13424. dialog: document.getElementById('passwordDialog'),
  13425. label: document.getElementById('passwordText'),
  13426. input: document.getElementById('password'),
  13427. submitButton: document.getElementById('passwordSubmit'),
  13428. cancelButton: document.getElementById('passwordCancel')
  13429. },
  13430. documentProperties: {
  13431. dialog: document.getElementById('documentPropertiesDialog'),
  13432. closeButton: document.getElementById('documentPropertiesClose'),
  13433. fields: {
  13434. fileName: document.getElementById('fileNameField'),
  13435. fileSize: document.getElementById('fileSizeField'),
  13436. title: document.getElementById('titleField'),
  13437. author: document.getElementById('authorField'),
  13438. subject: document.getElementById('subjectField'),
  13439. keywords: document.getElementById('keywordsField'),
  13440. creationDate: document.getElementById('creationDateField'),
  13441. modificationDate: document.getElementById('modificationDateField'),
  13442. creator: document.getElementById('creatorField'),
  13443. producer: document.getElementById('producerField'),
  13444. version: document.getElementById('versionField'),
  13445. pageCount: document.getElementById('pageCountField'),
  13446. pageSize: document.getElementById('pageSizeField'),
  13447. linearized: document.getElementById('linearizedField')
  13448. }
  13449. },
  13450. annotationEditorParams: {
  13451. editorFreeTextFontSize: document.getElementById('editorFreeTextFontSize'),
  13452. editorFreeTextColor: document.getElementById('editorFreeTextColor'),
  13453. editorInkColor: document.getElementById('editorInkColor'),
  13454. editorInkThickness: document.getElementById('editorInkThickness'),
  13455. editorInkOpacity: document.getElementById('editorInkOpacity')
  13456. },
  13457. printContainer: document.getElementById('printContainer'),
  13458. openFileInput: document.getElementById('fileInput'),
  13459. debuggerScriptPath: './debugger.js'
  13460. };
  13461. }
  13462. function webViewerLoad() {
  13463. const config = getViewerConfiguration();
  13464. const event = new CustomEvent('webviewerloaded', {
  13465. bubbles: true,
  13466. cancelable: true,
  13467. detail: {
  13468. source: window
  13469. }
  13470. });
  13471. try {
  13472. parent.document.dispatchEvent(event);
  13473. } catch (ex) {
  13474. console.error(`webviewerloaded: ${ex}`);
  13475. document.dispatchEvent(event);
  13476. }
  13477. _app.PDFViewerApplication.run(config);
  13478. }
  13479. document.blockUnblockOnload?.(true);
  13480. if (document.readyState === 'interactive' || document.readyState === 'complete') {
  13481. webViewerLoad();
  13482. } else {
  13483. document.addEventListener('DOMContentLoaded', webViewerLoad, true);
  13484. }
  13485. })();
  13486. /******/
  13487. })();
  13488. //# sourceMappingURL=viewer.js.map