viewer.js 257 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /* globals PDFJS, PDFBug, FirefoxCom, Stats, ProgressBar,
  16. DownloadManager, getFileName, getPDFFileNameFromURL,
  17. PDFHistory, Preferences, SidebarView, ViewHistory, Stats,
  18. PDFThumbnailViewer, URL, noContextMenuHandler, SecondaryToolbar,
  19. PasswordPrompt, PDFPresentationMode, PDFDocumentProperties, HandTool,
  20. Promise, PDFLinkService, PDFOutlineView, PDFAttachmentView,
  21. OverlayManager, PDFFindController, PDFFindBar, PDFViewer,
  22. PDFRenderingQueue, PresentationModeState, parseQueryString,
  23. RenderingStates, UNKNOWN_SCALE, DEFAULT_SCALE_VALUE,
  24. IGNORE_CURRENT_POSITION_ON_ZOOM: true */
  25. 'use strict';
  26. var DEFAULT_URL = 'compressed.tracemonkey-pldi-09.pdf';
  27. var DEFAULT_SCALE_DELTA = 1.1;
  28. var MIN_SCALE = 0.25;
  29. var MAX_SCALE = 10.0;
  30. var SCALE_SELECT_CONTAINER_PADDING = 8;
  31. var SCALE_SELECT_PADDING = 22;
  32. var PAGE_NUMBER_LOADING_INDICATOR = 'visiblePageIsLoading';
  33. var DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000;
  34. function configure(PDFJS) {
  35. PDFJS.imageResourcesPath = './images/';
  36. PDFJS.workerSrc = '../build/pdf.worker.js';
  37. PDFJS.cMapUrl = '../web/cmaps/';
  38. PDFJS.cMapPacked = true;
  39. }
  40. var mozL10n = document.mozL10n || document.webL10n;
  41. var CSS_UNITS = 96.0 / 72.0;
  42. var DEFAULT_SCALE_VALUE = 'page-width';
  43. var DEFAULT_SCALE = 1.0;
  44. var UNKNOWN_SCALE = 0;
  45. var MAX_AUTO_SCALE = 1.25;
  46. var SCROLLBAR_PADDING = 40;
  47. var VERTICAL_PADDING = 5;
  48. function getFileName(url) {
  49. var anchor = url.indexOf('#');
  50. var query = url.indexOf('?');
  51. var end = Math.min(
  52. anchor > 0 ? anchor : url.length,
  53. query > 0 ? query : url.length);
  54. return url.substring(url.lastIndexOf('/', end) + 1, end);
  55. }
  56. /**
  57. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  58. * @return {Object} The object with horizontal (sx) and vertical (sy)
  59. scales. The scaled property is set to false if scaling is
  60. not required, true otherwise.
  61. */
  62. function getOutputScale(ctx) {
  63. var devicePixelRatio = window.devicePixelRatio || 1;
  64. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  65. ctx.mozBackingStorePixelRatio ||
  66. ctx.msBackingStorePixelRatio ||
  67. ctx.oBackingStorePixelRatio ||
  68. ctx.backingStorePixelRatio || 1;
  69. var pixelRatio = devicePixelRatio / backingStoreRatio;
  70. return {
  71. sx: pixelRatio,
  72. sy: pixelRatio,
  73. scaled: pixelRatio !== 1
  74. };
  75. }
  76. /**
  77. * Scrolls specified element into view of its parent.
  78. * @param {Object} element - The element to be visible.
  79. * @param {Object} spot - An object with optional top and left properties,
  80. * specifying the offset from the top left edge.
  81. * @param {boolean} skipOverflowHiddenElements - Ignore elements that have
  82. * the CSS rule `overflow: hidden;` set. The default is false.
  83. */
  84. function scrollIntoView(element, spot, skipOverflowHiddenElements) {
  85. // Assuming offsetParent is available (it's not available when viewer is in
  86. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  87. // producing the error. See also animationStartedClosure.
  88. var parent = element.offsetParent;
  89. if (!parent) {
  90. console.error('offsetParent is not set -- cannot scroll');
  91. return;
  92. }
  93. var checkOverflow = skipOverflowHiddenElements || false;
  94. var offsetY = element.offsetTop + element.clientTop;
  95. var offsetX = element.offsetLeft + element.clientLeft;
  96. while (parent.clientHeight === parent.scrollHeight ||
  97. (checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
  98. if (parent.dataset._scaleY) {
  99. offsetY /= parent.dataset._scaleY;
  100. offsetX /= parent.dataset._scaleX;
  101. }
  102. offsetY += parent.offsetTop;
  103. offsetX += parent.offsetLeft;
  104. parent = parent.offsetParent;
  105. if (!parent) {
  106. return; // no need to scroll
  107. }
  108. }
  109. if (spot) {
  110. if (spot.top !== undefined) {
  111. offsetY += spot.top;
  112. }
  113. if (spot.left !== undefined) {
  114. offsetX += spot.left;
  115. parent.scrollLeft = offsetX;
  116. }
  117. }
  118. parent.scrollTop = offsetY;
  119. }
  120. /**
  121. * Helper function to start monitoring the scroll event and converting them into
  122. * PDF.js friendly one: with scroll debounce and scroll direction.
  123. */
  124. function watchScroll(viewAreaElement, callback) {
  125. var debounceScroll = function debounceScroll(evt) {
  126. if (rAF) {
  127. return;
  128. }
  129. // schedule an invocation of scroll for next animation frame.
  130. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  131. rAF = null;
  132. var currentY = viewAreaElement.scrollTop;
  133. var lastY = state.lastY;
  134. if (currentY !== lastY) {
  135. state.down = currentY > lastY;
  136. }
  137. state.lastY = currentY;
  138. callback(state);
  139. });
  140. };
  141. var state = {
  142. down: true,
  143. lastY: viewAreaElement.scrollTop,
  144. _eventHandler: debounceScroll
  145. };
  146. var rAF = null;
  147. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  148. return state;
  149. }
  150. /**
  151. * Helper function to parse query string (e.g. ?param1=value&parm2=...).
  152. */
  153. function parseQueryString(query) {
  154. var parts = query.split('&');
  155. var params = {};
  156. for (var i = 0, ii = parts.length; i < ii; ++i) {
  157. var param = parts[i].split('=');
  158. var key = param[0].toLowerCase();
  159. var value = param.length > 1 ? param[1] : null;
  160. params[decodeURIComponent(key)] = decodeURIComponent(value);
  161. }
  162. return params;
  163. }
  164. /**
  165. * Use binary search to find the index of the first item in a given array which
  166. * passes a given condition. The items are expected to be sorted in the sense
  167. * that if the condition is true for one item in the array, then it is also true
  168. * for all following items.
  169. *
  170. * @returns {Number} Index of the first array element to pass the test,
  171. * or |items.length| if no such element exists.
  172. */
  173. function binarySearchFirstItem(items, condition) {
  174. var minIndex = 0;
  175. var maxIndex = items.length - 1;
  176. if (items.length === 0 || !condition(items[maxIndex])) {
  177. return items.length;
  178. }
  179. if (condition(items[minIndex])) {
  180. return minIndex;
  181. }
  182. while (minIndex < maxIndex) {
  183. var currentIndex = (minIndex + maxIndex) >> 1;
  184. var currentItem = items[currentIndex];
  185. if (condition(currentItem)) {
  186. maxIndex = currentIndex;
  187. } else {
  188. minIndex = currentIndex + 1;
  189. }
  190. }
  191. return minIndex; /* === maxIndex */
  192. }
  193. /**
  194. * Approximates float number as a fraction using Farey sequence (max order
  195. * of 8).
  196. * @param {number} x - Positive float number.
  197. * @returns {Array} Estimated fraction: the first array item is a numerator,
  198. * the second one is a denominator.
  199. */
  200. function approximateFraction(x) {
  201. // Fast paths for int numbers or their inversions.
  202. if (Math.floor(x) === x) {
  203. return [x, 1];
  204. }
  205. var xinv = 1 / x;
  206. var limit = 8;
  207. if (xinv > limit) {
  208. return [1, limit];
  209. } else if (Math.floor(xinv) === xinv) {
  210. return [1, xinv];
  211. }
  212. var x_ = x > 1 ? xinv : x;
  213. // a/b and c/d are neighbours in Farey sequence.
  214. var a = 0, b = 1, c = 1, d = 1;
  215. // Limiting search to order 8.
  216. while (true) {
  217. // Generating next term in sequence (order of q).
  218. var p = a + c, q = b + d;
  219. if (q > limit) {
  220. break;
  221. }
  222. if (x_ <= p / q) {
  223. c = p; d = q;
  224. } else {
  225. a = p; b = q;
  226. }
  227. }
  228. // Select closest of the neighbours to x.
  229. if (x_ - a / b < c / d - x_) {
  230. return x_ === x ? [a, b] : [b, a];
  231. } else {
  232. return x_ === x ? [c, d] : [d, c];
  233. }
  234. }
  235. function roundToDivide(x, div) {
  236. var r = x % div;
  237. return r === 0 ? x : Math.round(x - r + div);
  238. }
  239. /**
  240. * Generic helper to find out what elements are visible within a scroll pane.
  241. */
  242. function getVisibleElements(scrollEl, views, sortByVisibility) {
  243. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  244. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  245. function isElementBottomBelowViewTop(view) {
  246. var element = view.div;
  247. var elementBottom =
  248. element.offsetTop + element.clientTop + element.clientHeight;
  249. return elementBottom > top;
  250. }
  251. var visible = [], view, element;
  252. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  253. var currentWidth, viewWidth;
  254. var firstVisibleElementInd = (views.length === 0) ? 0 :
  255. binarySearchFirstItem(views, isElementBottomBelowViewTop);
  256. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  257. view = views[i];
  258. element = view.div;
  259. currentHeight = element.offsetTop + element.clientTop;
  260. viewHeight = element.clientHeight;
  261. if (currentHeight > bottom) {
  262. break;
  263. }
  264. currentWidth = element.offsetLeft + element.clientLeft;
  265. viewWidth = element.clientWidth;
  266. if (currentWidth + viewWidth < left || currentWidth > right) {
  267. continue;
  268. }
  269. hiddenHeight = Math.max(0, top - currentHeight) +
  270. Math.max(0, currentHeight + viewHeight - bottom);
  271. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  272. visible.push({
  273. id: view.id,
  274. x: currentWidth,
  275. y: currentHeight,
  276. view: view,
  277. percent: percentHeight
  278. });
  279. }
  280. var first = visible[0];
  281. var last = visible[visible.length - 1];
  282. if (sortByVisibility) {
  283. visible.sort(function(a, b) {
  284. var pc = a.percent - b.percent;
  285. if (Math.abs(pc) > 0.001) {
  286. return -pc;
  287. }
  288. return a.id - b.id; // ensure stability
  289. });
  290. }
  291. return {first: first, last: last, views: visible};
  292. }
  293. /**
  294. * Event handler to suppress context menu.
  295. */
  296. function noContextMenuHandler(e) {
  297. e.preventDefault();
  298. }
  299. /**
  300. * Returns the filename or guessed filename from the url (see issue 3455).
  301. * url {String} The original PDF location.
  302. * @return {String} Guessed PDF file name.
  303. */
  304. function getPDFFileNameFromURL(url) {
  305. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  306. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  307. // Pattern to get last matching NAME.pdf
  308. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  309. var splitURI = reURI.exec(url);
  310. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  311. reFilename.exec(splitURI[2]) ||
  312. reFilename.exec(splitURI[3]);
  313. if (suggestedFilename) {
  314. suggestedFilename = suggestedFilename[0];
  315. if (suggestedFilename.indexOf('%') !== -1) {
  316. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  317. try {
  318. suggestedFilename =
  319. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  320. } catch(e) { // Possible (extremely rare) errors:
  321. // URIError "Malformed URI", e.g. for "%AA.pdf"
  322. // TypeError "null has no properties", e.g. for "%2F.pdf"
  323. }
  324. }
  325. }
  326. return suggestedFilename || 'document.pdf';
  327. }
  328. var ProgressBar = (function ProgressBarClosure() {
  329. function clamp(v, min, max) {
  330. return Math.min(Math.max(v, min), max);
  331. }
  332. function ProgressBar(id, opts) {
  333. this.visible = true;
  334. // Fetch the sub-elements for later.
  335. this.div = document.querySelector(id + ' .progress');
  336. // Get the loading bar element, so it can be resized to fit the viewer.
  337. this.bar = this.div.parentNode;
  338. // Get options, with sensible defaults.
  339. this.height = opts.height || 100;
  340. this.width = opts.width || 100;
  341. this.units = opts.units || '%';
  342. // Initialize heights.
  343. this.div.style.height = this.height + this.units;
  344. this.percent = 0;
  345. }
  346. ProgressBar.prototype = {
  347. updateBar: function ProgressBar_updateBar() {
  348. if (this._indeterminate) {
  349. this.div.classList.add('indeterminate');
  350. this.div.style.width = this.width + this.units;
  351. return;
  352. }
  353. this.div.classList.remove('indeterminate');
  354. var progressSize = this.width * this._percent / 100;
  355. this.div.style.width = progressSize + this.units;
  356. },
  357. get percent() {
  358. return this._percent;
  359. },
  360. set percent(val) {
  361. this._indeterminate = isNaN(val);
  362. this._percent = clamp(val, 0, 100);
  363. this.updateBar();
  364. },
  365. setWidth: function ProgressBar_setWidth(viewer) {
  366. if (viewer) {
  367. var container = viewer.parentNode;
  368. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  369. if (scrollbarWidth > 0) {
  370. this.bar.setAttribute('style', 'width: calc(100% - ' +
  371. scrollbarWidth + 'px);');
  372. }
  373. }
  374. },
  375. hide: function ProgressBar_hide() {
  376. if (!this.visible) {
  377. return;
  378. }
  379. this.visible = false;
  380. this.bar.classList.add('hidden');
  381. document.body.classList.remove('loadingInProgress');
  382. },
  383. show: function ProgressBar_show() {
  384. if (this.visible) {
  385. return;
  386. }
  387. this.visible = true;
  388. document.body.classList.add('loadingInProgress');
  389. this.bar.classList.remove('hidden');
  390. }
  391. };
  392. return ProgressBar;
  393. })();
  394. var DEFAULT_PREFERENCES = {
  395. showPreviousViewOnLoad: true,
  396. defaultZoomValue: '',
  397. sidebarViewOnLoad: 0,
  398. enableHandToolOnLoad: false,
  399. enableWebGL: false,
  400. pdfBugEnabled: false,
  401. disableRange: false,
  402. disableStream: false,
  403. disableAutoFetch: false,
  404. disableFontFace: false,
  405. disableTextLayer: false,
  406. useOnlyCssZoom: false,
  407. externalLinkTarget: 0,
  408. };
  409. var SidebarView = {
  410. NONE: 0,
  411. THUMBS: 1,
  412. OUTLINE: 2,
  413. ATTACHMENTS: 3
  414. };
  415. /**
  416. * Preferences - Utility for storing persistent settings.
  417. * Used for settings that should be applied to all opened documents,
  418. * or every time the viewer is loaded.
  419. */
  420. var Preferences = {
  421. prefs: Object.create(DEFAULT_PREFERENCES),
  422. isInitializedPromiseResolved: false,
  423. initializedPromise: null,
  424. /**
  425. * Initialize and fetch the current preference values from storage.
  426. * @return {Promise} A promise that is resolved when the preferences
  427. * have been initialized.
  428. */
  429. initialize: function preferencesInitialize() {
  430. return this.initializedPromise =
  431. this._readFromStorage(DEFAULT_PREFERENCES).then(function(prefObj) {
  432. this.isInitializedPromiseResolved = true;
  433. if (prefObj) {
  434. this.prefs = prefObj;
  435. }
  436. }.bind(this));
  437. },
  438. /**
  439. * Stub function for writing preferences to storage.
  440. * NOTE: This should be overridden by a build-specific function defined below.
  441. * @param {Object} prefObj The preferences that should be written to storage.
  442. * @return {Promise} A promise that is resolved when the preference values
  443. * have been written.
  444. */
  445. _writeToStorage: function preferences_writeToStorage(prefObj) {
  446. return Promise.resolve();
  447. },
  448. /**
  449. * Stub function for reading preferences from storage.
  450. * NOTE: This should be overridden by a build-specific function defined below.
  451. * @param {Object} prefObj The preferences that should be read from storage.
  452. * @return {Promise} A promise that is resolved with an {Object} containing
  453. * the preferences that have been read.
  454. */
  455. _readFromStorage: function preferences_readFromStorage(prefObj) {
  456. return Promise.resolve();
  457. },
  458. /**
  459. * Reset the preferences to their default values and update storage.
  460. * @return {Promise} A promise that is resolved when the preference values
  461. * have been reset.
  462. */
  463. reset: function preferencesReset() {
  464. return this.initializedPromise.then(function() {
  465. this.prefs = Object.create(DEFAULT_PREFERENCES);
  466. return this._writeToStorage(DEFAULT_PREFERENCES);
  467. }.bind(this));
  468. },
  469. /**
  470. * Replace the current preference values with the ones from storage.
  471. * @return {Promise} A promise that is resolved when the preference values
  472. * have been updated.
  473. */
  474. reload: function preferencesReload() {
  475. return this.initializedPromise.then(function () {
  476. this._readFromStorage(DEFAULT_PREFERENCES).then(function(prefObj) {
  477. if (prefObj) {
  478. this.prefs = prefObj;
  479. }
  480. }.bind(this));
  481. }.bind(this));
  482. },
  483. /**
  484. * Set the value of a preference.
  485. * @param {string} name The name of the preference that should be changed.
  486. * @param {boolean|number|string} value The new value of the preference.
  487. * @return {Promise} A promise that is resolved when the value has been set,
  488. * provided that the preference exists and the types match.
  489. */
  490. set: function preferencesSet(name, value) {
  491. return this.initializedPromise.then(function () {
  492. if (DEFAULT_PREFERENCES[name] === undefined) {
  493. throw new Error('preferencesSet: \'' + name + '\' is undefined.');
  494. } else if (value === undefined) {
  495. throw new Error('preferencesSet: no value is specified.');
  496. }
  497. var valueType = typeof value;
  498. var defaultType = typeof DEFAULT_PREFERENCES[name];
  499. if (valueType !== defaultType) {
  500. if (valueType === 'number' && defaultType === 'string') {
  501. value = value.toString();
  502. } else {
  503. throw new Error('Preferences_set: \'' + value + '\' is a \"' +
  504. valueType + '\", expected \"' + defaultType + '\".');
  505. }
  506. } else {
  507. if (valueType === 'number' && (value | 0) !== value) {
  508. throw new Error('Preferences_set: \'' + value +
  509. '\' must be an \"integer\".');
  510. }
  511. }
  512. this.prefs[name] = value;
  513. return this._writeToStorage(this.prefs);
  514. }.bind(this));
  515. },
  516. /**
  517. * Get the value of a preference.
  518. * @param {string} name The name of the preference whose value is requested.
  519. * @return {Promise} A promise that is resolved with a {boolean|number|string}
  520. * containing the value of the preference.
  521. */
  522. get: function preferencesGet(name) {
  523. return this.initializedPromise.then(function () {
  524. var defaultValue = DEFAULT_PREFERENCES[name];
  525. if (defaultValue === undefined) {
  526. throw new Error('preferencesGet: \'' + name + '\' is undefined.');
  527. } else {
  528. var prefValue = this.prefs[name];
  529. if (prefValue !== undefined) {
  530. return prefValue;
  531. }
  532. }
  533. return defaultValue;
  534. }.bind(this));
  535. }
  536. };
  537. Preferences._writeToStorage = function (prefObj) {
  538. return new Promise(function (resolve) {
  539. localStorage.setItem('pdfjs.preferences', JSON.stringify(prefObj));
  540. resolve();
  541. });
  542. };
  543. Preferences._readFromStorage = function (prefObj) {
  544. return new Promise(function (resolve) {
  545. var readPrefs = JSON.parse(localStorage.getItem('pdfjs.preferences'));
  546. resolve(readPrefs);
  547. });
  548. };
  549. (function mozPrintCallbackPolyfillClosure() {
  550. if ('mozPrintCallback' in document.createElement('canvas')) {
  551. return;
  552. }
  553. // Cause positive result on feature-detection:
  554. HTMLCanvasElement.prototype.mozPrintCallback = undefined;
  555. var canvases; // During print task: non-live NodeList of <canvas> elements
  556. var index; // Index of <canvas> element that is being processed
  557. var print = window.print;
  558. window.print = function print() {
  559. if (canvases) {
  560. console.warn('Ignored window.print() because of a pending print job.');
  561. return;
  562. }
  563. try {
  564. dispatchEvent('beforeprint');
  565. } finally {
  566. canvases = document.querySelectorAll('canvas');
  567. index = -1;
  568. next();
  569. }
  570. };
  571. function dispatchEvent(eventType) {
  572. var event = document.createEvent('CustomEvent');
  573. event.initCustomEvent(eventType, false, false, 'custom');
  574. window.dispatchEvent(event);
  575. }
  576. function next() {
  577. if (!canvases) {
  578. return; // Print task cancelled by user (state reset in abort())
  579. }
  580. renderProgress();
  581. if (++index < canvases.length) {
  582. var canvas = canvases[index];
  583. if (typeof canvas.mozPrintCallback === 'function') {
  584. canvas.mozPrintCallback({
  585. context: canvas.getContext('2d'),
  586. abort: abort,
  587. done: next
  588. });
  589. } else {
  590. next();
  591. }
  592. } else {
  593. renderProgress();
  594. print.call(window);
  595. setTimeout(abort, 20); // Tidy-up
  596. }
  597. }
  598. function abort() {
  599. if (canvases) {
  600. canvases = null;
  601. renderProgress();
  602. dispatchEvent('afterprint');
  603. }
  604. }
  605. function renderProgress() {
  606. var progressContainer = document.getElementById('mozPrintCallback-shim');
  607. if (canvases && canvases.length) {
  608. var progress = Math.round(100 * index / canvases.length);
  609. var progressBar = progressContainer.querySelector('progress');
  610. var progressPerc = progressContainer.querySelector('.relative-progress');
  611. progressBar.value = progress;
  612. progressPerc.textContent = progress + '%';
  613. progressContainer.removeAttribute('hidden');
  614. progressContainer.onclick = abort;
  615. } else {
  616. progressContainer.setAttribute('hidden', '');
  617. }
  618. }
  619. var hasAttachEvent = !!document.attachEvent;
  620. window.addEventListener('keydown', function(event) {
  621. // Intercept Cmd/Ctrl + P in all browsers.
  622. // Also intercept Cmd/Ctrl + Shift + P in Chrome and Opera
  623. if (event.keyCode === 80/*P*/ && (event.ctrlKey || event.metaKey) &&
  624. !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  625. window.print();
  626. if (hasAttachEvent) {
  627. // Only attachEvent can cancel Ctrl + P dialog in IE <=10
  628. // attachEvent is gone in IE11, so the dialog will re-appear in IE11.
  629. return;
  630. }
  631. event.preventDefault();
  632. if (event.stopImmediatePropagation) {
  633. event.stopImmediatePropagation();
  634. } else {
  635. event.stopPropagation();
  636. }
  637. return;
  638. }
  639. if (event.keyCode === 27 && canvases) { // Esc
  640. abort();
  641. }
  642. }, true);
  643. if (hasAttachEvent) {
  644. document.attachEvent('onkeydown', function(event) {
  645. event = event || window.event;
  646. if (event.keyCode === 80/*P*/ && event.ctrlKey) {
  647. event.keyCode = 0;
  648. return false;
  649. }
  650. });
  651. }
  652. if ('onbeforeprint' in window) {
  653. // Do not propagate before/afterprint events when they are not triggered
  654. // from within this polyfill. (FF/IE).
  655. var stopPropagationIfNeeded = function(event) {
  656. if (event.detail !== 'custom' && event.stopImmediatePropagation) {
  657. event.stopImmediatePropagation();
  658. }
  659. };
  660. window.addEventListener('beforeprint', stopPropagationIfNeeded, false);
  661. window.addEventListener('afterprint', stopPropagationIfNeeded, false);
  662. }
  663. })();
  664. var DownloadManager = (function DownloadManagerClosure() {
  665. function download(blobUrl, filename) {
  666. var a = document.createElement('a');
  667. if (a.click) {
  668. // Use a.click() if available. Otherwise, Chrome might show
  669. // "Unsafe JavaScript attempt to initiate a navigation change
  670. // for frame with URL" and not open the PDF at all.
  671. // Supported by (not mentioned = untested):
  672. // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
  673. // - Chrome 19 - 26 (18- does not support a.click)
  674. // - Opera 9 - 12.15
  675. // - Internet Explorer 6 - 10
  676. // - Safari 6 (5.1- does not support a.click)
  677. a.href = blobUrl;
  678. a.target = '_parent';
  679. // Use a.download if available. This increases the likelihood that
  680. // the file is downloaded instead of opened by another PDF plugin.
  681. if ('download' in a) {
  682. a.download = filename;
  683. }
  684. // <a> must be in the document for IE and recent Firefox versions.
  685. // (otherwise .click() is ignored)
  686. (document.body || document.documentElement).appendChild(a);
  687. a.click();
  688. a.parentNode.removeChild(a);
  689. } else {
  690. if (window.top === window &&
  691. blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  692. // If _parent == self, then opening an identical URL with different
  693. // location hash will only cause a navigation, not a download.
  694. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  695. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  696. }
  697. window.open(blobUrl, '_parent');
  698. }
  699. }
  700. function DownloadManager() {}
  701. DownloadManager.prototype = {
  702. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  703. if (!PDFJS.isValidUrl(url, true)) {
  704. return; // restricted/invalid URL
  705. }
  706. download(url + '#pdfjs.action=download', filename);
  707. },
  708. downloadData: function DownloadManager_downloadData(data, filename,
  709. contentType) {
  710. if (navigator.msSaveBlob) { // IE10 and above
  711. return navigator.msSaveBlob(new Blob([data], { type: contentType }),
  712. filename);
  713. }
  714. var blobUrl = PDFJS.createObjectURL(data, contentType);
  715. download(blobUrl, filename);
  716. },
  717. download: function DownloadManager_download(blob, url, filename) {
  718. if (!URL) {
  719. // URL.createObjectURL is not supported
  720. this.downloadUrl(url, filename);
  721. return;
  722. }
  723. if (navigator.msSaveBlob) {
  724. // IE10 / IE11
  725. if (!navigator.msSaveBlob(blob, filename)) {
  726. this.downloadUrl(url, filename);
  727. }
  728. return;
  729. }
  730. var blobUrl = URL.createObjectURL(blob);
  731. download(blobUrl, filename);
  732. }
  733. };
  734. return DownloadManager;
  735. })();
  736. var DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;
  737. /**
  738. * View History - This is a utility for saving various view parameters for
  739. * recently opened files.
  740. *
  741. * The way that the view parameters are stored depends on how PDF.js is built,
  742. * for 'node make <flag>' the following cases exist:
  743. * - FIREFOX or MOZCENTRAL - uses sessionStorage.
  744. * - GENERIC or CHROME - uses localStorage, if it is available.
  745. */
  746. var ViewHistory = (function ViewHistoryClosure() {
  747. function ViewHistory(fingerprint, cacheSize) {
  748. this.fingerprint = fingerprint;
  749. this.cacheSize = cacheSize || DEFAULT_VIEW_HISTORY_CACHE_SIZE;
  750. this.isInitializedPromiseResolved = false;
  751. this.initializedPromise =
  752. this._readFromStorage().then(function (databaseStr) {
  753. this.isInitializedPromiseResolved = true;
  754. var database = JSON.parse(databaseStr || '{}');
  755. if (!('files' in database)) {
  756. database.files = [];
  757. }
  758. if (database.files.length >= this.cacheSize) {
  759. database.files.shift();
  760. }
  761. var index;
  762. for (var i = 0, length = database.files.length; i < length; i++) {
  763. var branch = database.files[i];
  764. if (branch.fingerprint === this.fingerprint) {
  765. index = i;
  766. break;
  767. }
  768. }
  769. if (typeof index !== 'number') {
  770. index = database.files.push({fingerprint: this.fingerprint}) - 1;
  771. }
  772. this.file = database.files[index];
  773. this.database = database;
  774. }.bind(this));
  775. }
  776. ViewHistory.prototype = {
  777. _writeToStorage: function ViewHistory_writeToStorage() {
  778. return new Promise(function (resolve) {
  779. var databaseStr = JSON.stringify(this.database);
  780. localStorage.setItem('database', databaseStr);
  781. resolve();
  782. }.bind(this));
  783. },
  784. _readFromStorage: function ViewHistory_readFromStorage() {
  785. return new Promise(function (resolve) {
  786. resolve(localStorage.getItem('database'));
  787. });
  788. },
  789. set: function ViewHistory_set(name, val) {
  790. if (!this.isInitializedPromiseResolved) {
  791. return;
  792. }
  793. this.file[name] = val;
  794. return this._writeToStorage();
  795. },
  796. setMultiple: function ViewHistory_setMultiple(properties) {
  797. if (!this.isInitializedPromiseResolved) {
  798. return;
  799. }
  800. for (var name in properties) {
  801. this.file[name] = properties[name];
  802. }
  803. return this._writeToStorage();
  804. },
  805. get: function ViewHistory_get(name, defaultValue) {
  806. if (!this.isInitializedPromiseResolved) {
  807. return defaultValue;
  808. }
  809. return this.file[name] || defaultValue;
  810. }
  811. };
  812. return ViewHistory;
  813. })();
  814. /**
  815. * Creates a "search bar" given a set of DOM elements that act as controls
  816. * for searching or for setting search preferences in the UI. This object
  817. * also sets up the appropriate events for the controls. Actual searching
  818. * is done by PDFFindController.
  819. */
  820. var PDFFindBar = (function PDFFindBarClosure() {
  821. function PDFFindBar(options) {
  822. this.opened = false;
  823. this.bar = options.bar || null;
  824. this.toggleButton = options.toggleButton || null;
  825. this.findField = options.findField || null;
  826. this.highlightAll = options.highlightAllCheckbox || null;
  827. this.caseSensitive = options.caseSensitiveCheckbox || null;
  828. this.findMsg = options.findMsg || null;
  829. this.findResultsCount = options.findResultsCount || null;
  830. this.findStatusIcon = options.findStatusIcon || null;
  831. this.findPreviousButton = options.findPreviousButton || null;
  832. this.findNextButton = options.findNextButton || null;
  833. this.findController = options.findController || null;
  834. if (this.findController === null) {
  835. throw new Error('PDFFindBar cannot be used without a ' +
  836. 'PDFFindController instance.');
  837. }
  838. // Add event listeners to the DOM elements.
  839. var self = this;
  840. this.toggleButton.addEventListener('click', function() {
  841. self.toggle();
  842. });
  843. this.findField.addEventListener('input', function() {
  844. self.dispatchEvent('');
  845. });
  846. this.bar.addEventListener('keydown', function(evt) {
  847. switch (evt.keyCode) {
  848. case 13: // Enter
  849. if (evt.target === self.findField) {
  850. self.dispatchEvent('again', evt.shiftKey);
  851. }
  852. break;
  853. case 27: // Escape
  854. self.close();
  855. break;
  856. }
  857. });
  858. this.findPreviousButton.addEventListener('click', function() {
  859. self.dispatchEvent('again', true);
  860. });
  861. this.findNextButton.addEventListener('click', function() {
  862. self.dispatchEvent('again', false);
  863. });
  864. this.highlightAll.addEventListener('click', function() {
  865. self.dispatchEvent('highlightallchange');
  866. });
  867. this.caseSensitive.addEventListener('click', function() {
  868. self.dispatchEvent('casesensitivitychange');
  869. });
  870. }
  871. PDFFindBar.prototype = {
  872. dispatchEvent: function PDFFindBar_dispatchEvent(type, findPrev) {
  873. var event = document.createEvent('CustomEvent');
  874. event.initCustomEvent('find' + type, true, true, {
  875. query: this.findField.value,
  876. caseSensitive: this.caseSensitive.checked,
  877. highlightAll: this.highlightAll.checked,
  878. findPrevious: findPrev
  879. });
  880. return window.dispatchEvent(event);
  881. },
  882. updateUIState:
  883. function PDFFindBar_updateUIState(state, previous, matchCount) {
  884. var notFound = false;
  885. var findMsg = '';
  886. var status = '';
  887. switch (state) {
  888. case FindStates.FIND_FOUND:
  889. break;
  890. case FindStates.FIND_PENDING:
  891. status = 'pending';
  892. break;
  893. case FindStates.FIND_NOTFOUND:
  894. findMsg = mozL10n.get('find_not_found', null, 'Phrase not found');
  895. notFound = true;
  896. break;
  897. case FindStates.FIND_WRAPPED:
  898. if (previous) {
  899. findMsg = mozL10n.get('find_reached_top', null,
  900. 'Reached top of document, continued from bottom');
  901. } else {
  902. findMsg = mozL10n.get('find_reached_bottom', null,
  903. 'Reached end of document, continued from top');
  904. }
  905. break;
  906. }
  907. if (notFound) {
  908. this.findField.classList.add('notFound');
  909. } else {
  910. this.findField.classList.remove('notFound');
  911. }
  912. this.findField.setAttribute('data-status', status);
  913. this.findMsg.textContent = findMsg;
  914. this.updateResultsCount(matchCount);
  915. },
  916. updateResultsCount: function(matchCount) {
  917. if (!this.findResultsCount) {
  918. return; // no UI control is provided
  919. }
  920. // If there are no matches, hide the counter
  921. if (!matchCount) {
  922. this.findResultsCount.classList.add('hidden');
  923. return;
  924. }
  925. // Create the match counter
  926. this.findResultsCount.textContent = matchCount.toLocaleString();
  927. // Show the counter
  928. this.findResultsCount.classList.remove('hidden');
  929. },
  930. open: function PDFFindBar_open() {
  931. if (!this.opened) {
  932. this.opened = true;
  933. this.toggleButton.classList.add('toggled');
  934. this.bar.classList.remove('hidden');
  935. }
  936. this.findField.select();
  937. this.findField.focus();
  938. },
  939. close: function PDFFindBar_close() {
  940. if (!this.opened) {
  941. return;
  942. }
  943. this.opened = false;
  944. this.toggleButton.classList.remove('toggled');
  945. this.bar.classList.add('hidden');
  946. this.findController.active = false;
  947. },
  948. toggle: function PDFFindBar_toggle() {
  949. if (this.opened) {
  950. this.close();
  951. } else {
  952. this.open();
  953. }
  954. }
  955. };
  956. return PDFFindBar;
  957. })();
  958. var FindStates = {
  959. FIND_FOUND: 0,
  960. FIND_NOTFOUND: 1,
  961. FIND_WRAPPED: 2,
  962. FIND_PENDING: 3
  963. };
  964. var FIND_SCROLL_OFFSET_TOP = -50;
  965. var FIND_SCROLL_OFFSET_LEFT = -400;
  966. /**
  967. * Provides "search" or "find" functionality for the PDF.
  968. * This object actually performs the search for a given string.
  969. */
  970. var PDFFindController = (function PDFFindControllerClosure() {
  971. function PDFFindController(options) {
  972. this.startedTextExtraction = false;
  973. this.extractTextPromises = [];
  974. this.pendingFindMatches = {};
  975. this.active = false; // If active, find results will be highlighted.
  976. this.pageContents = []; // Stores the text for each page.
  977. this.pageMatches = [];
  978. this.matchCount = 0;
  979. this.selected = { // Currently selected match.
  980. pageIdx: -1,
  981. matchIdx: -1
  982. };
  983. this.offset = { // Where the find algorithm currently is in the document.
  984. pageIdx: null,
  985. matchIdx: null
  986. };
  987. this.pagesToSearch = null;
  988. this.resumePageIdx = null;
  989. this.state = null;
  990. this.dirtyMatch = false;
  991. this.findTimeout = null;
  992. this.pdfViewer = options.pdfViewer || null;
  993. this.integratedFind = options.integratedFind || false;
  994. this.charactersToNormalize = {
  995. '\u2018': '\'', // Left single quotation mark
  996. '\u2019': '\'', // Right single quotation mark
  997. '\u201A': '\'', // Single low-9 quotation mark
  998. '\u201B': '\'', // Single high-reversed-9 quotation mark
  999. '\u201C': '"', // Left double quotation mark
  1000. '\u201D': '"', // Right double quotation mark
  1001. '\u201E': '"', // Double low-9 quotation mark
  1002. '\u201F': '"', // Double high-reversed-9 quotation mark
  1003. '\u00BC': '1/4', // Vulgar fraction one quarter
  1004. '\u00BD': '1/2', // Vulgar fraction one half
  1005. '\u00BE': '3/4', // Vulgar fraction three quarters
  1006. };
  1007. this.findBar = options.findBar || null;
  1008. // Compile the regular expression for text normalization once
  1009. var replace = Object.keys(this.charactersToNormalize).join('');
  1010. this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
  1011. var events = [
  1012. 'find',
  1013. 'findagain',
  1014. 'findhighlightallchange',
  1015. 'findcasesensitivitychange'
  1016. ];
  1017. this.firstPagePromise = new Promise(function (resolve) {
  1018. this.resolveFirstPage = resolve;
  1019. }.bind(this));
  1020. this.handleEvent = this.handleEvent.bind(this);
  1021. for (var i = 0, len = events.length; i < len; i++) {
  1022. window.addEventListener(events[i], this.handleEvent);
  1023. }
  1024. }
  1025. PDFFindController.prototype = {
  1026. setFindBar: function PDFFindController_setFindBar(findBar) {
  1027. this.findBar = findBar;
  1028. },
  1029. reset: function PDFFindController_reset() {
  1030. this.startedTextExtraction = false;
  1031. this.extractTextPromises = [];
  1032. this.active = false;
  1033. },
  1034. normalize: function PDFFindController_normalize(text) {
  1035. var self = this;
  1036. return text.replace(this.normalizationRegex, function (ch) {
  1037. return self.charactersToNormalize[ch];
  1038. });
  1039. },
  1040. calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) {
  1041. var pageContent = this.normalize(this.pageContents[pageIndex]);
  1042. var query = this.normalize(this.state.query);
  1043. var caseSensitive = this.state.caseSensitive;
  1044. var queryLen = query.length;
  1045. if (queryLen === 0) {
  1046. // Do nothing: the matches should be wiped out already.
  1047. return;
  1048. }
  1049. if (!caseSensitive) {
  1050. pageContent = pageContent.toLowerCase();
  1051. query = query.toLowerCase();
  1052. }
  1053. var matches = [];
  1054. var matchIdx = -queryLen;
  1055. while (true) {
  1056. matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
  1057. if (matchIdx === -1) {
  1058. break;
  1059. }
  1060. matches.push(matchIdx);
  1061. }
  1062. this.pageMatches[pageIndex] = matches;
  1063. this.updatePage(pageIndex);
  1064. if (this.resumePageIdx === pageIndex) {
  1065. this.resumePageIdx = null;
  1066. this.nextPageMatch();
  1067. }
  1068. // Update the matches count
  1069. if (matches.length > 0) {
  1070. this.matchCount += matches.length;
  1071. this.updateUIResultsCount();
  1072. }
  1073. },
  1074. extractText: function PDFFindController_extractText() {
  1075. if (this.startedTextExtraction) {
  1076. return;
  1077. }
  1078. this.startedTextExtraction = true;
  1079. this.pageContents = [];
  1080. var extractTextPromisesResolves = [];
  1081. var numPages = this.pdfViewer.pagesCount;
  1082. for (var i = 0; i < numPages; i++) {
  1083. this.extractTextPromises.push(new Promise(function (resolve) {
  1084. extractTextPromisesResolves.push(resolve);
  1085. }));
  1086. }
  1087. var self = this;
  1088. function extractPageText(pageIndex) {
  1089. self.pdfViewer.getPageTextContent(pageIndex).then(
  1090. function textContentResolved(textContent) {
  1091. var textItems = textContent.items;
  1092. var str = [];
  1093. for (var i = 0, len = textItems.length; i < len; i++) {
  1094. str.push(textItems[i].str);
  1095. }
  1096. // Store the pageContent as a string.
  1097. self.pageContents.push(str.join(''));
  1098. extractTextPromisesResolves[pageIndex](pageIndex);
  1099. if ((pageIndex + 1) < self.pdfViewer.pagesCount) {
  1100. extractPageText(pageIndex + 1);
  1101. }
  1102. }
  1103. );
  1104. }
  1105. extractPageText(0);
  1106. },
  1107. handleEvent: function PDFFindController_handleEvent(e) {
  1108. if (this.state === null || e.type !== 'findagain') {
  1109. this.dirtyMatch = true;
  1110. }
  1111. this.state = e.detail;
  1112. this.updateUIState(FindStates.FIND_PENDING);
  1113. this.firstPagePromise.then(function() {
  1114. this.extractText();
  1115. clearTimeout(this.findTimeout);
  1116. if (e.type === 'find') {
  1117. // Only trigger the find action after 250ms of silence.
  1118. this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);
  1119. } else {
  1120. this.nextMatch();
  1121. }
  1122. }.bind(this));
  1123. },
  1124. updatePage: function PDFFindController_updatePage(index) {
  1125. if (this.selected.pageIdx === index) {
  1126. // If the page is selected, scroll the page into view, which triggers
  1127. // rendering the page, which adds the textLayer. Once the textLayer is
  1128. // build, it will scroll onto the selected match.
  1129. this.pdfViewer.scrollPageIntoView(index + 1);
  1130. }
  1131. var page = this.pdfViewer.getPageView(index);
  1132. if (page.textLayer) {
  1133. page.textLayer.updateMatches();
  1134. }
  1135. },
  1136. nextMatch: function PDFFindController_nextMatch() {
  1137. var previous = this.state.findPrevious;
  1138. var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
  1139. var numPages = this.pdfViewer.pagesCount;
  1140. this.active = true;
  1141. if (this.dirtyMatch) {
  1142. // Need to recalculate the matches, reset everything.
  1143. this.dirtyMatch = false;
  1144. this.selected.pageIdx = this.selected.matchIdx = -1;
  1145. this.offset.pageIdx = currentPageIndex;
  1146. this.offset.matchIdx = null;
  1147. this.hadMatch = false;
  1148. this.resumePageIdx = null;
  1149. this.pageMatches = [];
  1150. this.matchCount = 0;
  1151. var self = this;
  1152. for (var i = 0; i < numPages; i++) {
  1153. // Wipe out any previous highlighted matches.
  1154. this.updatePage(i);
  1155. // As soon as the text is extracted start finding the matches.
  1156. if (!(i in this.pendingFindMatches)) {
  1157. this.pendingFindMatches[i] = true;
  1158. this.extractTextPromises[i].then(function(pageIdx) {
  1159. delete self.pendingFindMatches[pageIdx];
  1160. self.calcFindMatch(pageIdx);
  1161. });
  1162. }
  1163. }
  1164. }
  1165. // If there's no query there's no point in searching.
  1166. if (this.state.query === '') {
  1167. this.updateUIState(FindStates.FIND_FOUND);
  1168. return;
  1169. }
  1170. // If we're waiting on a page, we return since we can't do anything else.
  1171. if (this.resumePageIdx) {
  1172. return;
  1173. }
  1174. var offset = this.offset;
  1175. // Keep track of how many pages we should maximally iterate through.
  1176. this.pagesToSearch = numPages;
  1177. // If there's already a matchIdx that means we are iterating through a
  1178. // page's matches.
  1179. if (offset.matchIdx !== null) {
  1180. var numPageMatches = this.pageMatches[offset.pageIdx].length;
  1181. if ((!previous && offset.matchIdx + 1 < numPageMatches) ||
  1182. (previous && offset.matchIdx > 0)) {
  1183. // The simple case; we just have advance the matchIdx to select
  1184. // the next match on the page.
  1185. this.hadMatch = true;
  1186. offset.matchIdx = (previous ? offset.matchIdx - 1 :
  1187. offset.matchIdx + 1);
  1188. this.updateMatch(true);
  1189. return;
  1190. }
  1191. // We went beyond the current page's matches, so we advance to
  1192. // the next page.
  1193. this.advanceOffsetPage(previous);
  1194. }
  1195. // Start searching through the page.
  1196. this.nextPageMatch();
  1197. },
  1198. matchesReady: function PDFFindController_matchesReady(matches) {
  1199. var offset = this.offset;
  1200. var numMatches = matches.length;
  1201. var previous = this.state.findPrevious;
  1202. if (numMatches) {
  1203. // There were matches for the page, so initialize the matchIdx.
  1204. this.hadMatch = true;
  1205. offset.matchIdx = (previous ? numMatches - 1 : 0);
  1206. this.updateMatch(true);
  1207. return true;
  1208. } else {
  1209. // No matches, so attempt to search the next page.
  1210. this.advanceOffsetPage(previous);
  1211. if (offset.wrapped) {
  1212. offset.matchIdx = null;
  1213. if (this.pagesToSearch < 0) {
  1214. // No point in wrapping again, there were no matches.
  1215. this.updateMatch(false);
  1216. // while matches were not found, searching for a page
  1217. // with matches should nevertheless halt.
  1218. return true;
  1219. }
  1220. }
  1221. // Matches were not found (and searching is not done).
  1222. return false;
  1223. }
  1224. },
  1225. /**
  1226. * The method is called back from the text layer when match presentation
  1227. * is updated.
  1228. * @param {number} pageIndex - page index.
  1229. * @param {number} index - match index.
  1230. * @param {Array} elements - text layer div elements array.
  1231. * @param {number} beginIdx - start index of the div array for the match.
  1232. * @param {number} endIdx - end index of the div array for the match.
  1233. */
  1234. updateMatchPosition: function PDFFindController_updateMatchPosition(
  1235. pageIndex, index, elements, beginIdx, endIdx) {
  1236. if (this.selected.matchIdx === index &&
  1237. this.selected.pageIdx === pageIndex) {
  1238. var spot = {
  1239. top: FIND_SCROLL_OFFSET_TOP,
  1240. left: FIND_SCROLL_OFFSET_LEFT
  1241. };
  1242. scrollIntoView(elements[beginIdx], spot,
  1243. /* skipOverflowHiddenElements = */ true);
  1244. }
  1245. },
  1246. nextPageMatch: function PDFFindController_nextPageMatch() {
  1247. if (this.resumePageIdx !== null) {
  1248. console.error('There can only be one pending page.');
  1249. }
  1250. do {
  1251. var pageIdx = this.offset.pageIdx;
  1252. var matches = this.pageMatches[pageIdx];
  1253. if (!matches) {
  1254. // The matches don't exist yet for processing by "matchesReady",
  1255. // so set a resume point for when they do exist.
  1256. this.resumePageIdx = pageIdx;
  1257. break;
  1258. }
  1259. } while (!this.matchesReady(matches));
  1260. },
  1261. advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) {
  1262. var offset = this.offset;
  1263. var numPages = this.extractTextPromises.length;
  1264. offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1);
  1265. offset.matchIdx = null;
  1266. this.pagesToSearch--;
  1267. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  1268. offset.pageIdx = (previous ? numPages - 1 : 0);
  1269. offset.wrapped = true;
  1270. }
  1271. },
  1272. updateMatch: function PDFFindController_updateMatch(found) {
  1273. var state = FindStates.FIND_NOTFOUND;
  1274. var wrapped = this.offset.wrapped;
  1275. this.offset.wrapped = false;
  1276. if (found) {
  1277. var previousPage = this.selected.pageIdx;
  1278. this.selected.pageIdx = this.offset.pageIdx;
  1279. this.selected.matchIdx = this.offset.matchIdx;
  1280. state = (wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND);
  1281. // Update the currently selected page to wipe out any selected matches.
  1282. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
  1283. this.updatePage(previousPage);
  1284. }
  1285. }
  1286. this.updateUIState(state, this.state.findPrevious);
  1287. if (this.selected.pageIdx !== -1) {
  1288. this.updatePage(this.selected.pageIdx);
  1289. }
  1290. },
  1291. updateUIResultsCount:
  1292. function PDFFindController_updateUIResultsCount() {
  1293. if (this.findBar === null) {
  1294. throw new Error('PDFFindController is not initialized with a ' +
  1295. 'PDFFindBar instance.');
  1296. }
  1297. this.findBar.updateResultsCount(this.matchCount);
  1298. },
  1299. updateUIState: function PDFFindController_updateUIState(state, previous) {
  1300. if (this.integratedFind) {
  1301. FirefoxCom.request('updateFindControlState',
  1302. { result: state, findPrevious: previous });
  1303. return;
  1304. }
  1305. if (this.findBar === null) {
  1306. throw new Error('PDFFindController is not initialized with a ' +
  1307. 'PDFFindBar instance.');
  1308. }
  1309. this.findBar.updateUIState(state, previous, this.matchCount);
  1310. }
  1311. };
  1312. return PDFFindController;
  1313. })();
  1314. /**
  1315. * Performs navigation functions inside PDF, such as opening specified page,
  1316. * or destination.
  1317. * @class
  1318. * @implements {IPDFLinkService}
  1319. */
  1320. var PDFLinkService = (function () {
  1321. /**
  1322. * @constructs PDFLinkService
  1323. */
  1324. function PDFLinkService() {
  1325. this.baseUrl = null;
  1326. this.pdfDocument = null;
  1327. this.pdfViewer = null;
  1328. this.pdfHistory = null;
  1329. this._pagesRefCache = null;
  1330. }
  1331. PDFLinkService.prototype = {
  1332. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  1333. this.baseUrl = baseUrl;
  1334. this.pdfDocument = pdfDocument;
  1335. this._pagesRefCache = Object.create(null);
  1336. },
  1337. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  1338. this.pdfViewer = pdfViewer;
  1339. },
  1340. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  1341. this.pdfHistory = pdfHistory;
  1342. },
  1343. /**
  1344. * @returns {number}
  1345. */
  1346. get pagesCount() {
  1347. return this.pdfDocument.numPages;
  1348. },
  1349. /**
  1350. * @returns {number}
  1351. */
  1352. get page() {
  1353. return this.pdfViewer.currentPageNumber;
  1354. },
  1355. /**
  1356. * @param {number} value
  1357. */
  1358. set page(value) {
  1359. this.pdfViewer.currentPageNumber = value;
  1360. },
  1361. /**
  1362. * @param dest - The PDF destination object.
  1363. */
  1364. navigateTo: function PDFLinkService_navigateTo(dest) {
  1365. var destString = '';
  1366. var self = this;
  1367. var goToDestination = function(destRef) {
  1368. // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
  1369. var pageNumber = destRef instanceof Object ?
  1370. self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  1371. (destRef + 1);
  1372. if (pageNumber) {
  1373. if (pageNumber > self.pagesCount) {
  1374. pageNumber = self.pagesCount;
  1375. }
  1376. self.pdfViewer.scrollPageIntoView(pageNumber, dest);
  1377. if (self.pdfHistory) {
  1378. // Update the browsing history.
  1379. self.pdfHistory.push({
  1380. dest: dest,
  1381. hash: destString,
  1382. page: pageNumber
  1383. });
  1384. }
  1385. } else {
  1386. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  1387. var pageNum = pageIndex + 1;
  1388. var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
  1389. self._pagesRefCache[cacheKey] = pageNum;
  1390. goToDestination(destRef);
  1391. });
  1392. }
  1393. };
  1394. var destinationPromise;
  1395. if (typeof dest === 'string') {
  1396. destString = dest;
  1397. destinationPromise = this.pdfDocument.getDestination(dest);
  1398. } else {
  1399. destinationPromise = Promise.resolve(dest);
  1400. }
  1401. destinationPromise.then(function(destination) {
  1402. dest = destination;
  1403. if (!(destination instanceof Array)) {
  1404. return; // invalid destination
  1405. }
  1406. goToDestination(destination[0]);
  1407. });
  1408. },
  1409. /**
  1410. * @param dest - The PDF destination object.
  1411. * @returns {string} The hyperlink to the PDF object.
  1412. */
  1413. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  1414. if (typeof dest === 'string') {
  1415. return this.getAnchorUrl('#' + escape(dest));
  1416. }
  1417. if (dest instanceof Array) {
  1418. var destRef = dest[0]; // see navigateTo method for dest format
  1419. var pageNumber = destRef instanceof Object ?
  1420. this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  1421. (destRef + 1);
  1422. if (pageNumber) {
  1423. var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
  1424. var destKind = dest[1];
  1425. if (typeof destKind === 'object' && 'name' in destKind &&
  1426. destKind.name === 'XYZ') {
  1427. var scale = (dest[4] || this.pdfViewer.currentScaleValue);
  1428. var scaleNumber = parseFloat(scale);
  1429. if (scaleNumber) {
  1430. scale = scaleNumber * 100;
  1431. }
  1432. pdfOpenParams += '&zoom=' + scale;
  1433. if (dest[2] || dest[3]) {
  1434. pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
  1435. }
  1436. }
  1437. return pdfOpenParams;
  1438. }
  1439. }
  1440. return this.getAnchorUrl('');
  1441. },
  1442. /**
  1443. * Prefix the full url on anchor links to make sure that links are resolved
  1444. * relative to the current URL instead of the one defined in <base href>.
  1445. * @param {String} anchor The anchor hash, including the #.
  1446. * @returns {string} The hyperlink to the PDF object.
  1447. */
  1448. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  1449. return (this.baseUrl || '') + anchor;
  1450. },
  1451. /**
  1452. * @param {string} hash
  1453. */
  1454. setHash: function PDFLinkService_setHash(hash) {
  1455. if (hash.indexOf('=') >= 0) {
  1456. var params = parseQueryString(hash);
  1457. // borrowing syntax from "Parameters for Opening PDF Files"
  1458. if ('nameddest' in params) {
  1459. if (this.pdfHistory) {
  1460. this.pdfHistory.updateNextHashParam(params.nameddest);
  1461. }
  1462. this.navigateTo(params.nameddest);
  1463. return;
  1464. }
  1465. var pageNumber, dest;
  1466. if ('page' in params) {
  1467. pageNumber = (params.page | 0) || 1;
  1468. }
  1469. if ('zoom' in params) {
  1470. // Build the destination array.
  1471. var zoomArgs = params.zoom.split(','); // scale,left,top
  1472. var zoomArg = zoomArgs[0];
  1473. var zoomArgNumber = parseFloat(zoomArg);
  1474. if (zoomArg.indexOf('Fit') === -1) {
  1475. // If the zoomArg is a number, it has to get divided by 100. If it's
  1476. // a string, it should stay as it is.
  1477. dest = [null, { name: 'XYZ' },
  1478. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
  1479. zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
  1480. (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
  1481. } else {
  1482. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  1483. dest = [null, { name: zoomArg }];
  1484. } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
  1485. (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  1486. dest = [null, { name: zoomArg },
  1487. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
  1488. } else if (zoomArg === 'FitR') {
  1489. if (zoomArgs.length !== 5) {
  1490. console.error('PDFLinkService_setHash: ' +
  1491. 'Not enough parameters for \'FitR\'.');
  1492. } else {
  1493. dest = [null, { name: zoomArg },
  1494. (zoomArgs[1] | 0), (zoomArgs[2] | 0),
  1495. (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
  1496. }
  1497. } else {
  1498. console.error('PDFLinkService_setHash: \'' + zoomArg +
  1499. '\' is not a valid zoom value.');
  1500. }
  1501. }
  1502. }
  1503. if (dest) {
  1504. this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
  1505. } else if (pageNumber) {
  1506. this.page = pageNumber; // simple page
  1507. }
  1508. if ('pagemode' in params) {
  1509. var event = document.createEvent('CustomEvent');
  1510. event.initCustomEvent('pagemode', true, true, {
  1511. mode: params.pagemode,
  1512. });
  1513. this.pdfViewer.container.dispatchEvent(event);
  1514. }
  1515. } else if (/^\d+$/.test(hash)) { // page number
  1516. this.page = hash;
  1517. } else { // named destination
  1518. if (this.pdfHistory) {
  1519. this.pdfHistory.updateNextHashParam(unescape(hash));
  1520. }
  1521. this.navigateTo(unescape(hash));
  1522. }
  1523. },
  1524. /**
  1525. * @param {string} action
  1526. */
  1527. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  1528. // See PDF reference, table 8.45 - Named action
  1529. switch (action) {
  1530. case 'GoBack':
  1531. if (this.pdfHistory) {
  1532. this.pdfHistory.back();
  1533. }
  1534. break;
  1535. case 'GoForward':
  1536. if (this.pdfHistory) {
  1537. this.pdfHistory.forward();
  1538. }
  1539. break;
  1540. case 'NextPage':
  1541. this.page++;
  1542. break;
  1543. case 'PrevPage':
  1544. this.page--;
  1545. break;
  1546. case 'LastPage':
  1547. this.page = this.pagesCount;
  1548. break;
  1549. case 'FirstPage':
  1550. this.page = 1;
  1551. break;
  1552. default:
  1553. break; // No action according to spec
  1554. }
  1555. var event = document.createEvent('CustomEvent');
  1556. event.initCustomEvent('namedaction', true, true, {
  1557. action: action
  1558. });
  1559. this.pdfViewer.container.dispatchEvent(event);
  1560. },
  1561. /**
  1562. * @param {number} pageNum - page number.
  1563. * @param {Object} pageRef - reference to the page.
  1564. */
  1565. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  1566. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  1567. this._pagesRefCache[refStr] = pageNum;
  1568. }
  1569. };
  1570. return PDFLinkService;
  1571. })();
  1572. var PDFHistory = (function () {
  1573. function PDFHistory(options) {
  1574. this.linkService = options.linkService;
  1575. this.initialized = false;
  1576. this.initialDestination = null;
  1577. this.initialBookmark = null;
  1578. }
  1579. PDFHistory.prototype = {
  1580. /**
  1581. * @param {string} fingerprint
  1582. * @param {IPDFLinkService} linkService
  1583. */
  1584. initialize: function pdfHistoryInitialize(fingerprint) {
  1585. this.initialized = true;
  1586. this.reInitialized = false;
  1587. this.allowHashChange = true;
  1588. this.historyUnlocked = true;
  1589. this.isViewerInPresentationMode = false;
  1590. this.previousHash = window.location.hash.substring(1);
  1591. this.currentBookmark = '';
  1592. this.currentPage = 0;
  1593. this.updatePreviousBookmark = false;
  1594. this.previousBookmark = '';
  1595. this.previousPage = 0;
  1596. this.nextHashParam = '';
  1597. this.fingerprint = fingerprint;
  1598. this.currentUid = this.uid = 0;
  1599. this.current = {};
  1600. var state = window.history.state;
  1601. if (this._isStateObjectDefined(state)) {
  1602. // This corresponds to navigating back to the document
  1603. // from another page in the browser history.
  1604. if (state.target.dest) {
  1605. this.initialDestination = state.target.dest;
  1606. } else {
  1607. this.initialBookmark = state.target.hash;
  1608. }
  1609. this.currentUid = state.uid;
  1610. this.uid = state.uid + 1;
  1611. this.current = state.target;
  1612. } else {
  1613. // This corresponds to the loading of a new document.
  1614. if (state && state.fingerprint &&
  1615. this.fingerprint !== state.fingerprint) {
  1616. // Reinitialize the browsing history when a new document
  1617. // is opened in the web viewer.
  1618. this.reInitialized = true;
  1619. }
  1620. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  1621. }
  1622. var self = this;
  1623. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  1624. if (!self.historyUnlocked) {
  1625. return;
  1626. }
  1627. if (evt.state) {
  1628. // Move back/forward in the history.
  1629. self._goTo(evt.state);
  1630. return;
  1631. }
  1632. // If the state is not set, then the user tried to navigate to a
  1633. // different hash by manually editing the URL and pressing Enter, or by
  1634. // clicking on an in-page link (e.g. the "current view" link).
  1635. // Save the current view state to the browser history.
  1636. // Note: In Firefox, history.null could also be null after an in-page
  1637. // navigation to the same URL, and without dispatching the popstate
  1638. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  1639. if (self.uid === 0) {
  1640. // Replace the previous state if it was not explicitly set.
  1641. var previousParams = (self.previousHash && self.currentBookmark &&
  1642. self.previousHash !== self.currentBookmark) ?
  1643. {hash: self.currentBookmark, page: self.currentPage} :
  1644. {page: 1};
  1645. replacePreviousHistoryState(previousParams, function() {
  1646. updateHistoryWithCurrentHash();
  1647. });
  1648. } else {
  1649. updateHistoryWithCurrentHash();
  1650. }
  1651. }, false);
  1652. function updateHistoryWithCurrentHash() {
  1653. self.previousHash = window.location.hash.slice(1);
  1654. self._pushToHistory({hash: self.previousHash}, false, true);
  1655. self._updatePreviousBookmark();
  1656. }
  1657. function replacePreviousHistoryState(params, callback) {
  1658. // To modify the previous history entry, the following happens:
  1659. // 1. history.back()
  1660. // 2. _pushToHistory, which calls history.replaceState( ... )
  1661. // 3. history.forward()
  1662. // Because a navigation via the history API does not immediately update
  1663. // the history state, the popstate event is used for synchronization.
  1664. self.historyUnlocked = false;
  1665. // Suppress the hashchange event to avoid side effects caused by
  1666. // navigating back and forward.
  1667. self.allowHashChange = false;
  1668. window.addEventListener('popstate', rewriteHistoryAfterBack);
  1669. history.back();
  1670. function rewriteHistoryAfterBack() {
  1671. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  1672. window.addEventListener('popstate', rewriteHistoryAfterForward);
  1673. self._pushToHistory(params, false, true);
  1674. history.forward();
  1675. }
  1676. function rewriteHistoryAfterForward() {
  1677. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  1678. self.allowHashChange = true;
  1679. self.historyUnlocked = true;
  1680. callback();
  1681. }
  1682. }
  1683. function pdfHistoryBeforeUnload() {
  1684. var previousParams = self._getPreviousParams(null, true);
  1685. if (previousParams) {
  1686. var replacePrevious = (!self.current.dest &&
  1687. self.current.hash !== self.previousHash);
  1688. self._pushToHistory(previousParams, false, replacePrevious);
  1689. self._updatePreviousBookmark();
  1690. }
  1691. // Remove the event listener when navigating away from the document,
  1692. // since 'beforeunload' prevents Firefox from caching the document.
  1693. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  1694. false);
  1695. }
  1696. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1697. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  1698. // If the entire viewer (including the PDF file) is cached in
  1699. // the browser, we need to reattach the 'beforeunload' event listener
  1700. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  1701. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1702. }, false);
  1703. window.addEventListener('presentationmodechanged', function(e) {
  1704. self.isViewerInPresentationMode = !!e.detail.active;
  1705. });
  1706. },
  1707. clearHistoryState: function pdfHistory_clearHistoryState() {
  1708. this._pushOrReplaceState(null, true);
  1709. },
  1710. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  1711. return (state && state.uid >= 0 &&
  1712. state.fingerprint && this.fingerprint === state.fingerprint &&
  1713. state.target && state.target.hash) ? true : false;
  1714. },
  1715. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  1716. replace) {
  1717. if (replace) {
  1718. window.history.replaceState(stateObj, '', document.URL);
  1719. } else {
  1720. window.history.pushState(stateObj, '', document.URL);
  1721. }
  1722. },
  1723. get isHashChangeUnlocked() {
  1724. if (!this.initialized) {
  1725. return true;
  1726. }
  1727. return this.allowHashChange;
  1728. },
  1729. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  1730. if (this.updatePreviousBookmark &&
  1731. this.currentBookmark && this.currentPage) {
  1732. this.previousBookmark = this.currentBookmark;
  1733. this.previousPage = this.currentPage;
  1734. this.updatePreviousBookmark = false;
  1735. }
  1736. },
  1737. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  1738. pageNum) {
  1739. if (this.initialized) {
  1740. this.currentBookmark = bookmark.substring(1);
  1741. this.currentPage = pageNum | 0;
  1742. this._updatePreviousBookmark();
  1743. }
  1744. },
  1745. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  1746. if (this.initialized) {
  1747. this.nextHashParam = param;
  1748. }
  1749. },
  1750. push: function pdfHistoryPush(params, isInitialBookmark) {
  1751. if (!(this.initialized && this.historyUnlocked)) {
  1752. return;
  1753. }
  1754. if (params.dest && !params.hash) {
  1755. params.hash = (this.current.hash && this.current.dest &&
  1756. this.current.dest === params.dest) ?
  1757. this.current.hash :
  1758. this.linkService.getDestinationHash(params.dest).split('#')[1];
  1759. }
  1760. if (params.page) {
  1761. params.page |= 0;
  1762. }
  1763. if (isInitialBookmark) {
  1764. var target = window.history.state.target;
  1765. if (!target) {
  1766. // Invoked when the user specifies an initial bookmark,
  1767. // thus setting initialBookmark, when the document is loaded.
  1768. this._pushToHistory(params, false);
  1769. this.previousHash = window.location.hash.substring(1);
  1770. }
  1771. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  1772. if (target) {
  1773. // If the current document is reloaded,
  1774. // avoid creating duplicate entries in the history.
  1775. this._updatePreviousBookmark();
  1776. }
  1777. return;
  1778. }
  1779. if (this.nextHashParam) {
  1780. if (this.nextHashParam === params.hash) {
  1781. this.nextHashParam = null;
  1782. this.updatePreviousBookmark = true;
  1783. return;
  1784. } else {
  1785. this.nextHashParam = null;
  1786. }
  1787. }
  1788. if (params.hash) {
  1789. if (this.current.hash) {
  1790. if (this.current.hash !== params.hash) {
  1791. this._pushToHistory(params, true);
  1792. } else {
  1793. if (!this.current.page && params.page) {
  1794. this._pushToHistory(params, false, true);
  1795. }
  1796. this.updatePreviousBookmark = true;
  1797. }
  1798. } else {
  1799. this._pushToHistory(params, true);
  1800. }
  1801. } else if (this.current.page && params.page &&
  1802. this.current.page !== params.page) {
  1803. this._pushToHistory(params, true);
  1804. }
  1805. },
  1806. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  1807. beforeUnload) {
  1808. if (!(this.currentBookmark && this.currentPage)) {
  1809. return null;
  1810. } else if (this.updatePreviousBookmark) {
  1811. this.updatePreviousBookmark = false;
  1812. }
  1813. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  1814. // Prevent the history from getting stuck in the current state,
  1815. // effectively preventing the user from going back/forward in
  1816. // the history.
  1817. //
  1818. // This happens if the current position in the document didn't change
  1819. // when the history was previously updated. The reasons for this are
  1820. // either:
  1821. // 1. The current zoom value is such that the document does not need to,
  1822. // or cannot, be scrolled to display the destination.
  1823. // 2. The previous destination is broken, and doesn't actally point to a
  1824. // position within the document.
  1825. // (This is either due to a bad PDF generator, or the user making a
  1826. // mistake when entering a destination in the hash parameters.)
  1827. return null;
  1828. }
  1829. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  1830. if (this.previousBookmark === this.currentBookmark) {
  1831. return null;
  1832. }
  1833. } else if (this.current.page || onlyCheckPage) {
  1834. if (this.previousPage === this.currentPage) {
  1835. return null;
  1836. }
  1837. } else {
  1838. return null;
  1839. }
  1840. var params = {hash: this.currentBookmark, page: this.currentPage};
  1841. if (this.isViewerInPresentationMode) {
  1842. params.hash = null;
  1843. }
  1844. return params;
  1845. },
  1846. _stateObj: function pdfHistory_stateObj(params) {
  1847. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  1848. },
  1849. _pushToHistory: function pdfHistory_pushToHistory(params,
  1850. addPrevious, overwrite) {
  1851. if (!this.initialized) {
  1852. return;
  1853. }
  1854. if (!params.hash && params.page) {
  1855. params.hash = ('page=' + params.page);
  1856. }
  1857. if (addPrevious && !overwrite) {
  1858. var previousParams = this._getPreviousParams();
  1859. if (previousParams) {
  1860. var replacePrevious = (!this.current.dest &&
  1861. this.current.hash !== this.previousHash);
  1862. this._pushToHistory(previousParams, false, replacePrevious);
  1863. }
  1864. }
  1865. this._pushOrReplaceState(this._stateObj(params),
  1866. (overwrite || this.uid === 0));
  1867. this.currentUid = this.uid++;
  1868. this.current = params;
  1869. this.updatePreviousBookmark = true;
  1870. },
  1871. _goTo: function pdfHistory_goTo(state) {
  1872. if (!(this.initialized && this.historyUnlocked &&
  1873. this._isStateObjectDefined(state))) {
  1874. return;
  1875. }
  1876. if (!this.reInitialized && state.uid < this.currentUid) {
  1877. var previousParams = this._getPreviousParams(true);
  1878. if (previousParams) {
  1879. this._pushToHistory(this.current, false);
  1880. this._pushToHistory(previousParams, false);
  1881. this.currentUid = state.uid;
  1882. window.history.back();
  1883. return;
  1884. }
  1885. }
  1886. this.historyUnlocked = false;
  1887. if (state.target.dest) {
  1888. this.linkService.navigateTo(state.target.dest);
  1889. } else {
  1890. this.linkService.setHash(state.target.hash);
  1891. }
  1892. this.currentUid = state.uid;
  1893. if (state.uid > this.uid) {
  1894. this.uid = state.uid;
  1895. }
  1896. this.current = state.target;
  1897. this.updatePreviousBookmark = true;
  1898. var currentHash = window.location.hash.substring(1);
  1899. if (this.previousHash !== currentHash) {
  1900. this.allowHashChange = false;
  1901. }
  1902. this.previousHash = currentHash;
  1903. this.historyUnlocked = true;
  1904. },
  1905. back: function pdfHistoryBack() {
  1906. this.go(-1);
  1907. },
  1908. forward: function pdfHistoryForward() {
  1909. this.go(1);
  1910. },
  1911. go: function pdfHistoryGo(direction) {
  1912. if (this.initialized && this.historyUnlocked) {
  1913. var state = window.history.state;
  1914. if (direction === -1 && state && state.uid > 0) {
  1915. window.history.back();
  1916. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  1917. window.history.forward();
  1918. }
  1919. }
  1920. }
  1921. };
  1922. return PDFHistory;
  1923. })();
  1924. var SecondaryToolbar = {
  1925. opened: false,
  1926. previousContainerHeight: null,
  1927. newContainerHeight: null,
  1928. initialize: function secondaryToolbarInitialize(options) {
  1929. this.toolbar = options.toolbar;
  1930. this.buttonContainer = this.toolbar.firstElementChild;
  1931. // Define the toolbar buttons.
  1932. this.toggleButton = options.toggleButton;
  1933. this.presentationModeButton = options.presentationModeButton;
  1934. this.openFile = options.openFile;
  1935. this.print = options.print;
  1936. this.download = options.download;
  1937. this.viewBookmark = options.viewBookmark;
  1938. this.firstPage = options.firstPage;
  1939. this.lastPage = options.lastPage;
  1940. this.pageRotateCw = options.pageRotateCw;
  1941. this.pageRotateCcw = options.pageRotateCcw;
  1942. this.documentPropertiesButton = options.documentPropertiesButton;
  1943. // Attach the event listeners.
  1944. var elements = [
  1945. // Button to toggle the visibility of the secondary toolbar:
  1946. { element: this.toggleButton, handler: this.toggle },
  1947. // All items within the secondary toolbar
  1948. // (except for toggleHandTool, hand_tool.js is responsible for it):
  1949. { element: this.presentationModeButton,
  1950. handler: this.presentationModeClick },
  1951. { element: this.openFile, handler: this.openFileClick },
  1952. { element: this.print, handler: this.printClick },
  1953. { element: this.download, handler: this.downloadClick },
  1954. { element: this.viewBookmark, handler: this.viewBookmarkClick },
  1955. { element: this.firstPage, handler: this.firstPageClick },
  1956. { element: this.lastPage, handler: this.lastPageClick },
  1957. { element: this.pageRotateCw, handler: this.pageRotateCwClick },
  1958. { element: this.pageRotateCcw, handler: this.pageRotateCcwClick },
  1959. { element: this.documentPropertiesButton,
  1960. handler: this.documentPropertiesClick }
  1961. ];
  1962. for (var item in elements) {
  1963. var element = elements[item].element;
  1964. if (element) {
  1965. element.addEventListener('click', elements[item].handler.bind(this));
  1966. }
  1967. }
  1968. },
  1969. // Event handling functions.
  1970. presentationModeClick: function secondaryToolbarPresentationModeClick(evt) {
  1971. PDFViewerApplication.requestPresentationMode();
  1972. this.close();
  1973. },
  1974. openFileClick: function secondaryToolbarOpenFileClick(evt) {
  1975. document.getElementById('fileInput').click();
  1976. this.close();
  1977. },
  1978. printClick: function secondaryToolbarPrintClick(evt) {
  1979. window.print();
  1980. this.close();
  1981. },
  1982. downloadClick: function secondaryToolbarDownloadClick(evt) {
  1983. PDFViewerApplication.download();
  1984. this.close();
  1985. },
  1986. viewBookmarkClick: function secondaryToolbarViewBookmarkClick(evt) {
  1987. this.close();
  1988. },
  1989. firstPageClick: function secondaryToolbarFirstPageClick(evt) {
  1990. PDFViewerApplication.page = 1;
  1991. this.close();
  1992. },
  1993. lastPageClick: function secondaryToolbarLastPageClick(evt) {
  1994. if (PDFViewerApplication.pdfDocument) {
  1995. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  1996. }
  1997. this.close();
  1998. },
  1999. pageRotateCwClick: function secondaryToolbarPageRotateCwClick(evt) {
  2000. PDFViewerApplication.rotatePages(90);
  2001. },
  2002. pageRotateCcwClick: function secondaryToolbarPageRotateCcwClick(evt) {
  2003. PDFViewerApplication.rotatePages(-90);
  2004. },
  2005. documentPropertiesClick: function secondaryToolbarDocumentPropsClick(evt) {
  2006. PDFViewerApplication.pdfDocumentProperties.open();
  2007. this.close();
  2008. },
  2009. // Misc. functions for interacting with the toolbar.
  2010. setMaxHeight: function secondaryToolbarSetMaxHeight(container) {
  2011. if (!container || !this.buttonContainer) {
  2012. return;
  2013. }
  2014. this.newContainerHeight = container.clientHeight;
  2015. if (this.previousContainerHeight === this.newContainerHeight) {
  2016. return;
  2017. }
  2018. this.buttonContainer.setAttribute('style',
  2019. 'max-height: ' + (this.newContainerHeight - SCROLLBAR_PADDING) + 'px;');
  2020. this.previousContainerHeight = this.newContainerHeight;
  2021. },
  2022. open: function secondaryToolbarOpen() {
  2023. if (this.opened) {
  2024. return;
  2025. }
  2026. this.opened = true;
  2027. this.toggleButton.classList.add('toggled');
  2028. this.toolbar.classList.remove('hidden');
  2029. },
  2030. close: function secondaryToolbarClose(target) {
  2031. if (!this.opened) {
  2032. return;
  2033. } else if (target && !this.toolbar.contains(target)) {
  2034. return;
  2035. }
  2036. this.opened = false;
  2037. this.toolbar.classList.add('hidden');
  2038. this.toggleButton.classList.remove('toggled');
  2039. },
  2040. toggle: function secondaryToolbarToggle() {
  2041. if (this.opened) {
  2042. this.close();
  2043. } else {
  2044. this.open();
  2045. }
  2046. }
  2047. };
  2048. var DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS = 1500; // in ms
  2049. var DELAY_BEFORE_HIDING_CONTROLS = 3000; // in ms
  2050. var ACTIVE_SELECTOR = 'pdfPresentationMode';
  2051. var CONTROLS_SELECTOR = 'pdfPresentationModeControls';
  2052. /**
  2053. * @typedef {Object} PDFPresentationModeOptions
  2054. * @property {HTMLDivElement} container - The container for the viewer element.
  2055. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  2056. * @property {PDFViewer} pdfViewer - The document viewer.
  2057. * @property {PDFThumbnailViewer} pdfThumbnailViewer - (optional) The thumbnail
  2058. * viewer.
  2059. * @property {Array} contextMenuItems - (optional) The menuitems that are added
  2060. * to the context menu in Presentation Mode.
  2061. */
  2062. /**
  2063. * @class
  2064. */
  2065. var PDFPresentationMode = (function PDFPresentationModeClosure() {
  2066. /**
  2067. * @constructs PDFPresentationMode
  2068. * @param {PDFPresentationModeOptions} options
  2069. */
  2070. function PDFPresentationMode(options) {
  2071. this.container = options.container;
  2072. this.viewer = options.viewer || options.container.firstElementChild;
  2073. this.pdfViewer = options.pdfViewer;
  2074. this.pdfThumbnailViewer = options.pdfThumbnailViewer || null;
  2075. var contextMenuItems = options.contextMenuItems || null;
  2076. this.active = false;
  2077. this.args = null;
  2078. this.contextMenuOpen = false;
  2079. this.mouseScrollTimeStamp = 0;
  2080. this.mouseScrollDelta = 0;
  2081. if (contextMenuItems) {
  2082. for (var i = 0, ii = contextMenuItems.length; i < ii; i++) {
  2083. var item = contextMenuItems[i];
  2084. item.element.addEventListener('click', function (handler) {
  2085. this.contextMenuOpen = false;
  2086. handler();
  2087. }.bind(this, item.handler));
  2088. }
  2089. }
  2090. }
  2091. PDFPresentationMode.prototype = {
  2092. /**
  2093. * Request the browser to enter fullscreen mode.
  2094. * @returns {boolean} Indicating if the request was successful.
  2095. */
  2096. request: function PDFPresentationMode_request() {
  2097. if (this.switchInProgress || this.active ||
  2098. !this.viewer.hasChildNodes()) {
  2099. return false;
  2100. }
  2101. this._addFullscreenChangeListeners();
  2102. this._setSwitchInProgress();
  2103. this._notifyStateChange();
  2104. if (this.container.requestFullscreen) {
  2105. this.container.requestFullscreen();
  2106. } else if (this.container.mozRequestFullScreen) {
  2107. this.container.mozRequestFullScreen();
  2108. } else if (this.container.webkitRequestFullscreen) {
  2109. this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  2110. } else if (this.container.msRequestFullscreen) {
  2111. this.container.msRequestFullscreen();
  2112. } else {
  2113. return false;
  2114. }
  2115. this.args = {
  2116. page: this.pdfViewer.currentPageNumber,
  2117. previousScale: this.pdfViewer.currentScaleValue,
  2118. };
  2119. return true;
  2120. },
  2121. /**
  2122. * Switches page when the user scrolls (using a scroll wheel or a touchpad)
  2123. * with large enough motion, to prevent accidental page switches.
  2124. * @param {number} delta - The delta value from the mouse event.
  2125. */
  2126. mouseScroll: function PDFPresentationMode_mouseScroll(delta) {
  2127. if (!this.active) {
  2128. return;
  2129. }
  2130. var MOUSE_SCROLL_COOLDOWN_TIME = 50;
  2131. var PAGE_SWITCH_THRESHOLD = 120;
  2132. var PageSwitchDirection = {
  2133. UP: -1,
  2134. DOWN: 1
  2135. };
  2136. var currentTime = (new Date()).getTime();
  2137. var storedTime = this.mouseScrollTimeStamp;
  2138. // If we've already switched page, avoid accidentally switching again.
  2139. if (currentTime > storedTime &&
  2140. currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
  2141. return;
  2142. }
  2143. // If the scroll direction changed, reset the accumulated scroll delta.
  2144. if ((this.mouseScrollDelta > 0 && delta < 0) ||
  2145. (this.mouseScrollDelta < 0 && delta > 0)) {
  2146. this._resetMouseScrollState();
  2147. }
  2148. this.mouseScrollDelta += delta;
  2149. if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) {
  2150. var pageSwitchDirection = (this.mouseScrollDelta > 0) ?
  2151. PageSwitchDirection.UP : PageSwitchDirection.DOWN;
  2152. var page = this.pdfViewer.currentPageNumber;
  2153. this._resetMouseScrollState();
  2154. // If we're at the first/last page, we don't need to do anything.
  2155. if ((page === 1 && pageSwitchDirection === PageSwitchDirection.UP) ||
  2156. (page === this.pdfViewer.pagesCount &&
  2157. pageSwitchDirection === PageSwitchDirection.DOWN)) {
  2158. return;
  2159. }
  2160. this.pdfViewer.currentPageNumber = (page + pageSwitchDirection);
  2161. this.mouseScrollTimeStamp = currentTime;
  2162. }
  2163. },
  2164. get isFullscreen() {
  2165. return !!(document.fullscreenElement ||
  2166. document.mozFullScreen ||
  2167. document.webkitIsFullScreen ||
  2168. document.msFullscreenElement);
  2169. },
  2170. /**
  2171. * @private
  2172. */
  2173. _notifyStateChange: function PDFPresentationMode_notifyStateChange() {
  2174. var event = document.createEvent('CustomEvent');
  2175. event.initCustomEvent('presentationmodechanged', true, true, {
  2176. active: this.active,
  2177. switchInProgress: !!this.switchInProgress
  2178. });
  2179. window.dispatchEvent(event);
  2180. },
  2181. /**
  2182. * Used to initialize a timeout when requesting Presentation Mode,
  2183. * i.e. when the browser is requested to enter fullscreen mode.
  2184. * This timeout is used to prevent the current page from being scrolled
  2185. * partially, or completely, out of view when entering Presentation Mode.
  2186. * NOTE: This issue seems limited to certain zoom levels (e.g. page-width).
  2187. * @private
  2188. */
  2189. _setSwitchInProgress: function PDFPresentationMode_setSwitchInProgress() {
  2190. if (this.switchInProgress) {
  2191. clearTimeout(this.switchInProgress);
  2192. }
  2193. this.switchInProgress = setTimeout(function switchInProgressTimeout() {
  2194. this._removeFullscreenChangeListeners();
  2195. delete this.switchInProgress;
  2196. this._notifyStateChange();
  2197. }.bind(this), DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS);
  2198. },
  2199. /**
  2200. * @private
  2201. */
  2202. _resetSwitchInProgress:
  2203. function PDFPresentationMode_resetSwitchInProgress() {
  2204. if (this.switchInProgress) {
  2205. clearTimeout(this.switchInProgress);
  2206. delete this.switchInProgress;
  2207. }
  2208. },
  2209. /**
  2210. * @private
  2211. */
  2212. _enter: function PDFPresentationMode_enter() {
  2213. this.active = true;
  2214. this._resetSwitchInProgress();
  2215. this._notifyStateChange();
  2216. this.container.classList.add(ACTIVE_SELECTOR);
  2217. // Ensure that the correct page is scrolled into view when entering
  2218. // Presentation Mode, by waiting until fullscreen mode in enabled.
  2219. setTimeout(function enterPresentationModeTimeout() {
  2220. this.pdfViewer.currentPageNumber = this.args.page;
  2221. this.pdfViewer.currentScaleValue = 'page-fit';
  2222. }.bind(this), 0);
  2223. this._addWindowListeners();
  2224. this._showControls();
  2225. this.contextMenuOpen = false;
  2226. this.container.setAttribute('contextmenu', 'viewerContextMenu');
  2227. // Text selection is disabled in Presentation Mode, thus it's not possible
  2228. // for the user to deselect text that is selected (e.g. with "Select all")
  2229. // when entering Presentation Mode, hence we remove any active selection.
  2230. window.getSelection().removeAllRanges();
  2231. },
  2232. /**
  2233. * @private
  2234. */
  2235. _exit: function PDFPresentationMode_exit() {
  2236. var page = this.pdfViewer.currentPageNumber;
  2237. this.container.classList.remove(ACTIVE_SELECTOR);
  2238. // Ensure that the correct page is scrolled into view when exiting
  2239. // Presentation Mode, by waiting until fullscreen mode is disabled.
  2240. setTimeout(function exitPresentationModeTimeout() {
  2241. this.active = false;
  2242. this._removeFullscreenChangeListeners();
  2243. this._notifyStateChange();
  2244. this.pdfViewer.currentScaleValue = this.args.previousScale;
  2245. this.pdfViewer.currentPageNumber = page;
  2246. this.args = null;
  2247. }.bind(this), 0);
  2248. this._removeWindowListeners();
  2249. this._hideControls();
  2250. this._resetMouseScrollState();
  2251. this.container.removeAttribute('contextmenu');
  2252. this.contextMenuOpen = false;
  2253. if (this.pdfThumbnailViewer) {
  2254. this.pdfThumbnailViewer.ensureThumbnailVisible(page);
  2255. }
  2256. },
  2257. /**
  2258. * @private
  2259. */
  2260. _mouseDown: function PDFPresentationMode_mouseDown(evt) {
  2261. if (this.contextMenuOpen) {
  2262. this.contextMenuOpen = false;
  2263. evt.preventDefault();
  2264. return;
  2265. }
  2266. if (evt.button === 0) {
  2267. // Enable clicking of links in presentation mode. Please note:
  2268. // Only links pointing to destinations in the current PDF document work.
  2269. var isInternalLink = (evt.target.href &&
  2270. evt.target.classList.contains('internalLink'));
  2271. if (!isInternalLink) {
  2272. // Unless an internal link was clicked, advance one page.
  2273. evt.preventDefault();
  2274. this.pdfViewer.currentPageNumber += (evt.shiftKey ? -1 : 1);
  2275. }
  2276. }
  2277. },
  2278. /**
  2279. * @private
  2280. */
  2281. _contextMenu: function PDFPresentationMode_contextMenu() {
  2282. this.contextMenuOpen = true;
  2283. },
  2284. /**
  2285. * @private
  2286. */
  2287. _showControls: function PDFPresentationMode_showControls() {
  2288. if (this.controlsTimeout) {
  2289. clearTimeout(this.controlsTimeout);
  2290. } else {
  2291. this.container.classList.add(CONTROLS_SELECTOR);
  2292. }
  2293. this.controlsTimeout = setTimeout(function showControlsTimeout() {
  2294. this.container.classList.remove(CONTROLS_SELECTOR);
  2295. delete this.controlsTimeout;
  2296. }.bind(this), DELAY_BEFORE_HIDING_CONTROLS);
  2297. },
  2298. /**
  2299. * @private
  2300. */
  2301. _hideControls: function PDFPresentationMode_hideControls() {
  2302. if (!this.controlsTimeout) {
  2303. return;
  2304. }
  2305. clearTimeout(this.controlsTimeout);
  2306. this.container.classList.remove(CONTROLS_SELECTOR);
  2307. delete this.controlsTimeout;
  2308. },
  2309. /**
  2310. * Resets the properties used for tracking mouse scrolling events.
  2311. * @private
  2312. */
  2313. _resetMouseScrollState:
  2314. function PDFPresentationMode_resetMouseScrollState() {
  2315. this.mouseScrollTimeStamp = 0;
  2316. this.mouseScrollDelta = 0;
  2317. },
  2318. /**
  2319. * @private
  2320. */
  2321. _addWindowListeners: function PDFPresentationMode_addWindowListeners() {
  2322. this.showControlsBind = this._showControls.bind(this);
  2323. this.mouseDownBind = this._mouseDown.bind(this);
  2324. this.resetMouseScrollStateBind = this._resetMouseScrollState.bind(this);
  2325. this.contextMenuBind = this._contextMenu.bind(this);
  2326. window.addEventListener('mousemove', this.showControlsBind);
  2327. window.addEventListener('mousedown', this.mouseDownBind);
  2328. window.addEventListener('keydown', this.resetMouseScrollStateBind);
  2329. window.addEventListener('contextmenu', this.contextMenuBind);
  2330. },
  2331. /**
  2332. * @private
  2333. */
  2334. _removeWindowListeners:
  2335. function PDFPresentationMode_removeWindowListeners() {
  2336. window.removeEventListener('mousemove', this.showControlsBind);
  2337. window.removeEventListener('mousedown', this.mouseDownBind);
  2338. window.removeEventListener('keydown', this.resetMouseScrollStateBind);
  2339. window.removeEventListener('contextmenu', this.contextMenuBind);
  2340. delete this.showControlsBind;
  2341. delete this.mouseDownBind;
  2342. delete this.resetMouseScrollStateBind;
  2343. delete this.contextMenuBind;
  2344. },
  2345. /**
  2346. * @private
  2347. */
  2348. _fullscreenChange: function PDFPresentationMode_fullscreenChange() {
  2349. if (this.isFullscreen) {
  2350. this._enter();
  2351. } else {
  2352. this._exit();
  2353. }
  2354. },
  2355. /**
  2356. * @private
  2357. */
  2358. _addFullscreenChangeListeners:
  2359. function PDFPresentationMode_addFullscreenChangeListeners() {
  2360. this.fullscreenChangeBind = this._fullscreenChange.bind(this);
  2361. window.addEventListener('fullscreenchange', this.fullscreenChangeBind);
  2362. window.addEventListener('mozfullscreenchange', this.fullscreenChangeBind);
  2363. window.addEventListener('webkitfullscreenchange',
  2364. this.fullscreenChangeBind);
  2365. window.addEventListener('MSFullscreenChange', this.fullscreenChangeBind);
  2366. },
  2367. /**
  2368. * @private
  2369. */
  2370. _removeFullscreenChangeListeners:
  2371. function PDFPresentationMode_removeFullscreenChangeListeners() {
  2372. window.removeEventListener('fullscreenchange', this.fullscreenChangeBind);
  2373. window.removeEventListener('mozfullscreenchange',
  2374. this.fullscreenChangeBind);
  2375. window.removeEventListener('webkitfullscreenchange',
  2376. this.fullscreenChangeBind);
  2377. window.removeEventListener('MSFullscreenChange',
  2378. this.fullscreenChangeBind);
  2379. delete this.fullscreenChangeBind;
  2380. }
  2381. };
  2382. return PDFPresentationMode;
  2383. })();
  2384. var GrabToPan = (function GrabToPanClosure() {
  2385. /**
  2386. * Construct a GrabToPan instance for a given HTML element.
  2387. * @param options.element {Element}
  2388. * @param options.ignoreTarget {function} optional. See `ignoreTarget(node)`
  2389. * @param options.onActiveChanged {function(boolean)} optional. Called
  2390. * when grab-to-pan is (de)activated. The first argument is a boolean that
  2391. * shows whether grab-to-pan is activated.
  2392. */
  2393. function GrabToPan(options) {
  2394. this.element = options.element;
  2395. this.document = options.element.ownerDocument;
  2396. if (typeof options.ignoreTarget === 'function') {
  2397. this.ignoreTarget = options.ignoreTarget;
  2398. }
  2399. this.onActiveChanged = options.onActiveChanged;
  2400. // Bind the contexts to ensure that `this` always points to
  2401. // the GrabToPan instance.
  2402. this.activate = this.activate.bind(this);
  2403. this.deactivate = this.deactivate.bind(this);
  2404. this.toggle = this.toggle.bind(this);
  2405. this._onmousedown = this._onmousedown.bind(this);
  2406. this._onmousemove = this._onmousemove.bind(this);
  2407. this._endPan = this._endPan.bind(this);
  2408. // This overlay will be inserted in the document when the mouse moves during
  2409. // a grab operation, to ensure that the cursor has the desired appearance.
  2410. var overlay = this.overlay = document.createElement('div');
  2411. overlay.className = 'grab-to-pan-grabbing';
  2412. }
  2413. GrabToPan.prototype = {
  2414. /**
  2415. * Class name of element which can be grabbed
  2416. */
  2417. CSS_CLASS_GRAB: 'grab-to-pan-grab',
  2418. /**
  2419. * Bind a mousedown event to the element to enable grab-detection.
  2420. */
  2421. activate: function GrabToPan_activate() {
  2422. if (!this.active) {
  2423. this.active = true;
  2424. this.element.addEventListener('mousedown', this._onmousedown, true);
  2425. this.element.classList.add(this.CSS_CLASS_GRAB);
  2426. if (this.onActiveChanged) {
  2427. this.onActiveChanged(true);
  2428. }
  2429. }
  2430. },
  2431. /**
  2432. * Removes all events. Any pending pan session is immediately stopped.
  2433. */
  2434. deactivate: function GrabToPan_deactivate() {
  2435. if (this.active) {
  2436. this.active = false;
  2437. this.element.removeEventListener('mousedown', this._onmousedown, true);
  2438. this._endPan();
  2439. this.element.classList.remove(this.CSS_CLASS_GRAB);
  2440. if (this.onActiveChanged) {
  2441. this.onActiveChanged(false);
  2442. }
  2443. }
  2444. },
  2445. toggle: function GrabToPan_toggle() {
  2446. if (this.active) {
  2447. this.deactivate();
  2448. } else {
  2449. this.activate();
  2450. }
  2451. },
  2452. /**
  2453. * Whether to not pan if the target element is clicked.
  2454. * Override this method to change the default behaviour.
  2455. *
  2456. * @param node {Element} The target of the event
  2457. * @return {boolean} Whether to not react to the click event.
  2458. */
  2459. ignoreTarget: function GrabToPan_ignoreTarget(node) {
  2460. // Use matchesSelector to check whether the clicked element
  2461. // is (a child of) an input element / link
  2462. return node[matchesSelector](
  2463. 'a[href], a[href] *, input, textarea, button, button *, select, option'
  2464. );
  2465. },
  2466. /**
  2467. * @private
  2468. */
  2469. _onmousedown: function GrabToPan__onmousedown(event) {
  2470. if (event.button !== 0 || this.ignoreTarget(event.target)) {
  2471. return;
  2472. }
  2473. if (event.originalTarget) {
  2474. try {
  2475. /* jshint expr:true */
  2476. event.originalTarget.tagName;
  2477. } catch (e) {
  2478. // Mozilla-specific: element is a scrollbar (XUL element)
  2479. return;
  2480. }
  2481. }
  2482. this.scrollLeftStart = this.element.scrollLeft;
  2483. this.scrollTopStart = this.element.scrollTop;
  2484. this.clientXStart = event.clientX;
  2485. this.clientYStart = event.clientY;
  2486. this.document.addEventListener('mousemove', this._onmousemove, true);
  2487. this.document.addEventListener('mouseup', this._endPan, true);
  2488. // When a scroll event occurs before a mousemove, assume that the user
  2489. // dragged a scrollbar (necessary for Opera Presto, Safari and IE)
  2490. // (not needed for Chrome/Firefox)
  2491. this.element.addEventListener('scroll', this._endPan, true);
  2492. event.preventDefault();
  2493. event.stopPropagation();
  2494. this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);
  2495. var focusedElement = document.activeElement;
  2496. if (focusedElement && !focusedElement.contains(event.target)) {
  2497. focusedElement.blur();
  2498. }
  2499. },
  2500. /**
  2501. * @private
  2502. */
  2503. _onmousemove: function GrabToPan__onmousemove(event) {
  2504. this.element.removeEventListener('scroll', this._endPan, true);
  2505. if (isLeftMouseReleased(event)) {
  2506. this._endPan();
  2507. return;
  2508. }
  2509. var xDiff = event.clientX - this.clientXStart;
  2510. var yDiff = event.clientY - this.clientYStart;
  2511. this.element.scrollTop = this.scrollTopStart - yDiff;
  2512. this.element.scrollLeft = this.scrollLeftStart - xDiff;
  2513. if (!this.overlay.parentNode) {
  2514. document.body.appendChild(this.overlay);
  2515. }
  2516. },
  2517. /**
  2518. * @private
  2519. */
  2520. _endPan: function GrabToPan__endPan() {
  2521. this.element.removeEventListener('scroll', this._endPan, true);
  2522. this.document.removeEventListener('mousemove', this._onmousemove, true);
  2523. this.document.removeEventListener('mouseup', this._endPan, true);
  2524. if (this.overlay.parentNode) {
  2525. this.overlay.parentNode.removeChild(this.overlay);
  2526. }
  2527. }
  2528. };
  2529. // Get the correct (vendor-prefixed) name of the matches method.
  2530. var matchesSelector;
  2531. ['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {
  2532. var name = prefix + 'atches';
  2533. if (name in document.documentElement) {
  2534. matchesSelector = name;
  2535. }
  2536. name += 'Selector';
  2537. if (name in document.documentElement) {
  2538. matchesSelector = name;
  2539. }
  2540. return matchesSelector; // If found, then truthy, and [].some() ends.
  2541. });
  2542. // Browser sniffing because it's impossible to feature-detect
  2543. // whether event.which for onmousemove is reliable
  2544. var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;
  2545. var chrome = window.chrome;
  2546. var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);
  2547. // ^ Chrome 15+ ^ Opera 15+
  2548. var isSafari6plus = /Apple/.test(navigator.vendor) &&
  2549. /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);
  2550. /**
  2551. * Whether the left mouse is not pressed.
  2552. * @param event {MouseEvent}
  2553. * @return {boolean} True if the left mouse button is not pressed.
  2554. * False if unsure or if the left mouse button is pressed.
  2555. */
  2556. function isLeftMouseReleased(event) {
  2557. if ('buttons' in event && isNotIEorIsIE10plus) {
  2558. // http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
  2559. // Firefox 15+
  2560. // Internet Explorer 10+
  2561. return !(event.buttons | 1);
  2562. }
  2563. if (isChrome15OrOpera15plus || isSafari6plus) {
  2564. // Chrome 14+
  2565. // Opera 15+
  2566. // Safari 6.0+
  2567. return event.which === 0;
  2568. }
  2569. }
  2570. return GrabToPan;
  2571. })();
  2572. var HandTool = {
  2573. initialize: function handToolInitialize(options) {
  2574. var toggleHandTool = options.toggleHandTool;
  2575. this.handTool = new GrabToPan({
  2576. element: options.container,
  2577. onActiveChanged: function(isActive) {
  2578. if (!toggleHandTool) {
  2579. return;
  2580. }
  2581. if (isActive) {
  2582. toggleHandTool.title =
  2583. mozL10n.get('hand_tool_disable.title', null, 'Disable hand tool');
  2584. toggleHandTool.firstElementChild.textContent =
  2585. mozL10n.get('hand_tool_disable_label', null, 'Disable hand tool');
  2586. } else {
  2587. toggleHandTool.title =
  2588. mozL10n.get('hand_tool_enable.title', null, 'Enable hand tool');
  2589. toggleHandTool.firstElementChild.textContent =
  2590. mozL10n.get('hand_tool_enable_label', null, 'Enable hand tool');
  2591. }
  2592. }
  2593. });
  2594. if (toggleHandTool) {
  2595. toggleHandTool.addEventListener('click', this.toggle.bind(this), false);
  2596. window.addEventListener('localized', function (evt) {
  2597. Preferences.get('enableHandToolOnLoad').then(function resolved(value) {
  2598. if (value) {
  2599. this.handTool.activate();
  2600. }
  2601. }.bind(this), function rejected(reason) {});
  2602. }.bind(this));
  2603. window.addEventListener('presentationmodechanged', function (evt) {
  2604. if (evt.detail.switchInProgress) {
  2605. return;
  2606. }
  2607. if (evt.detail.active) {
  2608. this.enterPresentationMode();
  2609. } else {
  2610. this.exitPresentationMode();
  2611. }
  2612. }.bind(this));
  2613. }
  2614. },
  2615. toggle: function handToolToggle() {
  2616. this.handTool.toggle();
  2617. SecondaryToolbar.close();
  2618. },
  2619. enterPresentationMode: function handToolEnterPresentationMode() {
  2620. if (this.handTool.active) {
  2621. this.wasActive = true;
  2622. this.handTool.deactivate();
  2623. }
  2624. },
  2625. exitPresentationMode: function handToolExitPresentationMode() {
  2626. if (this.wasActive) {
  2627. this.wasActive = null;
  2628. this.handTool.activate();
  2629. }
  2630. }
  2631. };
  2632. var OverlayManager = {
  2633. overlays: {},
  2634. active: null,
  2635. /**
  2636. * @param {string} name The name of the overlay that is registered. This must
  2637. * be equal to the ID of the overlay's DOM element.
  2638. * @param {function} callerCloseMethod (optional) The method that, if present,
  2639. * will call OverlayManager.close from the Object
  2640. * registering the overlay. Access to this method is
  2641. * necessary in order to run cleanup code when e.g.
  2642. * the overlay is force closed. The default is null.
  2643. * @param {boolean} canForceClose (optional) Indicates if opening the overlay
  2644. * will close an active overlay. The default is false.
  2645. * @returns {Promise} A promise that is resolved when the overlay has been
  2646. * registered.
  2647. */
  2648. register: function overlayManagerRegister(name,
  2649. callerCloseMethod, canForceClose) {
  2650. return new Promise(function (resolve) {
  2651. var element, container;
  2652. if (!name || !(element = document.getElementById(name)) ||
  2653. !(container = element.parentNode)) {
  2654. throw new Error('Not enough parameters.');
  2655. } else if (this.overlays[name]) {
  2656. throw new Error('The overlay is already registered.');
  2657. }
  2658. this.overlays[name] = { element: element,
  2659. container: container,
  2660. callerCloseMethod: (callerCloseMethod || null),
  2661. canForceClose: (canForceClose || false) };
  2662. resolve();
  2663. }.bind(this));
  2664. },
  2665. /**
  2666. * @param {string} name The name of the overlay that is unregistered.
  2667. * @returns {Promise} A promise that is resolved when the overlay has been
  2668. * unregistered.
  2669. */
  2670. unregister: function overlayManagerUnregister(name) {
  2671. return new Promise(function (resolve) {
  2672. if (!this.overlays[name]) {
  2673. throw new Error('The overlay does not exist.');
  2674. } else if (this.active === name) {
  2675. throw new Error('The overlay cannot be removed while it is active.');
  2676. }
  2677. delete this.overlays[name];
  2678. resolve();
  2679. }.bind(this));
  2680. },
  2681. /**
  2682. * @param {string} name The name of the overlay that should be opened.
  2683. * @returns {Promise} A promise that is resolved when the overlay has been
  2684. * opened.
  2685. */
  2686. open: function overlayManagerOpen(name) {
  2687. return new Promise(function (resolve) {
  2688. if (!this.overlays[name]) {
  2689. throw new Error('The overlay does not exist.');
  2690. } else if (this.active) {
  2691. if (this.overlays[name].canForceClose) {
  2692. this._closeThroughCaller();
  2693. } else if (this.active === name) {
  2694. throw new Error('The overlay is already active.');
  2695. } else {
  2696. throw new Error('Another overlay is currently active.');
  2697. }
  2698. }
  2699. this.active = name;
  2700. this.overlays[this.active].element.classList.remove('hidden');
  2701. this.overlays[this.active].container.classList.remove('hidden');
  2702. window.addEventListener('keydown', this._keyDown);
  2703. resolve();
  2704. }.bind(this));
  2705. },
  2706. /**
  2707. * @param {string} name The name of the overlay that should be closed.
  2708. * @returns {Promise} A promise that is resolved when the overlay has been
  2709. * closed.
  2710. */
  2711. close: function overlayManagerClose(name) {
  2712. return new Promise(function (resolve) {
  2713. if (!this.overlays[name]) {
  2714. throw new Error('The overlay does not exist.');
  2715. } else if (!this.active) {
  2716. throw new Error('The overlay is currently not active.');
  2717. } else if (this.active !== name) {
  2718. throw new Error('Another overlay is currently active.');
  2719. }
  2720. this.overlays[this.active].container.classList.add('hidden');
  2721. this.overlays[this.active].element.classList.add('hidden');
  2722. this.active = null;
  2723. window.removeEventListener('keydown', this._keyDown);
  2724. resolve();
  2725. }.bind(this));
  2726. },
  2727. /**
  2728. * @private
  2729. */
  2730. _keyDown: function overlayManager_keyDown(evt) {
  2731. var self = OverlayManager;
  2732. if (self.active && evt.keyCode === 27) { // Esc key.
  2733. self._closeThroughCaller();
  2734. evt.preventDefault();
  2735. }
  2736. },
  2737. /**
  2738. * @private
  2739. */
  2740. _closeThroughCaller: function overlayManager_closeThroughCaller() {
  2741. if (this.overlays[this.active].callerCloseMethod) {
  2742. this.overlays[this.active].callerCloseMethod();
  2743. }
  2744. if (this.active) {
  2745. this.close(this.active);
  2746. }
  2747. }
  2748. };
  2749. var PasswordPrompt = {
  2750. overlayName: null,
  2751. updatePassword: null,
  2752. reason: null,
  2753. passwordField: null,
  2754. passwordText: null,
  2755. passwordSubmit: null,
  2756. passwordCancel: null,
  2757. initialize: function secondaryToolbarInitialize(options) {
  2758. this.overlayName = options.overlayName;
  2759. this.passwordField = options.passwordField;
  2760. this.passwordText = options.passwordText;
  2761. this.passwordSubmit = options.passwordSubmit;
  2762. this.passwordCancel = options.passwordCancel;
  2763. // Attach the event listeners.
  2764. this.passwordSubmit.addEventListener('click',
  2765. this.verifyPassword.bind(this));
  2766. this.passwordCancel.addEventListener('click', this.close.bind(this));
  2767. this.passwordField.addEventListener('keydown', function (e) {
  2768. if (e.keyCode === 13) { // Enter key
  2769. this.verifyPassword();
  2770. }
  2771. }.bind(this));
  2772. OverlayManager.register(this.overlayName, this.close.bind(this), true);
  2773. },
  2774. open: function passwordPromptOpen() {
  2775. OverlayManager.open(this.overlayName).then(function () {
  2776. this.passwordField.type = 'password';
  2777. this.passwordField.focus();
  2778. var promptString = mozL10n.get('password_label', null,
  2779. 'Enter the password to open this PDF file.');
  2780. if (this.reason === PDFJS.PasswordResponses.INCORRECT_PASSWORD) {
  2781. promptString = mozL10n.get('password_invalid', null,
  2782. 'Invalid password. Please try again.');
  2783. }
  2784. this.passwordText.textContent = promptString;
  2785. }.bind(this));
  2786. },
  2787. close: function passwordPromptClose() {
  2788. OverlayManager.close(this.overlayName).then(function () {
  2789. this.passwordField.value = '';
  2790. this.passwordField.type = '';
  2791. }.bind(this));
  2792. },
  2793. verifyPassword: function passwordPromptVerifyPassword() {
  2794. var password = this.passwordField.value;
  2795. if (password && password.length > 0) {
  2796. this.close();
  2797. return this.updatePassword(password);
  2798. }
  2799. }
  2800. };
  2801. /**
  2802. * @typedef {Object} PDFDocumentPropertiesOptions
  2803. * @property {string} overlayName - Name/identifier for the overlay.
  2804. * @property {Object} fields - Names and elements of the overlay's fields.
  2805. * @property {HTMLButtonElement} closeButton - Button for closing the overlay.
  2806. */
  2807. /**
  2808. * @class
  2809. */
  2810. var PDFDocumentProperties = (function PDFDocumentPropertiesClosure() {
  2811. /**
  2812. * @constructs PDFDocumentProperties
  2813. * @param {PDFDocumentPropertiesOptions} options
  2814. */
  2815. function PDFDocumentProperties(options) {
  2816. this.fields = options.fields;
  2817. this.overlayName = options.overlayName;
  2818. this.rawFileSize = 0;
  2819. this.url = null;
  2820. this.pdfDocument = null;
  2821. // Bind the event listener for the Close button.
  2822. if (options.closeButton) {
  2823. options.closeButton.addEventListener('click', this.close.bind(this));
  2824. }
  2825. this.dataAvailablePromise = new Promise(function (resolve) {
  2826. this.resolveDataAvailable = resolve;
  2827. }.bind(this));
  2828. OverlayManager.register(this.overlayName, this.close.bind(this));
  2829. }
  2830. PDFDocumentProperties.prototype = {
  2831. /**
  2832. * Open the document properties overlay.
  2833. */
  2834. open: function PDFDocumentProperties_open() {
  2835. Promise.all([OverlayManager.open(this.overlayName),
  2836. this.dataAvailablePromise]).then(function () {
  2837. this._getProperties();
  2838. }.bind(this));
  2839. },
  2840. /**
  2841. * Close the document properties overlay.
  2842. */
  2843. close: function PDFDocumentProperties_close() {
  2844. OverlayManager.close(this.overlayName);
  2845. },
  2846. /**
  2847. * Set the file size of the PDF document. This method is used to
  2848. * update the file size in the document properties overlay once it
  2849. * is known so we do not have to wait until the entire file is loaded.
  2850. *
  2851. * @param {number} fileSize - The file size of the PDF document.
  2852. */
  2853. setFileSize: function PDFDocumentProperties_setFileSize(fileSize) {
  2854. if (fileSize > 0) {
  2855. this.rawFileSize = fileSize;
  2856. }
  2857. },
  2858. /**
  2859. * Set a reference to the PDF document and the URL in order
  2860. * to populate the overlay fields with the document properties.
  2861. * Note that the overlay will contain no information if this method
  2862. * is not called.
  2863. *
  2864. * @param {Object} pdfDocument - A reference to the PDF document.
  2865. * @param {string} url - The URL of the document.
  2866. */
  2867. setDocumentAndUrl:
  2868. function PDFDocumentProperties_setDocumentAndUrl(pdfDocument, url) {
  2869. this.pdfDocument = pdfDocument;
  2870. this.url = url;
  2871. this.resolveDataAvailable();
  2872. },
  2873. /**
  2874. * @private
  2875. */
  2876. _getProperties: function PDFDocumentProperties_getProperties() {
  2877. if (!OverlayManager.active) {
  2878. // If the dialog was closed before dataAvailablePromise was resolved,
  2879. // don't bother updating the properties.
  2880. return;
  2881. }
  2882. // Get the file size (if it hasn't already been set).
  2883. this.pdfDocument.getDownloadInfo().then(function(data) {
  2884. if (data.length === this.rawFileSize) {
  2885. return;
  2886. }
  2887. this.setFileSize(data.length);
  2888. this._updateUI(this.fields['fileSize'], this._parseFileSize());
  2889. }.bind(this));
  2890. // Get the document properties.
  2891. this.pdfDocument.getMetadata().then(function(data) {
  2892. var content = {
  2893. 'fileName': getPDFFileNameFromURL(this.url),
  2894. 'fileSize': this._parseFileSize(),
  2895. 'title': data.info.Title,
  2896. 'author': data.info.Author,
  2897. 'subject': data.info.Subject,
  2898. 'keywords': data.info.Keywords,
  2899. 'creationDate': this._parseDate(data.info.CreationDate),
  2900. 'modificationDate': this._parseDate(data.info.ModDate),
  2901. 'creator': data.info.Creator,
  2902. 'producer': data.info.Producer,
  2903. 'version': data.info.PDFFormatVersion,
  2904. 'pageCount': this.pdfDocument.numPages
  2905. };
  2906. // Show the properties in the dialog.
  2907. for (var identifier in content) {
  2908. this._updateUI(this.fields[identifier], content[identifier]);
  2909. }
  2910. }.bind(this));
  2911. },
  2912. /**
  2913. * @private
  2914. */
  2915. _updateUI: function PDFDocumentProperties_updateUI(field, content) {
  2916. if (field && content !== undefined && content !== '') {
  2917. field.textContent = content;
  2918. }
  2919. },
  2920. /**
  2921. * @private
  2922. */
  2923. _parseFileSize: function PDFDocumentProperties_parseFileSize() {
  2924. var fileSize = this.rawFileSize, kb = fileSize / 1024;
  2925. if (!kb) {
  2926. return;
  2927. } else if (kb < 1024) {
  2928. return mozL10n.get('document_properties_kb', {
  2929. size_kb: (+kb.toPrecision(3)).toLocaleString(),
  2930. size_b: fileSize.toLocaleString()
  2931. }, '{{size_kb}} KB ({{size_b}} bytes)');
  2932. } else {
  2933. return mozL10n.get('document_properties_mb', {
  2934. size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),
  2935. size_b: fileSize.toLocaleString()
  2936. }, '{{size_mb}} MB ({{size_b}} bytes)');
  2937. }
  2938. },
  2939. /**
  2940. * @private
  2941. */
  2942. _parseDate: function PDFDocumentProperties_parseDate(inputDate) {
  2943. // This is implemented according to the PDF specification, but note that
  2944. // Adobe Reader doesn't handle changing the date to universal time
  2945. // and doesn't use the user's time zone (they're effectively ignoring
  2946. // the HH' and mm' parts of the date string).
  2947. var dateToParse = inputDate;
  2948. if (dateToParse === undefined) {
  2949. return '';
  2950. }
  2951. // Remove the D: prefix if it is available.
  2952. if (dateToParse.substring(0,2) === 'D:') {
  2953. dateToParse = dateToParse.substring(2);
  2954. }
  2955. // Get all elements from the PDF date string.
  2956. // JavaScript's Date object expects the month to be between
  2957. // 0 and 11 instead of 1 and 12, so we're correcting for this.
  2958. var year = parseInt(dateToParse.substring(0,4), 10);
  2959. var month = parseInt(dateToParse.substring(4,6), 10) - 1;
  2960. var day = parseInt(dateToParse.substring(6,8), 10);
  2961. var hours = parseInt(dateToParse.substring(8,10), 10);
  2962. var minutes = parseInt(dateToParse.substring(10,12), 10);
  2963. var seconds = parseInt(dateToParse.substring(12,14), 10);
  2964. var utRel = dateToParse.substring(14,15);
  2965. var offsetHours = parseInt(dateToParse.substring(15,17), 10);
  2966. var offsetMinutes = parseInt(dateToParse.substring(18,20), 10);
  2967. // As per spec, utRel = 'Z' means equal to universal time.
  2968. // The other cases ('-' and '+') have to be handled here.
  2969. if (utRel === '-') {
  2970. hours += offsetHours;
  2971. minutes += offsetMinutes;
  2972. } else if (utRel === '+') {
  2973. hours -= offsetHours;
  2974. minutes -= offsetMinutes;
  2975. }
  2976. // Return the new date format from the user's locale.
  2977. var date = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
  2978. var dateString = date.toLocaleDateString();
  2979. var timeString = date.toLocaleTimeString();
  2980. return mozL10n.get('document_properties_date_string',
  2981. {date: dateString, time: timeString},
  2982. '{{date}}, {{time}}');
  2983. }
  2984. };
  2985. return PDFDocumentProperties;
  2986. })();
  2987. var PresentationModeState = {
  2988. UNKNOWN: 0,
  2989. NORMAL: 1,
  2990. CHANGING: 2,
  2991. FULLSCREEN: 3,
  2992. };
  2993. var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
  2994. var DEFAULT_CACHE_SIZE = 10;
  2995. var CLEANUP_TIMEOUT = 30000;
  2996. var RenderingStates = {
  2997. INITIAL: 0,
  2998. RUNNING: 1,
  2999. PAUSED: 2,
  3000. FINISHED: 3
  3001. };
  3002. /**
  3003. * Controls rendering of the views for pages and thumbnails.
  3004. * @class
  3005. */
  3006. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  3007. /**
  3008. * @constructs
  3009. */
  3010. function PDFRenderingQueue() {
  3011. this.pdfViewer = null;
  3012. this.pdfThumbnailViewer = null;
  3013. this.onIdle = null;
  3014. this.highestPriorityPage = null;
  3015. this.idleTimeout = null;
  3016. this.printing = false;
  3017. this.isThumbnailViewEnabled = false;
  3018. }
  3019. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  3020. /**
  3021. * @param {PDFViewer} pdfViewer
  3022. */
  3023. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  3024. this.pdfViewer = pdfViewer;
  3025. },
  3026. /**
  3027. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  3028. */
  3029. setThumbnailViewer:
  3030. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  3031. this.pdfThumbnailViewer = pdfThumbnailViewer;
  3032. },
  3033. /**
  3034. * @param {IRenderableView} view
  3035. * @returns {boolean}
  3036. */
  3037. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  3038. return this.highestPriorityPage === view.renderingId;
  3039. },
  3040. renderHighestPriority: function
  3041. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  3042. if (this.idleTimeout) {
  3043. clearTimeout(this.idleTimeout);
  3044. this.idleTimeout = null;
  3045. }
  3046. // Pages have a higher priority than thumbnails, so check them first.
  3047. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  3048. return;
  3049. }
  3050. // No pages needed rendering so check thumbnails.
  3051. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  3052. if (this.pdfThumbnailViewer.forceRendering()) {
  3053. return;
  3054. }
  3055. }
  3056. if (this.printing) {
  3057. // If printing is currently ongoing do not reschedule cleanup.
  3058. return;
  3059. }
  3060. if (this.onIdle) {
  3061. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  3062. }
  3063. },
  3064. getHighestPriority: function
  3065. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  3066. // The state has changed figure out which page has the highest priority to
  3067. // render next (if any).
  3068. // Priority:
  3069. // 1 visible pages
  3070. // 2 if last scrolled down page after the visible pages
  3071. // 2 if last scrolled up page before the visible pages
  3072. var visibleViews = visible.views;
  3073. var numVisible = visibleViews.length;
  3074. if (numVisible === 0) {
  3075. return false;
  3076. }
  3077. for (var i = 0; i < numVisible; ++i) {
  3078. var view = visibleViews[i].view;
  3079. if (!this.isViewFinished(view)) {
  3080. return view;
  3081. }
  3082. }
  3083. // All the visible views have rendered, try to render next/previous pages.
  3084. if (scrolledDown) {
  3085. var nextPageIndex = visible.last.id;
  3086. // ID's start at 1 so no need to add 1.
  3087. if (views[nextPageIndex] &&
  3088. !this.isViewFinished(views[nextPageIndex])) {
  3089. return views[nextPageIndex];
  3090. }
  3091. } else {
  3092. var previousPageIndex = visible.first.id - 2;
  3093. if (views[previousPageIndex] &&
  3094. !this.isViewFinished(views[previousPageIndex])) {
  3095. return views[previousPageIndex];
  3096. }
  3097. }
  3098. // Everything that needs to be rendered has been.
  3099. return null;
  3100. },
  3101. /**
  3102. * @param {IRenderableView} view
  3103. * @returns {boolean}
  3104. */
  3105. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  3106. return view.renderingState === RenderingStates.FINISHED;
  3107. },
  3108. /**
  3109. * Render a page or thumbnail view. This calls the appropriate function
  3110. * based on the views state. If the view is already rendered it will return
  3111. * false.
  3112. * @param {IRenderableView} view
  3113. */
  3114. renderView: function PDFRenderingQueue_renderView(view) {
  3115. var state = view.renderingState;
  3116. switch (state) {
  3117. case RenderingStates.FINISHED:
  3118. return false;
  3119. case RenderingStates.PAUSED:
  3120. this.highestPriorityPage = view.renderingId;
  3121. view.resume();
  3122. break;
  3123. case RenderingStates.RUNNING:
  3124. this.highestPriorityPage = view.renderingId;
  3125. break;
  3126. case RenderingStates.INITIAL:
  3127. this.highestPriorityPage = view.renderingId;
  3128. var continueRendering = function () {
  3129. this.renderHighestPriority();
  3130. }.bind(this);
  3131. view.draw().then(continueRendering, continueRendering);
  3132. break;
  3133. }
  3134. return true;
  3135. },
  3136. };
  3137. return PDFRenderingQueue;
  3138. })();
  3139. var TEXT_LAYER_RENDER_DELAY = 200; // ms
  3140. /**
  3141. * @typedef {Object} PDFPageViewOptions
  3142. * @property {HTMLDivElement} container - The viewer element.
  3143. * @property {number} id - The page unique ID (normally its number).
  3144. * @property {number} scale - The page scale display.
  3145. * @property {PageViewport} defaultViewport - The page viewport.
  3146. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  3147. * @property {IPDFTextLayerFactory} textLayerFactory
  3148. * @property {IPDFAnnotationLayerFactory} annotationLayerFactory
  3149. */
  3150. /**
  3151. * @class
  3152. * @implements {IRenderableView}
  3153. */
  3154. var PDFPageView = (function PDFPageViewClosure() {
  3155. /**
  3156. * @constructs PDFPageView
  3157. * @param {PDFPageViewOptions} options
  3158. */
  3159. function PDFPageView(options) {
  3160. var container = options.container;
  3161. var id = options.id;
  3162. var scale = options.scale;
  3163. var defaultViewport = options.defaultViewport;
  3164. var renderingQueue = options.renderingQueue;
  3165. var textLayerFactory = options.textLayerFactory;
  3166. var annotationLayerFactory = options.annotationLayerFactory;
  3167. this.id = id;
  3168. this.renderingId = 'page' + id;
  3169. this.rotation = 0;
  3170. this.scale = scale || DEFAULT_SCALE;
  3171. this.viewport = defaultViewport;
  3172. this.pdfPageRotate = defaultViewport.rotation;
  3173. this.hasRestrictedScaling = false;
  3174. this.renderingQueue = renderingQueue;
  3175. this.textLayerFactory = textLayerFactory;
  3176. this.annotationLayerFactory = annotationLayerFactory;
  3177. this.renderingState = RenderingStates.INITIAL;
  3178. this.resume = null;
  3179. this.onBeforeDraw = null;
  3180. this.onAfterDraw = null;
  3181. this.textLayer = null;
  3182. this.zoomLayer = null;
  3183. this.annotationLayer = null;
  3184. var div = document.createElement('div');
  3185. div.id = 'pageContainer' + this.id;
  3186. div.className = 'page';
  3187. div.style.width = Math.floor(this.viewport.width) + 'px';
  3188. div.style.height = Math.floor(this.viewport.height) + 'px';
  3189. div.setAttribute('data-page-number', this.id);
  3190. this.div = div;
  3191. container.appendChild(div);
  3192. }
  3193. PDFPageView.prototype = {
  3194. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  3195. this.pdfPage = pdfPage;
  3196. this.pdfPageRotate = pdfPage.rotate;
  3197. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  3198. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
  3199. totalRotation);
  3200. this.stats = pdfPage.stats;
  3201. this.reset();
  3202. },
  3203. destroy: function PDFPageView_destroy() {
  3204. this.zoomLayer = null;
  3205. this.reset();
  3206. if (this.pdfPage) {
  3207. this.pdfPage.cleanup();
  3208. }
  3209. },
  3210. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  3211. if (this.renderTask) {
  3212. this.renderTask.cancel();
  3213. }
  3214. this.resume = null;
  3215. this.renderingState = RenderingStates.INITIAL;
  3216. var div = this.div;
  3217. div.style.width = Math.floor(this.viewport.width) + 'px';
  3218. div.style.height = Math.floor(this.viewport.height) + 'px';
  3219. var childNodes = div.childNodes;
  3220. var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
  3221. var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
  3222. this.annotationLayer.div) || null;
  3223. for (var i = childNodes.length - 1; i >= 0; i--) {
  3224. var node = childNodes[i];
  3225. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  3226. continue;
  3227. }
  3228. div.removeChild(node);
  3229. }
  3230. div.removeAttribute('data-loaded');
  3231. if (currentAnnotationNode) {
  3232. // Hide annotationLayer until all elements are resized
  3233. // so they are not displayed on the already-resized page
  3234. this.annotationLayer.hide();
  3235. } else {
  3236. this.annotationLayer = null;
  3237. }
  3238. if (this.canvas && !currentZoomLayerNode) {
  3239. // Zeroing the width and height causes Firefox to release graphics
  3240. // resources immediately, which can greatly reduce memory consumption.
  3241. this.canvas.width = 0;
  3242. this.canvas.height = 0;
  3243. delete this.canvas;
  3244. }
  3245. this.loadingIconDiv = document.createElement('div');
  3246. this.loadingIconDiv.className = 'loadingIcon';
  3247. div.appendChild(this.loadingIconDiv);
  3248. },
  3249. update: function PDFPageView_update(scale, rotation) {
  3250. this.scale = scale || this.scale;
  3251. if (typeof rotation !== 'undefined') {
  3252. this.rotation = rotation;
  3253. }
  3254. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  3255. this.viewport = this.viewport.clone({
  3256. scale: this.scale * CSS_UNITS,
  3257. rotation: totalRotation
  3258. });
  3259. var isScalingRestricted = false;
  3260. if (this.canvas && PDFJS.maxCanvasPixels > 0) {
  3261. var outputScale = this.outputScale;
  3262. var pixelsInViewport = this.viewport.width * this.viewport.height;
  3263. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  3264. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  3265. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  3266. PDFJS.maxCanvasPixels) {
  3267. isScalingRestricted = true;
  3268. }
  3269. }
  3270. if (this.canvas) {
  3271. if (PDFJS.useOnlyCssZoom ||
  3272. (this.hasRestrictedScaling && isScalingRestricted)) {
  3273. this.cssTransform(this.canvas, true);
  3274. var event = document.createEvent('CustomEvent');
  3275. event.initCustomEvent('pagerendered', true, true, {
  3276. pageNumber: this.id,
  3277. cssTransform: true,
  3278. });
  3279. this.div.dispatchEvent(event);
  3280. return;
  3281. }
  3282. if (!this.zoomLayer) {
  3283. this.zoomLayer = this.canvas.parentNode;
  3284. this.zoomLayer.style.position = 'absolute';
  3285. }
  3286. }
  3287. if (this.zoomLayer) {
  3288. this.cssTransform(this.zoomLayer.firstChild);
  3289. }
  3290. this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
  3291. },
  3292. /**
  3293. * Called when moved in the parent's container.
  3294. */
  3295. updatePosition: function PDFPageView_updatePosition() {
  3296. if (this.textLayer) {
  3297. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  3298. }
  3299. },
  3300. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  3301. var CustomStyle = PDFJS.CustomStyle;
  3302. // Scale canvas, canvas wrapper, and page container.
  3303. var width = this.viewport.width;
  3304. var height = this.viewport.height;
  3305. var div = this.div;
  3306. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  3307. Math.floor(width) + 'px';
  3308. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  3309. Math.floor(height) + 'px';
  3310. // The canvas may have been originally rotated, rotate relative to that.
  3311. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  3312. var absRotation = Math.abs(relativeRotation);
  3313. var scaleX = 1, scaleY = 1;
  3314. if (absRotation === 90 || absRotation === 270) {
  3315. // Scale x and y because of the rotation.
  3316. scaleX = height / width;
  3317. scaleY = width / height;
  3318. }
  3319. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  3320. 'scale(' + scaleX + ',' + scaleY + ')';
  3321. CustomStyle.setProp('transform', canvas, cssTransform);
  3322. if (this.textLayer) {
  3323. // Rotating the text layer is more complicated since the divs inside the
  3324. // the text layer are rotated.
  3325. // TODO: This could probably be simplified by drawing the text layer in
  3326. // one orientation then rotating overall.
  3327. var textLayerViewport = this.textLayer.viewport;
  3328. var textRelativeRotation = this.viewport.rotation -
  3329. textLayerViewport.rotation;
  3330. var textAbsRotation = Math.abs(textRelativeRotation);
  3331. var scale = width / textLayerViewport.width;
  3332. if (textAbsRotation === 90 || textAbsRotation === 270) {
  3333. scale = width / textLayerViewport.height;
  3334. }
  3335. var textLayerDiv = this.textLayer.textLayerDiv;
  3336. var transX, transY;
  3337. switch (textAbsRotation) {
  3338. case 0:
  3339. transX = transY = 0;
  3340. break;
  3341. case 90:
  3342. transX = 0;
  3343. transY = '-' + textLayerDiv.style.height;
  3344. break;
  3345. case 180:
  3346. transX = '-' + textLayerDiv.style.width;
  3347. transY = '-' + textLayerDiv.style.height;
  3348. break;
  3349. case 270:
  3350. transX = '-' + textLayerDiv.style.width;
  3351. transY = 0;
  3352. break;
  3353. default:
  3354. console.error('Bad rotation value.');
  3355. break;
  3356. }
  3357. CustomStyle.setProp('transform', textLayerDiv,
  3358. 'rotate(' + textAbsRotation + 'deg) ' +
  3359. 'scale(' + scale + ', ' + scale + ') ' +
  3360. 'translate(' + transX + ', ' + transY + ')');
  3361. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  3362. }
  3363. if (redrawAnnotations && this.annotationLayer) {
  3364. this.annotationLayer.render(this.viewport, 'display');
  3365. }
  3366. },
  3367. get width() {
  3368. return this.viewport.width;
  3369. },
  3370. get height() {
  3371. return this.viewport.height;
  3372. },
  3373. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  3374. return this.viewport.convertToPdfPoint(x, y);
  3375. },
  3376. draw: function PDFPageView_draw() {
  3377. if (this.renderingState !== RenderingStates.INITIAL) {
  3378. console.error('Must be in new state before drawing');
  3379. }
  3380. this.renderingState = RenderingStates.RUNNING;
  3381. var pdfPage = this.pdfPage;
  3382. var viewport = this.viewport;
  3383. var div = this.div;
  3384. // Wrap the canvas so if it has a css transform for highdpi the overflow
  3385. // will be hidden in FF.
  3386. var canvasWrapper = document.createElement('div');
  3387. canvasWrapper.style.width = div.style.width;
  3388. canvasWrapper.style.height = div.style.height;
  3389. canvasWrapper.classList.add('canvasWrapper');
  3390. var canvas = document.createElement('canvas');
  3391. canvas.id = 'page' + this.id;
  3392. // Keep the canvas hidden until the first draw callback, or until drawing
  3393. // is complete when `!this.renderingQueue`, to prevent black flickering.
  3394. canvas.setAttribute('hidden', 'hidden');
  3395. var isCanvasHidden = true;
  3396. canvasWrapper.appendChild(canvas);
  3397. if (this.annotationLayer && this.annotationLayer.div) {
  3398. // annotationLayer needs to stay on top
  3399. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  3400. } else {
  3401. div.appendChild(canvasWrapper);
  3402. }
  3403. this.canvas = canvas;
  3404. canvas.mozOpaque = true;
  3405. var ctx = canvas.getContext('2d', {alpha: false});
  3406. var outputScale = getOutputScale(ctx);
  3407. this.outputScale = outputScale;
  3408. if (PDFJS.useOnlyCssZoom) {
  3409. var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
  3410. // Use a scale that will make the canvas be the original intended size
  3411. // of the page.
  3412. outputScale.sx *= actualSizeViewport.width / viewport.width;
  3413. outputScale.sy *= actualSizeViewport.height / viewport.height;
  3414. outputScale.scaled = true;
  3415. }
  3416. if (PDFJS.maxCanvasPixels > 0) {
  3417. var pixelsInViewport = viewport.width * viewport.height;
  3418. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  3419. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  3420. outputScale.sx = maxScale;
  3421. outputScale.sy = maxScale;
  3422. outputScale.scaled = true;
  3423. this.hasRestrictedScaling = true;
  3424. } else {
  3425. this.hasRestrictedScaling = false;
  3426. }
  3427. }
  3428. var sfx = approximateFraction(outputScale.sx);
  3429. var sfy = approximateFraction(outputScale.sy);
  3430. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  3431. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  3432. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  3433. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  3434. // Add the viewport so it's known what it was originally drawn with.
  3435. canvas._viewport = viewport;
  3436. var textLayerDiv = null;
  3437. var textLayer = null;
  3438. if (this.textLayerFactory) {
  3439. textLayerDiv = document.createElement('div');
  3440. textLayerDiv.className = 'textLayer';
  3441. textLayerDiv.style.width = canvasWrapper.style.width;
  3442. textLayerDiv.style.height = canvasWrapper.style.height;
  3443. if (this.annotationLayer && this.annotationLayer.div) {
  3444. // annotationLayer needs to stay on top
  3445. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  3446. } else {
  3447. div.appendChild(textLayerDiv);
  3448. }
  3449. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
  3450. this.id - 1,
  3451. this.viewport);
  3452. }
  3453. this.textLayer = textLayer;
  3454. var resolveRenderPromise, rejectRenderPromise;
  3455. var promise = new Promise(function (resolve, reject) {
  3456. resolveRenderPromise = resolve;
  3457. rejectRenderPromise = reject;
  3458. });
  3459. // Rendering area
  3460. var self = this;
  3461. function pageViewDrawCallback(error) {
  3462. // The renderTask may have been replaced by a new one, so only remove
  3463. // the reference to the renderTask if it matches the one that is
  3464. // triggering this callback.
  3465. if (renderTask === self.renderTask) {
  3466. self.renderTask = null;
  3467. }
  3468. if (error === 'cancelled') {
  3469. rejectRenderPromise(error);
  3470. return;
  3471. }
  3472. self.renderingState = RenderingStates.FINISHED;
  3473. if (isCanvasHidden) {
  3474. self.canvas.removeAttribute('hidden');
  3475. isCanvasHidden = false;
  3476. }
  3477. if (self.loadingIconDiv) {
  3478. div.removeChild(self.loadingIconDiv);
  3479. delete self.loadingIconDiv;
  3480. }
  3481. if (self.zoomLayer) {
  3482. // Zeroing the width and height causes Firefox to release graphics
  3483. // resources immediately, which can greatly reduce memory consumption.
  3484. var zoomLayerCanvas = self.zoomLayer.firstChild;
  3485. zoomLayerCanvas.width = 0;
  3486. zoomLayerCanvas.height = 0;
  3487. div.removeChild(self.zoomLayer);
  3488. self.zoomLayer = null;
  3489. }
  3490. self.error = error;
  3491. self.stats = pdfPage.stats;
  3492. if (self.onAfterDraw) {
  3493. self.onAfterDraw();
  3494. }
  3495. var event = document.createEvent('CustomEvent');
  3496. event.initCustomEvent('pagerendered', true, true, {
  3497. pageNumber: self.id,
  3498. cssTransform: false,
  3499. });
  3500. div.dispatchEvent(event);
  3501. // This custom event is deprecated, and will be removed in the future,
  3502. // please use the |pagerendered| event instead.
  3503. var deprecatedEvent = document.createEvent('CustomEvent');
  3504. deprecatedEvent.initCustomEvent('pagerender', true, true, {
  3505. pageNumber: pdfPage.pageNumber
  3506. });
  3507. div.dispatchEvent(deprecatedEvent);
  3508. if (!error) {
  3509. resolveRenderPromise(undefined);
  3510. } else {
  3511. rejectRenderPromise(error);
  3512. }
  3513. }
  3514. var renderContinueCallback = null;
  3515. if (this.renderingQueue) {
  3516. renderContinueCallback = function renderContinueCallback(cont) {
  3517. if (!self.renderingQueue.isHighestPriority(self)) {
  3518. self.renderingState = RenderingStates.PAUSED;
  3519. self.resume = function resumeCallback() {
  3520. self.renderingState = RenderingStates.RUNNING;
  3521. cont();
  3522. };
  3523. return;
  3524. }
  3525. if (isCanvasHidden) {
  3526. self.canvas.removeAttribute('hidden');
  3527. isCanvasHidden = false;
  3528. }
  3529. cont();
  3530. };
  3531. }
  3532. var transform = !outputScale.scaled ? null :
  3533. [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  3534. var renderContext = {
  3535. canvasContext: ctx,
  3536. transform: transform,
  3537. viewport: this.viewport,
  3538. // intent: 'default', // === 'display'
  3539. };
  3540. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  3541. renderTask.onContinue = renderContinueCallback;
  3542. this.renderTask.promise.then(
  3543. function pdfPageRenderCallback() {
  3544. pageViewDrawCallback(null);
  3545. if (textLayer) {
  3546. self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(
  3547. function textContentResolved(textContent) {
  3548. textLayer.setTextContent(textContent);
  3549. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  3550. }
  3551. );
  3552. }
  3553. },
  3554. function pdfPageRenderError(error) {
  3555. pageViewDrawCallback(error);
  3556. }
  3557. );
  3558. if (this.annotationLayerFactory) {
  3559. if (!this.annotationLayer) {
  3560. this.annotationLayer = this.annotationLayerFactory.
  3561. createAnnotationLayerBuilder(div, this.pdfPage);
  3562. }
  3563. this.annotationLayer.render(this.viewport, 'display');
  3564. }
  3565. div.setAttribute('data-loaded', true);
  3566. if (self.onBeforeDraw) {
  3567. self.onBeforeDraw();
  3568. }
  3569. return promise;
  3570. },
  3571. beforePrint: function PDFPageView_beforePrint() {
  3572. var CustomStyle = PDFJS.CustomStyle;
  3573. var pdfPage = this.pdfPage;
  3574. var viewport = pdfPage.getViewport(1);
  3575. // Use the same hack we use for high dpi displays for printing to get
  3576. // better output until bug 811002 is fixed in FF.
  3577. var PRINT_OUTPUT_SCALE = 2;
  3578. var canvas = document.createElement('canvas');
  3579. // The logical size of the canvas.
  3580. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  3581. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  3582. // The rendered size of the canvas, relative to the size of canvasWrapper.
  3583. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  3584. canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
  3585. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  3586. (1 / PRINT_OUTPUT_SCALE) + ')';
  3587. CustomStyle.setProp('transform' , canvas, cssScale);
  3588. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  3589. var printContainer = document.getElementById('printContainer');
  3590. var canvasWrapper = document.createElement('div');
  3591. canvasWrapper.style.width = viewport.width + 'pt';
  3592. canvasWrapper.style.height = viewport.height + 'pt';
  3593. canvasWrapper.appendChild(canvas);
  3594. printContainer.appendChild(canvasWrapper);
  3595. canvas.mozPrintCallback = function(obj) {
  3596. var ctx = obj.context;
  3597. ctx.save();
  3598. ctx.fillStyle = 'rgb(255, 255, 255)';
  3599. ctx.fillRect(0, 0, canvas.width, canvas.height);
  3600. ctx.restore();
  3601. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  3602. ctx._transformMatrix =
  3603. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  3604. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  3605. var renderContext = {
  3606. canvasContext: ctx,
  3607. viewport: viewport,
  3608. intent: 'print'
  3609. };
  3610. pdfPage.render(renderContext).promise.then(function() {
  3611. // Tell the printEngine that rendering this canvas/page has finished.
  3612. obj.done();
  3613. }, function(error) {
  3614. console.error(error);
  3615. // Tell the printEngine that rendering this canvas/page has failed.
  3616. // This will make the print proces stop.
  3617. if ('abort' in obj) {
  3618. obj.abort();
  3619. } else {
  3620. obj.done();
  3621. }
  3622. });
  3623. };
  3624. },
  3625. };
  3626. return PDFPageView;
  3627. })();
  3628. /**
  3629. * @typedef {Object} TextLayerBuilderOptions
  3630. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  3631. * @property {number} pageIndex - The page index.
  3632. * @property {PageViewport} viewport - The viewport of the text layer.
  3633. * @property {PDFFindController} findController
  3634. */
  3635. /**
  3636. * TextLayerBuilder provides text-selection functionality for the PDF.
  3637. * It does this by creating overlay divs over the PDF text. These divs
  3638. * contain text that matches the PDF text they are overlaying. This object
  3639. * also provides a way to highlight text that is being searched for.
  3640. * @class
  3641. */
  3642. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  3643. function TextLayerBuilder(options) {
  3644. this.textLayerDiv = options.textLayerDiv;
  3645. this.renderingDone = false;
  3646. this.divContentDone = false;
  3647. this.pageIdx = options.pageIndex;
  3648. this.pageNumber = this.pageIdx + 1;
  3649. this.matches = [];
  3650. this.viewport = options.viewport;
  3651. this.textDivs = [];
  3652. this.findController = options.findController || null;
  3653. this.textLayerRenderTask = null;
  3654. this._bindMouse();
  3655. }
  3656. TextLayerBuilder.prototype = {
  3657. _finishRendering: function TextLayerBuilder_finishRendering() {
  3658. this.renderingDone = true;
  3659. var endOfContent = document.createElement('div');
  3660. endOfContent.className = 'endOfContent';
  3661. this.textLayerDiv.appendChild(endOfContent);
  3662. var event = document.createEvent('CustomEvent');
  3663. event.initCustomEvent('textlayerrendered', true, true, {
  3664. pageNumber: this.pageNumber
  3665. });
  3666. this.textLayerDiv.dispatchEvent(event);
  3667. },
  3668. /**
  3669. * Renders the text layer.
  3670. * @param {number} timeout (optional) if specified, the rendering waits
  3671. * for specified amount of ms.
  3672. */
  3673. render: function TextLayerBuilder_render(timeout) {
  3674. if (!this.divContentDone || this.renderingDone) {
  3675. return;
  3676. }
  3677. if (this.textLayerRenderTask) {
  3678. this.textLayerRenderTask.cancel();
  3679. this.textLayerRenderTask = null;
  3680. }
  3681. this.textDivs = [];
  3682. var textLayerFrag = document.createDocumentFragment();
  3683. this.textLayerRenderTask = PDFJS.renderTextLayer({
  3684. textContent: this.textContent,
  3685. container: textLayerFrag,
  3686. viewport: this.viewport,
  3687. textDivs: this.textDivs,
  3688. timeout: timeout
  3689. });
  3690. this.textLayerRenderTask.promise.then(function () {
  3691. this.textLayerDiv.appendChild(textLayerFrag);
  3692. this._finishRendering();
  3693. this.updateMatches();
  3694. }.bind(this), function (reason) {
  3695. // canceled or failed to render text layer -- skipping errors
  3696. });
  3697. },
  3698. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  3699. if (this.textLayerRenderTask) {
  3700. this.textLayerRenderTask.cancel();
  3701. this.textLayerRenderTask = null;
  3702. }
  3703. this.textContent = textContent;
  3704. this.divContentDone = true;
  3705. },
  3706. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  3707. var i = 0;
  3708. var iIndex = 0;
  3709. var bidiTexts = this.textContent.items;
  3710. var end = bidiTexts.length - 1;
  3711. var queryLen = (this.findController === null ?
  3712. 0 : this.findController.state.query.length);
  3713. var ret = [];
  3714. for (var m = 0, len = matches.length; m < len; m++) {
  3715. // Calculate the start position.
  3716. var matchIdx = matches[m];
  3717. // Loop over the divIdxs.
  3718. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  3719. iIndex += bidiTexts[i].str.length;
  3720. i++;
  3721. }
  3722. if (i === bidiTexts.length) {
  3723. console.error('Could not find a matching mapping');
  3724. }
  3725. var match = {
  3726. begin: {
  3727. divIdx: i,
  3728. offset: matchIdx - iIndex
  3729. }
  3730. };
  3731. // Calculate the end position.
  3732. matchIdx += queryLen;
  3733. // Somewhat the same array as above, but use > instead of >= to get
  3734. // the end position right.
  3735. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  3736. iIndex += bidiTexts[i].str.length;
  3737. i++;
  3738. }
  3739. match.end = {
  3740. divIdx: i,
  3741. offset: matchIdx - iIndex
  3742. };
  3743. ret.push(match);
  3744. }
  3745. return ret;
  3746. },
  3747. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  3748. // Early exit if there is nothing to render.
  3749. if (matches.length === 0) {
  3750. return;
  3751. }
  3752. var bidiTexts = this.textContent.items;
  3753. var textDivs = this.textDivs;
  3754. var prevEnd = null;
  3755. var pageIdx = this.pageIdx;
  3756. var isSelectedPage = (this.findController === null ?
  3757. false : (pageIdx === this.findController.selected.pageIdx));
  3758. var selectedMatchIdx = (this.findController === null ?
  3759. -1 : this.findController.selected.matchIdx);
  3760. var highlightAll = (this.findController === null ?
  3761. false : this.findController.state.highlightAll);
  3762. var infinity = {
  3763. divIdx: -1,
  3764. offset: undefined
  3765. };
  3766. function beginText(begin, className) {
  3767. var divIdx = begin.divIdx;
  3768. textDivs[divIdx].textContent = '';
  3769. appendTextToDiv(divIdx, 0, begin.offset, className);
  3770. }
  3771. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  3772. var div = textDivs[divIdx];
  3773. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  3774. var node = document.createTextNode(content);
  3775. if (className) {
  3776. var span = document.createElement('span');
  3777. span.className = className;
  3778. span.appendChild(node);
  3779. div.appendChild(span);
  3780. return;
  3781. }
  3782. div.appendChild(node);
  3783. }
  3784. var i0 = selectedMatchIdx, i1 = i0 + 1;
  3785. if (highlightAll) {
  3786. i0 = 0;
  3787. i1 = matches.length;
  3788. } else if (!isSelectedPage) {
  3789. // Not highlighting all and this isn't the selected page, so do nothing.
  3790. return;
  3791. }
  3792. for (var i = i0; i < i1; i++) {
  3793. var match = matches[i];
  3794. var begin = match.begin;
  3795. var end = match.end;
  3796. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  3797. var highlightSuffix = (isSelected ? ' selected' : '');
  3798. if (this.findController) {
  3799. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  3800. begin.divIdx, end.divIdx);
  3801. }
  3802. // Match inside new div.
  3803. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  3804. // If there was a previous div, then add the text at the end.
  3805. if (prevEnd !== null) {
  3806. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  3807. }
  3808. // Clear the divs and set the content until the starting point.
  3809. beginText(begin);
  3810. } else {
  3811. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  3812. }
  3813. if (begin.divIdx === end.divIdx) {
  3814. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  3815. 'highlight' + highlightSuffix);
  3816. } else {
  3817. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  3818. 'highlight begin' + highlightSuffix);
  3819. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  3820. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  3821. }
  3822. beginText(end, 'highlight end' + highlightSuffix);
  3823. }
  3824. prevEnd = end;
  3825. }
  3826. if (prevEnd) {
  3827. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  3828. }
  3829. },
  3830. updateMatches: function TextLayerBuilder_updateMatches() {
  3831. // Only show matches when all rendering is done.
  3832. if (!this.renderingDone) {
  3833. return;
  3834. }
  3835. // Clear all matches.
  3836. var matches = this.matches;
  3837. var textDivs = this.textDivs;
  3838. var bidiTexts = this.textContent.items;
  3839. var clearedUntilDivIdx = -1;
  3840. // Clear all current matches.
  3841. for (var i = 0, len = matches.length; i < len; i++) {
  3842. var match = matches[i];
  3843. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  3844. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  3845. var div = textDivs[n];
  3846. div.textContent = bidiTexts[n].str;
  3847. div.className = '';
  3848. }
  3849. clearedUntilDivIdx = match.end.divIdx + 1;
  3850. }
  3851. if (this.findController === null || !this.findController.active) {
  3852. return;
  3853. }
  3854. // Convert the matches on the page controller into the match format
  3855. // used for the textLayer.
  3856. this.matches = this.convertMatches(this.findController === null ?
  3857. [] : (this.findController.pageMatches[this.pageIdx] || []));
  3858. this.renderMatches(this.matches);
  3859. },
  3860. /**
  3861. * Fixes text selection: adds additional div where mouse was clicked.
  3862. * This reduces flickering of the content if mouse slowly dragged down/up.
  3863. * @private
  3864. */
  3865. _bindMouse: function TextLayerBuilder_bindMouse() {
  3866. var div = this.textLayerDiv;
  3867. div.addEventListener('mousedown', function (e) {
  3868. var end = div.querySelector('.endOfContent');
  3869. if (!end) {
  3870. return;
  3871. }
  3872. // On non-Firefox browsers, the selection will feel better if the height
  3873. // of the endOfContent div will be adjusted to start at mouse click
  3874. // location -- this will avoid flickering when selections moves up.
  3875. // However it does not work when selection started on empty space.
  3876. var adjustTop = e.target !== div;
  3877. adjustTop = adjustTop && window.getComputedStyle(end).
  3878. getPropertyValue('-moz-user-select') !== 'none';
  3879. if (adjustTop) {
  3880. var divBounds = div.getBoundingClientRect();
  3881. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  3882. end.style.top = (r * 100).toFixed(2) + '%';
  3883. }
  3884. end.classList.add('active');
  3885. });
  3886. div.addEventListener('mouseup', function (e) {
  3887. var end = div.querySelector('.endOfContent');
  3888. if (!end) {
  3889. return;
  3890. }
  3891. end.style.top = '';
  3892. end.classList.remove('active');
  3893. });
  3894. },
  3895. };
  3896. return TextLayerBuilder;
  3897. })();
  3898. /**
  3899. * @constructor
  3900. * @implements IPDFTextLayerFactory
  3901. */
  3902. function DefaultTextLayerFactory() {}
  3903. DefaultTextLayerFactory.prototype = {
  3904. /**
  3905. * @param {HTMLDivElement} textLayerDiv
  3906. * @param {number} pageIndex
  3907. * @param {PageViewport} viewport
  3908. * @returns {TextLayerBuilder}
  3909. */
  3910. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  3911. return new TextLayerBuilder({
  3912. textLayerDiv: textLayerDiv,
  3913. pageIndex: pageIndex,
  3914. viewport: viewport
  3915. });
  3916. }
  3917. };
  3918. /**
  3919. * @typedef {Object} AnnotationLayerBuilderOptions
  3920. * @property {HTMLDivElement} pageDiv
  3921. * @property {PDFPage} pdfPage
  3922. * @property {IPDFLinkService} linkService
  3923. */
  3924. /**
  3925. * @class
  3926. */
  3927. var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
  3928. /**
  3929. * @param {AnnotationLayerBuilderOptions} options
  3930. * @constructs AnnotationLayerBuilder
  3931. */
  3932. function AnnotationLayerBuilder(options) {
  3933. this.pageDiv = options.pageDiv;
  3934. this.pdfPage = options.pdfPage;
  3935. this.linkService = options.linkService;
  3936. this.div = null;
  3937. }
  3938. AnnotationLayerBuilder.prototype =
  3939. /** @lends AnnotationLayerBuilder.prototype */ {
  3940. /**
  3941. * @param {PageViewport} viewport
  3942. * @param {string} intent (default value is 'display')
  3943. */
  3944. render: function AnnotationLayerBuilder_render(viewport, intent) {
  3945. var self = this;
  3946. var parameters = {
  3947. intent: (intent === undefined ? 'display' : intent),
  3948. };
  3949. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  3950. viewport = viewport.clone({ dontFlip: true });
  3951. parameters = {
  3952. viewport: viewport,
  3953. div: self.div,
  3954. annotations: annotations,
  3955. page: self.pdfPage,
  3956. linkService: self.linkService
  3957. };
  3958. if (self.div) {
  3959. // If an annotationLayer already exists, refresh its children's
  3960. // transformation matrices.
  3961. PDFJS.AnnotationLayer.update(parameters);
  3962. } else {
  3963. // Create an annotation layer div and render the annotations
  3964. // if there is at least one annotation.
  3965. if (annotations.length === 0) {
  3966. return;
  3967. }
  3968. self.div = document.createElement('div');
  3969. self.div.className = 'annotationLayer';
  3970. self.pageDiv.appendChild(self.div);
  3971. parameters.div = self.div;
  3972. PDFJS.AnnotationLayer.render(parameters);
  3973. if (typeof mozL10n !== 'undefined') {
  3974. mozL10n.translate(self.div);
  3975. }
  3976. }
  3977. });
  3978. },
  3979. hide: function AnnotationLayerBuilder_hide() {
  3980. if (!this.div) {
  3981. return;
  3982. }
  3983. this.div.setAttribute('hidden', 'true');
  3984. }
  3985. };
  3986. return AnnotationLayerBuilder;
  3987. })();
  3988. /**
  3989. * @constructor
  3990. * @implements IPDFAnnotationLayerFactory
  3991. */
  3992. function DefaultAnnotationLayerFactory() {}
  3993. DefaultAnnotationLayerFactory.prototype = {
  3994. /**
  3995. * @param {HTMLDivElement} pageDiv
  3996. * @param {PDFPage} pdfPage
  3997. * @returns {AnnotationLayerBuilder}
  3998. */
  3999. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  4000. return new AnnotationLayerBuilder({
  4001. pageDiv: pageDiv,
  4002. pdfPage: pdfPage,
  4003. linkService: new SimpleLinkService(),
  4004. });
  4005. }
  4006. };
  4007. /**
  4008. * @typedef {Object} PDFViewerOptions
  4009. * @property {HTMLDivElement} container - The container for the viewer element.
  4010. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  4011. * @property {IPDFLinkService} linkService - The navigation/linking service.
  4012. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  4013. * queue object.
  4014. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  4015. * around the pages. The default is false.
  4016. */
  4017. /**
  4018. * Simple viewer control to display PDF content/pages.
  4019. * @class
  4020. * @implements {IRenderableView}
  4021. */
  4022. var PDFViewer = (function pdfViewer() {
  4023. function PDFPageViewBuffer(size) {
  4024. var data = [];
  4025. this.push = function cachePush(view) {
  4026. var i = data.indexOf(view);
  4027. if (i >= 0) {
  4028. data.splice(i, 1);
  4029. }
  4030. data.push(view);
  4031. if (data.length > size) {
  4032. data.shift().destroy();
  4033. }
  4034. };
  4035. this.resize = function (newSize) {
  4036. size = newSize;
  4037. while (data.length > size) {
  4038. data.shift().destroy();
  4039. }
  4040. };
  4041. }
  4042. function isSameScale(oldScale, newScale) {
  4043. if (newScale === oldScale) {
  4044. return true;
  4045. }
  4046. if (Math.abs(newScale - oldScale) < 1e-15) {
  4047. // Prevent unnecessary re-rendering of all pages when the scale
  4048. // changes only because of limited numerical precision.
  4049. return true;
  4050. }
  4051. return false;
  4052. }
  4053. /**
  4054. * @constructs PDFViewer
  4055. * @param {PDFViewerOptions} options
  4056. */
  4057. function PDFViewer(options) {
  4058. this.container = options.container;
  4059. this.viewer = options.viewer || options.container.firstElementChild;
  4060. this.linkService = options.linkService || new SimpleLinkService();
  4061. this.removePageBorders = options.removePageBorders || false;
  4062. this.defaultRenderingQueue = !options.renderingQueue;
  4063. if (this.defaultRenderingQueue) {
  4064. // Custom rendering queue is not specified, using default one
  4065. this.renderingQueue = new PDFRenderingQueue();
  4066. this.renderingQueue.setViewer(this);
  4067. } else {
  4068. this.renderingQueue = options.renderingQueue;
  4069. }
  4070. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  4071. this.updateInProgress = false;
  4072. this.presentationModeState = PresentationModeState.UNKNOWN;
  4073. this._resetView();
  4074. if (this.removePageBorders) {
  4075. this.viewer.classList.add('removePageBorders');
  4076. }
  4077. }
  4078. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  4079. get pagesCount() {
  4080. return this._pages.length;
  4081. },
  4082. getPageView: function (index) {
  4083. return this._pages[index];
  4084. },
  4085. get currentPageNumber() {
  4086. return this._currentPageNumber;
  4087. },
  4088. set currentPageNumber(val) {
  4089. if (!this.pdfDocument) {
  4090. this._currentPageNumber = val;
  4091. return;
  4092. }
  4093. var event = document.createEvent('UIEvents');
  4094. event.initUIEvent('pagechange', true, true, window, 0);
  4095. event.updateInProgress = this.updateInProgress;
  4096. if (!(0 < val && val <= this.pagesCount)) {
  4097. event.pageNumber = this._currentPageNumber;
  4098. event.previousPageNumber = val;
  4099. this.container.dispatchEvent(event);
  4100. return;
  4101. }
  4102. event.previousPageNumber = this._currentPageNumber;
  4103. this._currentPageNumber = val;
  4104. event.pageNumber = val;
  4105. this.container.dispatchEvent(event);
  4106. // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
  4107. if (this.updateInProgress) {
  4108. return;
  4109. }
  4110. this.scrollPageIntoView(val);
  4111. },
  4112. /**
  4113. * @returns {number}
  4114. */
  4115. get currentScale() {
  4116. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  4117. DEFAULT_SCALE;
  4118. },
  4119. /**
  4120. * @param {number} val - Scale of the pages in percents.
  4121. */
  4122. set currentScale(val) {
  4123. if (isNaN(val)) {
  4124. throw new Error('Invalid numeric scale');
  4125. }
  4126. if (!this.pdfDocument) {
  4127. this._currentScale = val;
  4128. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  4129. return;
  4130. }
  4131. this._setScale(val, false);
  4132. },
  4133. /**
  4134. * @returns {string}
  4135. */
  4136. get currentScaleValue() {
  4137. return this._currentScaleValue;
  4138. },
  4139. /**
  4140. * @param val - The scale of the pages (in percent or predefined value).
  4141. */
  4142. set currentScaleValue(val) {
  4143. if (!this.pdfDocument) {
  4144. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  4145. this._currentScaleValue = val;
  4146. return;
  4147. }
  4148. this._setScale(val, false);
  4149. },
  4150. /**
  4151. * @returns {number}
  4152. */
  4153. get pagesRotation() {
  4154. return this._pagesRotation;
  4155. },
  4156. /**
  4157. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  4158. */
  4159. set pagesRotation(rotation) {
  4160. this._pagesRotation = rotation;
  4161. for (var i = 0, l = this._pages.length; i < l; i++) {
  4162. var pageView = this._pages[i];
  4163. pageView.update(pageView.scale, rotation);
  4164. }
  4165. this._setScale(this._currentScaleValue, true);
  4166. if (this.defaultRenderingQueue) {
  4167. this.update();
  4168. }
  4169. },
  4170. /**
  4171. * @param pdfDocument {PDFDocument}
  4172. */
  4173. setDocument: function (pdfDocument) {
  4174. if (this.pdfDocument) {
  4175. this._resetView();
  4176. }
  4177. this.pdfDocument = pdfDocument;
  4178. if (!pdfDocument) {
  4179. return;
  4180. }
  4181. var pagesCount = pdfDocument.numPages;
  4182. var self = this;
  4183. var resolvePagesPromise;
  4184. var pagesPromise = new Promise(function (resolve) {
  4185. resolvePagesPromise = resolve;
  4186. });
  4187. this.pagesPromise = pagesPromise;
  4188. pagesPromise.then(function () {
  4189. var event = document.createEvent('CustomEvent');
  4190. event.initCustomEvent('pagesloaded', true, true, {
  4191. pagesCount: pagesCount
  4192. });
  4193. self.container.dispatchEvent(event);
  4194. });
  4195. var isOnePageRenderedResolved = false;
  4196. var resolveOnePageRendered = null;
  4197. var onePageRendered = new Promise(function (resolve) {
  4198. resolveOnePageRendered = resolve;
  4199. });
  4200. this.onePageRendered = onePageRendered;
  4201. var bindOnAfterAndBeforeDraw = function (pageView) {
  4202. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  4203. // Add the page to the buffer at the start of drawing. That way it can
  4204. // be evicted from the buffer and destroyed even if we pause its
  4205. // rendering.
  4206. self._buffer.push(this);
  4207. };
  4208. // when page is painted, using the image as thumbnail base
  4209. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  4210. if (!isOnePageRenderedResolved) {
  4211. isOnePageRenderedResolved = true;
  4212. resolveOnePageRendered();
  4213. }
  4214. };
  4215. };
  4216. var firstPagePromise = pdfDocument.getPage(1);
  4217. this.firstPagePromise = firstPagePromise;
  4218. // Fetch a single page so we can get a viewport that will be the default
  4219. // viewport for all pages
  4220. return firstPagePromise.then(function(pdfPage) {
  4221. var scale = this.currentScale;
  4222. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  4223. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  4224. var textLayerFactory = null;
  4225. if (!PDFJS.disableTextLayer) {
  4226. textLayerFactory = this;
  4227. }
  4228. var pageView = new PDFPageView({
  4229. container: this.viewer,
  4230. id: pageNum,
  4231. scale: scale,
  4232. defaultViewport: viewport.clone(),
  4233. renderingQueue: this.renderingQueue,
  4234. textLayerFactory: textLayerFactory,
  4235. annotationLayerFactory: this
  4236. });
  4237. bindOnAfterAndBeforeDraw(pageView);
  4238. this._pages.push(pageView);
  4239. }
  4240. var linkService = this.linkService;
  4241. // Fetch all the pages since the viewport is needed before printing
  4242. // starts to create the correct size canvas. Wait until one page is
  4243. // rendered so we don't tie up too many resources early on.
  4244. onePageRendered.then(function () {
  4245. if (!PDFJS.disableAutoFetch) {
  4246. var getPagesLeft = pagesCount;
  4247. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  4248. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  4249. var pageView = self._pages[pageNum - 1];
  4250. if (!pageView.pdfPage) {
  4251. pageView.setPdfPage(pdfPage);
  4252. }
  4253. linkService.cachePageRef(pageNum, pdfPage.ref);
  4254. getPagesLeft--;
  4255. if (!getPagesLeft) {
  4256. resolvePagesPromise();
  4257. }
  4258. }.bind(null, pageNum));
  4259. }
  4260. } else {
  4261. // XXX: Printing is semi-broken with auto fetch disabled.
  4262. resolvePagesPromise();
  4263. }
  4264. });
  4265. var event = document.createEvent('CustomEvent');
  4266. event.initCustomEvent('pagesinit', true, true, null);
  4267. self.container.dispatchEvent(event);
  4268. if (this.defaultRenderingQueue) {
  4269. this.update();
  4270. }
  4271. if (this.findController) {
  4272. this.findController.resolveFirstPage();
  4273. }
  4274. }.bind(this));
  4275. },
  4276. _resetView: function () {
  4277. this._pages = [];
  4278. this._currentPageNumber = 1;
  4279. this._currentScale = UNKNOWN_SCALE;
  4280. this._currentScaleValue = null;
  4281. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  4282. this._location = null;
  4283. this._pagesRotation = 0;
  4284. this._pagesRequests = [];
  4285. var container = this.viewer;
  4286. while (container.hasChildNodes()) {
  4287. container.removeChild(container.lastChild);
  4288. }
  4289. },
  4290. _scrollUpdate: function PDFViewer_scrollUpdate() {
  4291. if (this.pagesCount === 0) {
  4292. return;
  4293. }
  4294. this.update();
  4295. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  4296. this._pages[i].updatePosition();
  4297. }
  4298. },
  4299. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  4300. newScale, newValue, preset) {
  4301. var event = document.createEvent('UIEvents');
  4302. event.initUIEvent('scalechange', true, true, window, 0);
  4303. event.scale = newScale;
  4304. if (preset) {
  4305. event.presetValue = newValue;
  4306. }
  4307. this.container.dispatchEvent(event);
  4308. },
  4309. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  4310. newScale, newValue, noScroll, preset) {
  4311. this._currentScaleValue = newValue;
  4312. if (isSameScale(this._currentScale, newScale)) {
  4313. if (preset) {
  4314. this._setScaleDispatchEvent(newScale, newValue, true);
  4315. }
  4316. return;
  4317. }
  4318. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  4319. this._pages[i].update(newScale);
  4320. }
  4321. this._currentScale = newScale;
  4322. if (!noScroll) {
  4323. var page = this._currentPageNumber, dest;
  4324. if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
  4325. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  4326. page = this._location.pageNumber;
  4327. dest = [null, { name: 'XYZ' }, this._location.left,
  4328. this._location.top, null];
  4329. }
  4330. this.scrollPageIntoView(page, dest);
  4331. }
  4332. this._setScaleDispatchEvent(newScale, newValue, preset);
  4333. if (this.defaultRenderingQueue) {
  4334. this.update();
  4335. }
  4336. },
  4337. _setScale: function pdfViewer_setScale(value, noScroll) {
  4338. var scale = parseFloat(value);
  4339. if (scale > 0) {
  4340. this._setScaleUpdatePages(scale, value, noScroll, false);
  4341. } else {
  4342. var currentPage = this._pages[this._currentPageNumber - 1];
  4343. if (!currentPage) {
  4344. return;
  4345. }
  4346. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  4347. 0 : SCROLLBAR_PADDING;
  4348. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  4349. 0 : VERTICAL_PADDING;
  4350. var pageWidthScale = (this.container.clientWidth - hPadding) /
  4351. currentPage.width * currentPage.scale;
  4352. var pageHeightScale = (this.container.clientHeight - vPadding) /
  4353. currentPage.height * currentPage.scale;
  4354. switch (value) {
  4355. case 'page-actual':
  4356. scale = 1;
  4357. break;
  4358. case 'page-width':
  4359. scale = pageWidthScale;
  4360. break;
  4361. case 'page-height':
  4362. scale = pageHeightScale;
  4363. break;
  4364. case 'page-fit':
  4365. scale = Math.min(pageWidthScale, pageHeightScale);
  4366. break;
  4367. case 'auto':
  4368. var isLandscape = (currentPage.width > currentPage.height);
  4369. // For pages in landscape mode, fit the page height to the viewer
  4370. // *unless* the page would thus become too wide to fit horizontally.
  4371. var horizontalScale = isLandscape ?
  4372. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  4373. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  4374. break;
  4375. default:
  4376. console.error('pdfViewSetScale: \'' + value +
  4377. '\' is an unknown zoom value.');
  4378. return;
  4379. }
  4380. this._setScaleUpdatePages(scale, value, noScroll, true);
  4381. }
  4382. },
  4383. /**
  4384. * Scrolls page into view.
  4385. * @param {number} pageNumber
  4386. * @param {Array} dest - (optional) original PDF destination array:
  4387. * <page-ref> </XYZ|FitXXX> <args..>
  4388. */
  4389. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  4390. dest) {
  4391. if (!this.pdfDocument) {
  4392. return;
  4393. }
  4394. var pageView = this._pages[pageNumber - 1];
  4395. if (this.isInPresentationMode) {
  4396. if (this._currentPageNumber !== pageView.id) {
  4397. // Avoid breaking getVisiblePages in presentation mode.
  4398. this.currentPageNumber = pageView.id;
  4399. return;
  4400. }
  4401. dest = null;
  4402. // Fixes the case when PDF has different page sizes.
  4403. this._setScale(this._currentScaleValue, true);
  4404. }
  4405. if (!dest) {
  4406. scrollIntoView(pageView.div);
  4407. return;
  4408. }
  4409. var x = 0, y = 0;
  4410. var width = 0, height = 0, widthScale, heightScale;
  4411. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  4412. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  4413. pageView.scale / CSS_UNITS;
  4414. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  4415. pageView.scale / CSS_UNITS;
  4416. var scale = 0;
  4417. switch (dest[1].name) {
  4418. case 'XYZ':
  4419. x = dest[2];
  4420. y = dest[3];
  4421. scale = dest[4];
  4422. // If x and/or y coordinates are not supplied, default to
  4423. // _top_ left of the page (not the obvious bottom left,
  4424. // since aligning the bottom of the intended page with the
  4425. // top of the window is rarely helpful).
  4426. x = x !== null ? x : 0;
  4427. y = y !== null ? y : pageHeight;
  4428. break;
  4429. case 'Fit':
  4430. case 'FitB':
  4431. scale = 'page-fit';
  4432. break;
  4433. case 'FitH':
  4434. case 'FitBH':
  4435. y = dest[2];
  4436. scale = 'page-width';
  4437. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  4438. // parameter should maintain the position relative to the new page.
  4439. if (y === null && this._location) {
  4440. x = this._location.left;
  4441. y = this._location.top;
  4442. }
  4443. break;
  4444. case 'FitV':
  4445. case 'FitBV':
  4446. x = dest[2];
  4447. width = pageWidth;
  4448. height = pageHeight;
  4449. scale = 'page-height';
  4450. break;
  4451. case 'FitR':
  4452. x = dest[2];
  4453. y = dest[3];
  4454. width = dest[4] - x;
  4455. height = dest[5] - y;
  4456. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  4457. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  4458. widthScale = (this.container.clientWidth - hPadding) /
  4459. width / CSS_UNITS;
  4460. heightScale = (this.container.clientHeight - vPadding) /
  4461. height / CSS_UNITS;
  4462. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  4463. break;
  4464. default:
  4465. return;
  4466. }
  4467. if (scale && scale !== this._currentScale) {
  4468. this.currentScaleValue = scale;
  4469. } else if (this._currentScale === UNKNOWN_SCALE) {
  4470. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  4471. }
  4472. if (scale === 'page-fit' && !dest[4]) {
  4473. scrollIntoView(pageView.div);
  4474. return;
  4475. }
  4476. var boundingRect = [
  4477. pageView.viewport.convertToViewportPoint(x, y),
  4478. pageView.viewport.convertToViewportPoint(x + width, y + height)
  4479. ];
  4480. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  4481. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  4482. scrollIntoView(pageView.div, { left: left, top: top });
  4483. },
  4484. _updateLocation: function (firstPage) {
  4485. var currentScale = this._currentScale;
  4486. var currentScaleValue = this._currentScaleValue;
  4487. var normalizedScaleValue =
  4488. parseFloat(currentScaleValue) === currentScale ?
  4489. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  4490. var pageNumber = firstPage.id;
  4491. var pdfOpenParams = '#page=' + pageNumber;
  4492. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  4493. var currentPageView = this._pages[pageNumber - 1];
  4494. var container = this.container;
  4495. var topLeft = currentPageView.getPagePoint(
  4496. (container.scrollLeft - firstPage.x),
  4497. (container.scrollTop - firstPage.y));
  4498. var intLeft = Math.round(topLeft[0]);
  4499. var intTop = Math.round(topLeft[1]);
  4500. pdfOpenParams += ',' + intLeft + ',' + intTop;
  4501. this._location = {
  4502. pageNumber: pageNumber,
  4503. scale: normalizedScaleValue,
  4504. top: intTop,
  4505. left: intLeft,
  4506. pdfOpenParams: pdfOpenParams
  4507. };
  4508. },
  4509. update: function PDFViewer_update() {
  4510. var visible = this._getVisiblePages();
  4511. var visiblePages = visible.views;
  4512. if (visiblePages.length === 0) {
  4513. return;
  4514. }
  4515. this.updateInProgress = true;
  4516. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  4517. 2 * visiblePages.length + 1);
  4518. this._buffer.resize(suggestedCacheSize);
  4519. this.renderingQueue.renderHighestPriority(visible);
  4520. var currentId = this._currentPageNumber;
  4521. var firstPage = visible.first;
  4522. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  4523. i < ii; ++i) {
  4524. var page = visiblePages[i];
  4525. if (page.percent < 100) {
  4526. break;
  4527. }
  4528. if (page.id === currentId) {
  4529. stillFullyVisible = true;
  4530. break;
  4531. }
  4532. }
  4533. if (!stillFullyVisible) {
  4534. currentId = visiblePages[0].id;
  4535. }
  4536. if (!this.isInPresentationMode) {
  4537. this.currentPageNumber = currentId;
  4538. }
  4539. this._updateLocation(firstPage);
  4540. this.updateInProgress = false;
  4541. var event = document.createEvent('UIEvents');
  4542. event.initUIEvent('updateviewarea', true, true, window, 0);
  4543. event.location = this._location;
  4544. this.container.dispatchEvent(event);
  4545. },
  4546. containsElement: function (element) {
  4547. return this.container.contains(element);
  4548. },
  4549. focus: function () {
  4550. this.container.focus();
  4551. },
  4552. get isInPresentationMode() {
  4553. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  4554. },
  4555. get isChangingPresentationMode() {
  4556. return this.presentationModeState === PresentationModeState.CHANGING;
  4557. },
  4558. get isHorizontalScrollbarEnabled() {
  4559. return (this.isInPresentationMode ?
  4560. false : (this.container.scrollWidth > this.container.clientWidth));
  4561. },
  4562. _getVisiblePages: function () {
  4563. if (!this.isInPresentationMode) {
  4564. return getVisibleElements(this.container, this._pages, true);
  4565. } else {
  4566. // The algorithm in getVisibleElements doesn't work in all browsers and
  4567. // configurations when presentation mode is active.
  4568. var visible = [];
  4569. var currentPage = this._pages[this._currentPageNumber - 1];
  4570. visible.push({ id: currentPage.id, view: currentPage });
  4571. return { first: currentPage, last: currentPage, views: visible };
  4572. }
  4573. },
  4574. cleanup: function () {
  4575. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  4576. if (this._pages[i] &&
  4577. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  4578. this._pages[i].reset();
  4579. }
  4580. }
  4581. },
  4582. /**
  4583. * @param {PDFPageView} pageView
  4584. * @returns {PDFPage}
  4585. * @private
  4586. */
  4587. _ensurePdfPageLoaded: function (pageView) {
  4588. if (pageView.pdfPage) {
  4589. return Promise.resolve(pageView.pdfPage);
  4590. }
  4591. var pageNumber = pageView.id;
  4592. if (this._pagesRequests[pageNumber]) {
  4593. return this._pagesRequests[pageNumber];
  4594. }
  4595. var promise = this.pdfDocument.getPage(pageNumber).then(
  4596. function (pdfPage) {
  4597. pageView.setPdfPage(pdfPage);
  4598. this._pagesRequests[pageNumber] = null;
  4599. return pdfPage;
  4600. }.bind(this));
  4601. this._pagesRequests[pageNumber] = promise;
  4602. return promise;
  4603. },
  4604. forceRendering: function (currentlyVisiblePages) {
  4605. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  4606. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  4607. this._pages,
  4608. this.scroll.down);
  4609. if (pageView) {
  4610. this._ensurePdfPageLoaded(pageView).then(function () {
  4611. this.renderingQueue.renderView(pageView);
  4612. }.bind(this));
  4613. return true;
  4614. }
  4615. return false;
  4616. },
  4617. getPageTextContent: function (pageIndex) {
  4618. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  4619. return page.getTextContent({ normalizeWhitespace: true });
  4620. });
  4621. },
  4622. /**
  4623. * @param {HTMLDivElement} textLayerDiv
  4624. * @param {number} pageIndex
  4625. * @param {PageViewport} viewport
  4626. * @returns {TextLayerBuilder}
  4627. */
  4628. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  4629. return new TextLayerBuilder({
  4630. textLayerDiv: textLayerDiv,
  4631. pageIndex: pageIndex,
  4632. viewport: viewport,
  4633. findController: this.isInPresentationMode ? null : this.findController
  4634. });
  4635. },
  4636. /**
  4637. * @param {HTMLDivElement} pageDiv
  4638. * @param {PDFPage} pdfPage
  4639. * @returns {AnnotationLayerBuilder}
  4640. */
  4641. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  4642. return new AnnotationLayerBuilder({
  4643. pageDiv: pageDiv,
  4644. pdfPage: pdfPage,
  4645. linkService: this.linkService
  4646. });
  4647. },
  4648. setFindController: function (findController) {
  4649. this.findController = findController;
  4650. },
  4651. };
  4652. return PDFViewer;
  4653. })();
  4654. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  4655. function SimpleLinkService() {}
  4656. SimpleLinkService.prototype = {
  4657. /**
  4658. * @returns {number}
  4659. */
  4660. get page() {
  4661. return 0;
  4662. },
  4663. /**
  4664. * @param {number} value
  4665. */
  4666. set page(value) {},
  4667. /**
  4668. * @param dest - The PDF destination object.
  4669. */
  4670. navigateTo: function (dest) {},
  4671. /**
  4672. * @param dest - The PDF destination object.
  4673. * @returns {string} The hyperlink to the PDF object.
  4674. */
  4675. getDestinationHash: function (dest) {
  4676. return '#';
  4677. },
  4678. /**
  4679. * @param hash - The PDF parameters/hash.
  4680. * @returns {string} The hyperlink to the PDF object.
  4681. */
  4682. getAnchorUrl: function (hash) {
  4683. return '#';
  4684. },
  4685. /**
  4686. * @param {string} hash
  4687. */
  4688. setHash: function (hash) {},
  4689. /**
  4690. * @param {string} action
  4691. */
  4692. executeNamedAction: function (action) {},
  4693. /**
  4694. * @param {number} pageNum - page number.
  4695. * @param {Object} pageRef - reference to the page.
  4696. */
  4697. cachePageRef: function (pageNum, pageRef) {}
  4698. };
  4699. return SimpleLinkService;
  4700. })();
  4701. var THUMBNAIL_SCROLL_MARGIN = -19;
  4702. var THUMBNAIL_WIDTH = 98; // px
  4703. var THUMBNAIL_CANVAS_BORDER_WIDTH = 1; // px
  4704. /**
  4705. * @typedef {Object} PDFThumbnailViewOptions
  4706. * @property {HTMLDivElement} container - The viewer element.
  4707. * @property {number} id - The thumbnail's unique ID (normally its number).
  4708. * @property {PageViewport} defaultViewport - The page viewport.
  4709. * @property {IPDFLinkService} linkService - The navigation/linking service.
  4710. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  4711. */
  4712. /**
  4713. * @class
  4714. * @implements {IRenderableView}
  4715. */
  4716. var PDFThumbnailView = (function PDFThumbnailViewClosure() {
  4717. function getTempCanvas(width, height) {
  4718. var tempCanvas = PDFThumbnailView.tempImageCache;
  4719. if (!tempCanvas) {
  4720. tempCanvas = document.createElement('canvas');
  4721. PDFThumbnailView.tempImageCache = tempCanvas;
  4722. }
  4723. tempCanvas.width = width;
  4724. tempCanvas.height = height;
  4725. // Since this is a temporary canvas, we need to fill the canvas with a white
  4726. // background ourselves. |_getPageDrawContext| uses CSS rules for this.
  4727. tempCanvas.mozOpaque = true;
  4728. var ctx = tempCanvas.getContext('2d', {alpha: false});
  4729. ctx.save();
  4730. ctx.fillStyle = 'rgb(255, 255, 255)';
  4731. ctx.fillRect(0, 0, width, height);
  4732. ctx.restore();
  4733. return tempCanvas;
  4734. }
  4735. /**
  4736. * @constructs PDFThumbnailView
  4737. * @param {PDFThumbnailViewOptions} options
  4738. */
  4739. function PDFThumbnailView(options) {
  4740. var container = options.container;
  4741. var id = options.id;
  4742. var defaultViewport = options.defaultViewport;
  4743. var linkService = options.linkService;
  4744. var renderingQueue = options.renderingQueue;
  4745. this.id = id;
  4746. this.renderingId = 'thumbnail' + id;
  4747. this.pdfPage = null;
  4748. this.rotation = 0;
  4749. this.viewport = defaultViewport;
  4750. this.pdfPageRotate = defaultViewport.rotation;
  4751. this.linkService = linkService;
  4752. this.renderingQueue = renderingQueue;
  4753. this.hasImage = false;
  4754. this.resume = null;
  4755. this.renderingState = RenderingStates.INITIAL;
  4756. this.pageWidth = this.viewport.width;
  4757. this.pageHeight = this.viewport.height;
  4758. this.pageRatio = this.pageWidth / this.pageHeight;
  4759. this.canvasWidth = THUMBNAIL_WIDTH;
  4760. this.canvasHeight = (this.canvasWidth / this.pageRatio) | 0;
  4761. this.scale = this.canvasWidth / this.pageWidth;
  4762. var anchor = document.createElement('a');
  4763. anchor.href = linkService.getAnchorUrl('#page=' + id);
  4764. anchor.title = mozL10n.get('thumb_page_title', {page: id}, 'Page {{page}}');
  4765. anchor.onclick = function stopNavigation() {
  4766. linkService.page = id;
  4767. return false;
  4768. };
  4769. var div = document.createElement('div');
  4770. div.id = 'thumbnailContainer' + id;
  4771. div.className = 'thumbnail';
  4772. this.div = div;
  4773. if (id === 1) {
  4774. // Highlight the thumbnail of the first page when no page number is
  4775. // specified (or exists in cache) when the document is loaded.
  4776. div.classList.add('selected');
  4777. }
  4778. var ring = document.createElement('div');
  4779. ring.className = 'thumbnailSelectionRing';
  4780. var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
  4781. ring.style.width = this.canvasWidth + borderAdjustment + 'px';
  4782. ring.style.height = this.canvasHeight + borderAdjustment + 'px';
  4783. this.ring = ring;
  4784. div.appendChild(ring);
  4785. anchor.appendChild(div);
  4786. container.appendChild(anchor);
  4787. }
  4788. PDFThumbnailView.prototype = {
  4789. setPdfPage: function PDFThumbnailView_setPdfPage(pdfPage) {
  4790. this.pdfPage = pdfPage;
  4791. this.pdfPageRotate = pdfPage.rotate;
  4792. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  4793. this.viewport = pdfPage.getViewport(1, totalRotation);
  4794. this.reset();
  4795. },
  4796. reset: function PDFThumbnailView_reset() {
  4797. if (this.renderTask) {
  4798. this.renderTask.cancel();
  4799. }
  4800. this.hasImage = false;
  4801. this.resume = null;
  4802. this.renderingState = RenderingStates.INITIAL;
  4803. this.pageWidth = this.viewport.width;
  4804. this.pageHeight = this.viewport.height;
  4805. this.pageRatio = this.pageWidth / this.pageHeight;
  4806. this.canvasHeight = (this.canvasWidth / this.pageRatio) | 0;
  4807. this.scale = (this.canvasWidth / this.pageWidth);
  4808. this.div.removeAttribute('data-loaded');
  4809. var ring = this.ring;
  4810. var childNodes = ring.childNodes;
  4811. for (var i = childNodes.length - 1; i >= 0; i--) {
  4812. ring.removeChild(childNodes[i]);
  4813. }
  4814. var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
  4815. ring.style.width = this.canvasWidth + borderAdjustment + 'px';
  4816. ring.style.height = this.canvasHeight + borderAdjustment + 'px';
  4817. if (this.canvas) {
  4818. // Zeroing the width and height causes Firefox to release graphics
  4819. // resources immediately, which can greatly reduce memory consumption.
  4820. this.canvas.width = 0;
  4821. this.canvas.height = 0;
  4822. delete this.canvas;
  4823. }
  4824. if (this.image) {
  4825. this.image.removeAttribute('src');
  4826. delete this.image;
  4827. }
  4828. },
  4829. update: function PDFThumbnailView_update(rotation) {
  4830. if (typeof rotation !== 'undefined') {
  4831. this.rotation = rotation;
  4832. }
  4833. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  4834. this.viewport = this.viewport.clone({
  4835. scale: 1,
  4836. rotation: totalRotation
  4837. });
  4838. this.reset();
  4839. },
  4840. /**
  4841. * @private
  4842. */
  4843. _getPageDrawContext:
  4844. function PDFThumbnailView_getPageDrawContext(noCtxScale) {
  4845. var canvas = document.createElement('canvas');
  4846. this.canvas = canvas;
  4847. canvas.mozOpaque = true;
  4848. var ctx = canvas.getContext('2d', {alpha: false});
  4849. var outputScale = getOutputScale(ctx);
  4850. canvas.width = (this.canvasWidth * outputScale.sx) | 0;
  4851. canvas.height = (this.canvasHeight * outputScale.sy) | 0;
  4852. canvas.style.width = this.canvasWidth + 'px';
  4853. canvas.style.height = this.canvasHeight + 'px';
  4854. if (!noCtxScale && outputScale.scaled) {
  4855. ctx.scale(outputScale.sx, outputScale.sy);
  4856. }
  4857. var image = document.createElement('img');
  4858. this.image = image;
  4859. image.id = this.renderingId;
  4860. image.className = 'thumbnailImage';
  4861. image.setAttribute('aria-label', mozL10n.get('thumb_page_canvas',
  4862. { page: this.id }, 'Thumbnail of Page {{page}}'));
  4863. image.style.width = canvas.style.width;
  4864. image.style.height = canvas.style.height;
  4865. return ctx;
  4866. },
  4867. /**
  4868. * @private
  4869. */
  4870. _convertCanvasToImage: function PDFThumbnailView_convertCanvasToImage() {
  4871. if (!this.canvas) {
  4872. return;
  4873. }
  4874. this.image.src = this.canvas.toDataURL();
  4875. this.div.setAttribute('data-loaded', true);
  4876. this.ring.appendChild(this.image);
  4877. // Zeroing the width and height causes Firefox to release graphics
  4878. // resources immediately, which can greatly reduce memory consumption.
  4879. this.canvas.width = 0;
  4880. this.canvas.height = 0;
  4881. delete this.canvas;
  4882. },
  4883. draw: function PDFThumbnailView_draw() {
  4884. if (this.renderingState !== RenderingStates.INITIAL) {
  4885. console.error('Must be in new state before drawing');
  4886. }
  4887. if (this.hasImage) {
  4888. return Promise.resolve(undefined);
  4889. }
  4890. this.hasImage = true;
  4891. this.renderingState = RenderingStates.RUNNING;
  4892. var resolveRenderPromise, rejectRenderPromise;
  4893. var promise = new Promise(function (resolve, reject) {
  4894. resolveRenderPromise = resolve;
  4895. rejectRenderPromise = reject;
  4896. });
  4897. var self = this;
  4898. function thumbnailDrawCallback(error) {
  4899. // The renderTask may have been replaced by a new one, so only remove
  4900. // the reference to the renderTask if it matches the one that is
  4901. // triggering this callback.
  4902. if (renderTask === self.renderTask) {
  4903. self.renderTask = null;
  4904. }
  4905. if (error === 'cancelled') {
  4906. rejectRenderPromise(error);
  4907. return;
  4908. }
  4909. self.renderingState = RenderingStates.FINISHED;
  4910. self._convertCanvasToImage();
  4911. if (!error) {
  4912. resolveRenderPromise(undefined);
  4913. } else {
  4914. rejectRenderPromise(error);
  4915. }
  4916. }
  4917. var ctx = this._getPageDrawContext();
  4918. var drawViewport = this.viewport.clone({ scale: this.scale });
  4919. var renderContinueCallback = function renderContinueCallback(cont) {
  4920. if (!self.renderingQueue.isHighestPriority(self)) {
  4921. self.renderingState = RenderingStates.PAUSED;
  4922. self.resume = function resumeCallback() {
  4923. self.renderingState = RenderingStates.RUNNING;
  4924. cont();
  4925. };
  4926. return;
  4927. }
  4928. cont();
  4929. };
  4930. var renderContext = {
  4931. canvasContext: ctx,
  4932. viewport: drawViewport
  4933. };
  4934. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  4935. renderTask.onContinue = renderContinueCallback;
  4936. renderTask.promise.then(
  4937. function pdfPageRenderCallback() {
  4938. thumbnailDrawCallback(null);
  4939. },
  4940. function pdfPageRenderError(error) {
  4941. thumbnailDrawCallback(error);
  4942. }
  4943. );
  4944. return promise;
  4945. },
  4946. setImage: function PDFThumbnailView_setImage(pageView) {
  4947. var img = pageView.canvas;
  4948. if (this.hasImage || !img) {
  4949. return;
  4950. }
  4951. if (!this.pdfPage) {
  4952. this.setPdfPage(pageView.pdfPage);
  4953. }
  4954. this.hasImage = true;
  4955. this.renderingState = RenderingStates.FINISHED;
  4956. var ctx = this._getPageDrawContext(true);
  4957. var canvas = ctx.canvas;
  4958. if (img.width <= 2 * canvas.width) {
  4959. ctx.drawImage(img, 0, 0, img.width, img.height,
  4960. 0, 0, canvas.width, canvas.height);
  4961. this._convertCanvasToImage();
  4962. return;
  4963. }
  4964. // drawImage does an awful job of rescaling the image, doing it gradually.
  4965. var MAX_NUM_SCALING_STEPS = 3;
  4966. var reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
  4967. var reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
  4968. var reducedImage = getTempCanvas(reducedWidth, reducedHeight);
  4969. var reducedImageCtx = reducedImage.getContext('2d');
  4970. while (reducedWidth > img.width || reducedHeight > img.height) {
  4971. reducedWidth >>= 1;
  4972. reducedHeight >>= 1;
  4973. }
  4974. reducedImageCtx.drawImage(img, 0, 0, img.width, img.height,
  4975. 0, 0, reducedWidth, reducedHeight);
  4976. while (reducedWidth > 2 * canvas.width) {
  4977. reducedImageCtx.drawImage(reducedImage,
  4978. 0, 0, reducedWidth, reducedHeight,
  4979. 0, 0, reducedWidth >> 1, reducedHeight >> 1);
  4980. reducedWidth >>= 1;
  4981. reducedHeight >>= 1;
  4982. }
  4983. ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight,
  4984. 0, 0, canvas.width, canvas.height);
  4985. this._convertCanvasToImage();
  4986. }
  4987. };
  4988. return PDFThumbnailView;
  4989. })();
  4990. PDFThumbnailView.tempImageCache = null;
  4991. /**
  4992. * @typedef {Object} PDFThumbnailViewerOptions
  4993. * @property {HTMLDivElement} container - The container for the thumbnail
  4994. * elements.
  4995. * @property {IPDFLinkService} linkService - The navigation/linking service.
  4996. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  4997. */
  4998. /**
  4999. * Simple viewer control to display thumbnails for pages.
  5000. * @class
  5001. * @implements {IRenderableView}
  5002. */
  5003. var PDFThumbnailViewer = (function PDFThumbnailViewerClosure() {
  5004. /**
  5005. * @constructs PDFThumbnailViewer
  5006. * @param {PDFThumbnailViewerOptions} options
  5007. */
  5008. function PDFThumbnailViewer(options) {
  5009. this.container = options.container;
  5010. this.renderingQueue = options.renderingQueue;
  5011. this.linkService = options.linkService;
  5012. this.scroll = watchScroll(this.container, this._scrollUpdated.bind(this));
  5013. this._resetView();
  5014. }
  5015. PDFThumbnailViewer.prototype = {
  5016. /**
  5017. * @private
  5018. */
  5019. _scrollUpdated: function PDFThumbnailViewer_scrollUpdated() {
  5020. this.renderingQueue.renderHighestPriority();
  5021. },
  5022. getThumbnail: function PDFThumbnailViewer_getThumbnail(index) {
  5023. return this.thumbnails[index];
  5024. },
  5025. /**
  5026. * @private
  5027. */
  5028. _getVisibleThumbs: function PDFThumbnailViewer_getVisibleThumbs() {
  5029. return getVisibleElements(this.container, this.thumbnails);
  5030. },
  5031. scrollThumbnailIntoView:
  5032. function PDFThumbnailViewer_scrollThumbnailIntoView(page) {
  5033. var selected = document.querySelector('.thumbnail.selected');
  5034. if (selected) {
  5035. selected.classList.remove('selected');
  5036. }
  5037. var thumbnail = document.getElementById('thumbnailContainer' + page);
  5038. if (thumbnail) {
  5039. thumbnail.classList.add('selected');
  5040. }
  5041. var visibleThumbs = this._getVisibleThumbs();
  5042. var numVisibleThumbs = visibleThumbs.views.length;
  5043. // If the thumbnail isn't currently visible, scroll it into view.
  5044. if (numVisibleThumbs > 0) {
  5045. var first = visibleThumbs.first.id;
  5046. // Account for only one thumbnail being visible.
  5047. var last = (numVisibleThumbs > 1 ? visibleThumbs.last.id : first);
  5048. if (page <= first || page >= last) {
  5049. scrollIntoView(thumbnail, { top: THUMBNAIL_SCROLL_MARGIN });
  5050. }
  5051. }
  5052. },
  5053. get pagesRotation() {
  5054. return this._pagesRotation;
  5055. },
  5056. set pagesRotation(rotation) {
  5057. this._pagesRotation = rotation;
  5058. for (var i = 0, l = this.thumbnails.length; i < l; i++) {
  5059. var thumb = this.thumbnails[i];
  5060. thumb.update(rotation);
  5061. }
  5062. },
  5063. cleanup: function PDFThumbnailViewer_cleanup() {
  5064. var tempCanvas = PDFThumbnailView.tempImageCache;
  5065. if (tempCanvas) {
  5066. // Zeroing the width and height causes Firefox to release graphics
  5067. // resources immediately, which can greatly reduce memory consumption.
  5068. tempCanvas.width = 0;
  5069. tempCanvas.height = 0;
  5070. }
  5071. PDFThumbnailView.tempImageCache = null;
  5072. },
  5073. /**
  5074. * @private
  5075. */
  5076. _resetView: function PDFThumbnailViewer_resetView() {
  5077. this.thumbnails = [];
  5078. this._pagesRotation = 0;
  5079. this._pagesRequests = [];
  5080. },
  5081. setDocument: function PDFThumbnailViewer_setDocument(pdfDocument) {
  5082. if (this.pdfDocument) {
  5083. // cleanup of the elements and views
  5084. var thumbsView = this.container;
  5085. while (thumbsView.hasChildNodes()) {
  5086. thumbsView.removeChild(thumbsView.lastChild);
  5087. }
  5088. this._resetView();
  5089. }
  5090. this.pdfDocument = pdfDocument;
  5091. if (!pdfDocument) {
  5092. return Promise.resolve();
  5093. }
  5094. return pdfDocument.getPage(1).then(function (firstPage) {
  5095. var pagesCount = pdfDocument.numPages;
  5096. var viewport = firstPage.getViewport(1.0);
  5097. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  5098. var thumbnail = new PDFThumbnailView({
  5099. container: this.container,
  5100. id: pageNum,
  5101. defaultViewport: viewport.clone(),
  5102. linkService: this.linkService,
  5103. renderingQueue: this.renderingQueue
  5104. });
  5105. this.thumbnails.push(thumbnail);
  5106. }
  5107. }.bind(this));
  5108. },
  5109. /**
  5110. * @param {PDFPageView} pageView
  5111. * @returns {PDFPage}
  5112. * @private
  5113. */
  5114. _ensurePdfPageLoaded:
  5115. function PDFThumbnailViewer_ensurePdfPageLoaded(thumbView) {
  5116. if (thumbView.pdfPage) {
  5117. return Promise.resolve(thumbView.pdfPage);
  5118. }
  5119. var pageNumber = thumbView.id;
  5120. if (this._pagesRequests[pageNumber]) {
  5121. return this._pagesRequests[pageNumber];
  5122. }
  5123. var promise = this.pdfDocument.getPage(pageNumber).then(
  5124. function (pdfPage) {
  5125. thumbView.setPdfPage(pdfPage);
  5126. this._pagesRequests[pageNumber] = null;
  5127. return pdfPage;
  5128. }.bind(this));
  5129. this._pagesRequests[pageNumber] = promise;
  5130. return promise;
  5131. },
  5132. ensureThumbnailVisible:
  5133. function PDFThumbnailViewer_ensureThumbnailVisible(page) {
  5134. // Ensure that the thumbnail of the current page is visible
  5135. // when switching from another view.
  5136. scrollIntoView(document.getElementById('thumbnailContainer' + page));
  5137. },
  5138. forceRendering: function () {
  5139. var visibleThumbs = this._getVisibleThumbs();
  5140. var thumbView = this.renderingQueue.getHighestPriority(visibleThumbs,
  5141. this.thumbnails,
  5142. this.scroll.down);
  5143. if (thumbView) {
  5144. this._ensurePdfPageLoaded(thumbView).then(function () {
  5145. this.renderingQueue.renderView(thumbView);
  5146. }.bind(this));
  5147. return true;
  5148. }
  5149. return false;
  5150. }
  5151. };
  5152. return PDFThumbnailViewer;
  5153. })();
  5154. /**
  5155. * @typedef {Object} PDFOutlineViewOptions
  5156. * @property {HTMLDivElement} container - The viewer element.
  5157. * @property {Array} outline - An array of outline objects.
  5158. * @property {IPDFLinkService} linkService - The navigation/linking service.
  5159. */
  5160. /**
  5161. * @class
  5162. */
  5163. var PDFOutlineView = (function PDFOutlineViewClosure() {
  5164. /**
  5165. * @constructs PDFOutlineView
  5166. * @param {PDFOutlineViewOptions} options
  5167. */
  5168. function PDFOutlineView(options) {
  5169. this.container = options.container;
  5170. this.outline = options.outline;
  5171. this.linkService = options.linkService;
  5172. this.lastToggleIsShow = true;
  5173. }
  5174. PDFOutlineView.prototype = {
  5175. reset: function PDFOutlineView_reset() {
  5176. var container = this.container;
  5177. while (container.firstChild) {
  5178. container.removeChild(container.firstChild);
  5179. }
  5180. this.lastToggleIsShow = true;
  5181. },
  5182. /**
  5183. * @private
  5184. */
  5185. _dispatchEvent: function PDFOutlineView_dispatchEvent(outlineCount) {
  5186. var event = document.createEvent('CustomEvent');
  5187. event.initCustomEvent('outlineloaded', true, true, {
  5188. outlineCount: outlineCount
  5189. });
  5190. this.container.dispatchEvent(event);
  5191. },
  5192. /**
  5193. * @private
  5194. */
  5195. _bindLink: function PDFOutlineView_bindLink(element, item) {
  5196. if (item.url) {
  5197. PDFJS.addLinkAttributes(element, { url: item.url });
  5198. return;
  5199. }
  5200. var linkService = this.linkService;
  5201. element.href = linkService.getDestinationHash(item.dest);
  5202. element.onclick = function goToDestination(e) {
  5203. linkService.navigateTo(item.dest);
  5204. return false;
  5205. };
  5206. },
  5207. /**
  5208. * Prepend a button before an outline item which allows the user to toggle
  5209. * the visibility of all outline items at that level.
  5210. *
  5211. * @private
  5212. */
  5213. _addToggleButton: function PDFOutlineView_addToggleButton(div) {
  5214. var toggler = document.createElement('div');
  5215. toggler.className = 'outlineItemToggler';
  5216. toggler.onclick = function(event) {
  5217. event.stopPropagation();
  5218. toggler.classList.toggle('outlineItemsHidden');
  5219. if (event.shiftKey) {
  5220. var shouldShowAll = !toggler.classList.contains('outlineItemsHidden');
  5221. this._toggleOutlineItem(div, shouldShowAll);
  5222. }
  5223. }.bind(this);
  5224. div.insertBefore(toggler, div.firstChild);
  5225. },
  5226. /**
  5227. * Toggle the visibility of the subtree of an outline item.
  5228. *
  5229. * @param {Element} root - the root of the outline (sub)tree.
  5230. * @param {boolean} state - whether to show the outline (sub)tree. If false,
  5231. * the outline subtree rooted at |root| will be collapsed.
  5232. *
  5233. * @private
  5234. */
  5235. _toggleOutlineItem: function PDFOutlineView_toggleOutlineItem(root, show) {
  5236. this.lastToggleIsShow = show;
  5237. var togglers = root.querySelectorAll('.outlineItemToggler');
  5238. for (var i = 0, ii = togglers.length; i < ii; ++i) {
  5239. togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden');
  5240. }
  5241. },
  5242. /**
  5243. * Collapse or expand all subtrees of the outline.
  5244. */
  5245. toggleOutlineTree: function PDFOutlineView_toggleOutlineTree() {
  5246. this._toggleOutlineItem(this.container, !this.lastToggleIsShow);
  5247. },
  5248. render: function PDFOutlineView_render() {
  5249. var outline = this.outline;
  5250. var outlineCount = 0;
  5251. this.reset();
  5252. if (!outline) {
  5253. this._dispatchEvent(outlineCount);
  5254. return;
  5255. }
  5256. var fragment = document.createDocumentFragment();
  5257. var queue = [{ parent: fragment, items: this.outline }];
  5258. var hasAnyNesting = false;
  5259. while (queue.length > 0) {
  5260. var levelData = queue.shift();
  5261. for (var i = 0, len = levelData.items.length; i < len; i++) {
  5262. var item = levelData.items[i];
  5263. var div = document.createElement('div');
  5264. div.className = 'outlineItem';
  5265. var element = document.createElement('a');
  5266. this._bindLink(element, item);
  5267. element.textContent = PDFJS.removeNullCharacters(item.title);
  5268. div.appendChild(element);
  5269. if (item.items.length > 0) {
  5270. hasAnyNesting = true;
  5271. this._addToggleButton(div);
  5272. var itemsDiv = document.createElement('div');
  5273. itemsDiv.className = 'outlineItems';
  5274. div.appendChild(itemsDiv);
  5275. queue.push({ parent: itemsDiv, items: item.items });
  5276. }
  5277. levelData.parent.appendChild(div);
  5278. outlineCount++;
  5279. }
  5280. }
  5281. if (hasAnyNesting) {
  5282. this.container.classList.add('outlineWithDeepNesting');
  5283. }
  5284. this.container.appendChild(fragment);
  5285. this._dispatchEvent(outlineCount);
  5286. }
  5287. };
  5288. return PDFOutlineView;
  5289. })();
  5290. /**
  5291. * @typedef {Object} PDFAttachmentViewOptions
  5292. * @property {HTMLDivElement} container - The viewer element.
  5293. * @property {Array} attachments - An array of attachment objects.
  5294. * @property {DownloadManager} downloadManager - The download manager.
  5295. */
  5296. /**
  5297. * @class
  5298. */
  5299. var PDFAttachmentView = (function PDFAttachmentViewClosure() {
  5300. /**
  5301. * @constructs PDFAttachmentView
  5302. * @param {PDFAttachmentViewOptions} options
  5303. */
  5304. function PDFAttachmentView(options) {
  5305. this.container = options.container;
  5306. this.attachments = options.attachments;
  5307. this.downloadManager = options.downloadManager;
  5308. }
  5309. PDFAttachmentView.prototype = {
  5310. reset: function PDFAttachmentView_reset() {
  5311. var container = this.container;
  5312. while (container.firstChild) {
  5313. container.removeChild(container.firstChild);
  5314. }
  5315. },
  5316. /**
  5317. * @private
  5318. */
  5319. _dispatchEvent: function PDFAttachmentView_dispatchEvent(attachmentsCount) {
  5320. var event = document.createEvent('CustomEvent');
  5321. event.initCustomEvent('attachmentsloaded', true, true, {
  5322. attachmentsCount: attachmentsCount
  5323. });
  5324. this.container.dispatchEvent(event);
  5325. },
  5326. /**
  5327. * @private
  5328. */
  5329. _bindLink: function PDFAttachmentView_bindLink(button, content, filename) {
  5330. button.onclick = function downloadFile(e) {
  5331. this.downloadManager.downloadData(content, filename, '');
  5332. return false;
  5333. }.bind(this);
  5334. },
  5335. render: function PDFAttachmentView_render() {
  5336. var attachments = this.attachments;
  5337. var attachmentsCount = 0;
  5338. this.reset();
  5339. if (!attachments) {
  5340. this._dispatchEvent(attachmentsCount);
  5341. return;
  5342. }
  5343. var names = Object.keys(attachments).sort(function(a, b) {
  5344. return a.toLowerCase().localeCompare(b.toLowerCase());
  5345. });
  5346. attachmentsCount = names.length;
  5347. for (var i = 0; i < attachmentsCount; i++) {
  5348. var item = attachments[names[i]];
  5349. var filename = getFileName(item.filename);
  5350. var div = document.createElement('div');
  5351. div.className = 'attachmentsItem';
  5352. var button = document.createElement('button');
  5353. this._bindLink(button, item.content, filename);
  5354. button.textContent = PDFJS.removeNullCharacters(filename);
  5355. div.appendChild(button);
  5356. this.container.appendChild(div);
  5357. }
  5358. this._dispatchEvent(attachmentsCount);
  5359. }
  5360. };
  5361. return PDFAttachmentView;
  5362. })();
  5363. var PDFViewerApplication = {
  5364. initialBookmark: document.location.hash.substring(1),
  5365. initialDestination: null,
  5366. initialized: false,
  5367. fellback: false,
  5368. pdfDocument: null,
  5369. pdfLoadingTask: null,
  5370. sidebarOpen: false,
  5371. printing: false,
  5372. /** @type {PDFViewer} */
  5373. pdfViewer: null,
  5374. /** @type {PDFThumbnailViewer} */
  5375. pdfThumbnailViewer: null,
  5376. /** @type {PDFRenderingQueue} */
  5377. pdfRenderingQueue: null,
  5378. /** @type {PDFPresentationMode} */
  5379. pdfPresentationMode: null,
  5380. /** @type {PDFDocumentProperties} */
  5381. pdfDocumentProperties: null,
  5382. /** @type {PDFLinkService} */
  5383. pdfLinkService: null,
  5384. /** @type {PDFHistory} */
  5385. pdfHistory: null,
  5386. pageRotation: 0,
  5387. isInitialViewSet: false,
  5388. animationStartedPromise: null,
  5389. preferenceSidebarViewOnLoad: SidebarView.NONE,
  5390. preferencePdfBugEnabled: false,
  5391. preferenceShowPreviousViewOnLoad: true,
  5392. preferenceDefaultZoomValue: '',
  5393. isViewerEmbedded: (window.parent !== window),
  5394. url: '',
  5395. // called once when the document is loaded
  5396. initialize: function pdfViewInitialize() {
  5397. var pdfRenderingQueue = new PDFRenderingQueue();
  5398. pdfRenderingQueue.onIdle = this.cleanup.bind(this);
  5399. this.pdfRenderingQueue = pdfRenderingQueue;
  5400. var pdfLinkService = new PDFLinkService();
  5401. this.pdfLinkService = pdfLinkService;
  5402. var container = document.getElementById('viewerContainer');
  5403. var viewer = document.getElementById('viewer');
  5404. this.pdfViewer = new PDFViewer({
  5405. container: container,
  5406. viewer: viewer,
  5407. renderingQueue: pdfRenderingQueue,
  5408. linkService: pdfLinkService
  5409. });
  5410. pdfRenderingQueue.setViewer(this.pdfViewer);
  5411. pdfLinkService.setViewer(this.pdfViewer);
  5412. var thumbnailContainer = document.getElementById('thumbnailView');
  5413. this.pdfThumbnailViewer = new PDFThumbnailViewer({
  5414. container: thumbnailContainer,
  5415. renderingQueue: pdfRenderingQueue,
  5416. linkService: pdfLinkService
  5417. });
  5418. pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
  5419. Preferences.initialize();
  5420. this.pdfHistory = new PDFHistory({
  5421. linkService: pdfLinkService
  5422. });
  5423. pdfLinkService.setHistory(this.pdfHistory);
  5424. this.findController = new PDFFindController({
  5425. pdfViewer: this.pdfViewer,
  5426. integratedFind: this.supportsIntegratedFind
  5427. });
  5428. this.pdfViewer.setFindController(this.findController);
  5429. this.findBar = new PDFFindBar({
  5430. bar: document.getElementById('findbar'),
  5431. toggleButton: document.getElementById('viewFind'),
  5432. findField: document.getElementById('findInput'),
  5433. highlightAllCheckbox: document.getElementById('findHighlightAll'),
  5434. caseSensitiveCheckbox: document.getElementById('findMatchCase'),
  5435. findMsg: document.getElementById('findMsg'),
  5436. findResultsCount: document.getElementById('findResultsCount'),
  5437. findStatusIcon: document.getElementById('findStatusIcon'),
  5438. findPreviousButton: document.getElementById('findPrevious'),
  5439. findNextButton: document.getElementById('findNext'),
  5440. findController: this.findController
  5441. });
  5442. this.findController.setFindBar(this.findBar);
  5443. HandTool.initialize({
  5444. container: container,
  5445. toggleHandTool: document.getElementById('toggleHandTool')
  5446. });
  5447. this.pdfDocumentProperties = new PDFDocumentProperties({
  5448. overlayName: 'documentPropertiesOverlay',
  5449. closeButton: document.getElementById('documentPropertiesClose'),
  5450. fields: {
  5451. 'fileName': document.getElementById('fileNameField'),
  5452. 'fileSize': document.getElementById('fileSizeField'),
  5453. 'title': document.getElementById('titleField'),
  5454. 'author': document.getElementById('authorField'),
  5455. 'subject': document.getElementById('subjectField'),
  5456. 'keywords': document.getElementById('keywordsField'),
  5457. 'creationDate': document.getElementById('creationDateField'),
  5458. 'modificationDate': document.getElementById('modificationDateField'),
  5459. 'creator': document.getElementById('creatorField'),
  5460. 'producer': document.getElementById('producerField'),
  5461. 'version': document.getElementById('versionField'),
  5462. 'pageCount': document.getElementById('pageCountField')
  5463. }
  5464. });
  5465. SecondaryToolbar.initialize({
  5466. toolbar: document.getElementById('secondaryToolbar'),
  5467. toggleButton: document.getElementById('secondaryToolbarToggle'),
  5468. presentationModeButton:
  5469. document.getElementById('secondaryPresentationMode'),
  5470. openFile: document.getElementById('secondaryOpenFile'),
  5471. print: document.getElementById('secondaryPrint'),
  5472. download: document.getElementById('secondaryDownload'),
  5473. viewBookmark: document.getElementById('secondaryViewBookmark'),
  5474. firstPage: document.getElementById('firstPage'),
  5475. lastPage: document.getElementById('lastPage'),
  5476. pageRotateCw: document.getElementById('pageRotateCw'),
  5477. pageRotateCcw: document.getElementById('pageRotateCcw'),
  5478. documentPropertiesButton: document.getElementById('documentProperties')
  5479. });
  5480. if (this.supportsFullscreen) {
  5481. var toolbar = SecondaryToolbar;
  5482. this.pdfPresentationMode = new PDFPresentationMode({
  5483. container: container,
  5484. viewer: viewer,
  5485. pdfViewer: this.pdfViewer,
  5486. pdfThumbnailViewer: this.pdfThumbnailViewer,
  5487. contextMenuItems: [
  5488. { element: document.getElementById('contextFirstPage'),
  5489. handler: toolbar.firstPageClick.bind(toolbar) },
  5490. { element: document.getElementById('contextLastPage'),
  5491. handler: toolbar.lastPageClick.bind(toolbar) },
  5492. { element: document.getElementById('contextPageRotateCw'),
  5493. handler: toolbar.pageRotateCwClick.bind(toolbar) },
  5494. { element: document.getElementById('contextPageRotateCcw'),
  5495. handler: toolbar.pageRotateCcwClick.bind(toolbar) }
  5496. ]
  5497. });
  5498. }
  5499. PasswordPrompt.initialize({
  5500. overlayName: 'passwordOverlay',
  5501. passwordField: document.getElementById('password'),
  5502. passwordText: document.getElementById('passwordText'),
  5503. passwordSubmit: document.getElementById('passwordSubmit'),
  5504. passwordCancel: document.getElementById('passwordCancel')
  5505. });
  5506. var self = this;
  5507. var initializedPromise = Promise.all([
  5508. Preferences.get('enableWebGL').then(function resolved(value) {
  5509. PDFJS.disableWebGL = !value;
  5510. }),
  5511. Preferences.get('sidebarViewOnLoad').then(function resolved(value) {
  5512. self.preferenceSidebarViewOnLoad = value;
  5513. }),
  5514. Preferences.get('pdfBugEnabled').then(function resolved(value) {
  5515. self.preferencePdfBugEnabled = value;
  5516. }),
  5517. Preferences.get('showPreviousViewOnLoad').then(function resolved(value) {
  5518. self.preferenceShowPreviousViewOnLoad = value;
  5519. }),
  5520. Preferences.get('defaultZoomValue').then(function resolved(value) {
  5521. self.preferenceDefaultZoomValue = value;
  5522. }),
  5523. Preferences.get('disableTextLayer').then(function resolved(value) {
  5524. if (PDFJS.disableTextLayer === true) {
  5525. return;
  5526. }
  5527. PDFJS.disableTextLayer = value;
  5528. }),
  5529. Preferences.get('disableRange').then(function resolved(value) {
  5530. if (PDFJS.disableRange === true) {
  5531. return;
  5532. }
  5533. PDFJS.disableRange = value;
  5534. }),
  5535. Preferences.get('disableStream').then(function resolved(value) {
  5536. if (PDFJS.disableStream === true) {
  5537. return;
  5538. }
  5539. PDFJS.disableStream = value;
  5540. }),
  5541. Preferences.get('disableAutoFetch').then(function resolved(value) {
  5542. PDFJS.disableAutoFetch = value;
  5543. }),
  5544. Preferences.get('disableFontFace').then(function resolved(value) {
  5545. if (PDFJS.disableFontFace === true) {
  5546. return;
  5547. }
  5548. PDFJS.disableFontFace = value;
  5549. }),
  5550. Preferences.get('useOnlyCssZoom').then(function resolved(value) {
  5551. PDFJS.useOnlyCssZoom = value;
  5552. }),
  5553. Preferences.get('externalLinkTarget').then(function resolved(value) {
  5554. if (PDFJS.isExternalLinkTargetSet()) {
  5555. return;
  5556. }
  5557. PDFJS.externalLinkTarget = value;
  5558. }),
  5559. // TODO move more preferences and other async stuff here
  5560. ]).catch(function (reason) { });
  5561. return initializedPromise.then(function () {
  5562. if (self.isViewerEmbedded && !PDFJS.isExternalLinkTargetSet()) {
  5563. // Prevent external links from "replacing" the viewer,
  5564. // when it's embedded in e.g. an iframe or an object.
  5565. PDFJS.externalLinkTarget = PDFJS.LinkTarget.TOP;
  5566. }
  5567. self.initialized = true;
  5568. });
  5569. },
  5570. zoomIn: function pdfViewZoomIn(ticks) {
  5571. var newScale = this.pdfViewer.currentScale;
  5572. do {
  5573. newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
  5574. newScale = Math.ceil(newScale * 10) / 10;
  5575. newScale = Math.min(MAX_SCALE, newScale);
  5576. } while (--ticks > 0 && newScale < MAX_SCALE);
  5577. this.pdfViewer.currentScaleValue = newScale;
  5578. },
  5579. zoomOut: function pdfViewZoomOut(ticks) {
  5580. var newScale = this.pdfViewer.currentScale;
  5581. do {
  5582. newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
  5583. newScale = Math.floor(newScale * 10) / 10;
  5584. newScale = Math.max(MIN_SCALE, newScale);
  5585. } while (--ticks > 0 && newScale > MIN_SCALE);
  5586. this.pdfViewer.currentScaleValue = newScale;
  5587. },
  5588. get pagesCount() {
  5589. return this.pdfDocument.numPages;
  5590. },
  5591. set page(val) {
  5592. this.pdfLinkService.page = val;
  5593. },
  5594. get page() { // TODO remove
  5595. return this.pdfLinkService.page;
  5596. },
  5597. get supportsPrinting() {
  5598. var canvas = document.createElement('canvas');
  5599. var value = 'mozPrintCallback' in canvas;
  5600. return PDFJS.shadow(this, 'supportsPrinting', value);
  5601. },
  5602. get supportsFullscreen() {
  5603. var doc = document.documentElement;
  5604. var support = !!(doc.requestFullscreen || doc.mozRequestFullScreen ||
  5605. doc.webkitRequestFullScreen || doc.msRequestFullscreen);
  5606. if (document.fullscreenEnabled === false ||
  5607. document.mozFullScreenEnabled === false ||
  5608. document.webkitFullscreenEnabled === false ||
  5609. document.msFullscreenEnabled === false) {
  5610. support = false;
  5611. }
  5612. if (support && PDFJS.disableFullscreen === true) {
  5613. support = false;
  5614. }
  5615. return PDFJS.shadow(this, 'supportsFullscreen', support);
  5616. },
  5617. get supportsIntegratedFind() {
  5618. var support = false;
  5619. return PDFJS.shadow(this, 'supportsIntegratedFind', support);
  5620. },
  5621. get supportsDocumentFonts() {
  5622. var support = true;
  5623. return PDFJS.shadow(this, 'supportsDocumentFonts', support);
  5624. },
  5625. get supportsDocumentColors() {
  5626. var support = true;
  5627. return PDFJS.shadow(this, 'supportsDocumentColors', support);
  5628. },
  5629. get loadingBar() {
  5630. var bar = new ProgressBar('#loadingBar', {});
  5631. return PDFJS.shadow(this, 'loadingBar', bar);
  5632. },
  5633. get supportedMouseWheelZoomModifierKeys() {
  5634. var support = {
  5635. ctrlKey: true,
  5636. metaKey: true,
  5637. };
  5638. return PDFJS.shadow(this, 'supportedMouseWheelZoomModifierKeys', support);
  5639. },
  5640. setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
  5641. this.url = url;
  5642. try {
  5643. this.setTitle(decodeURIComponent(getFileName(url)) || url);
  5644. } catch (e) {
  5645. // decodeURIComponent may throw URIError,
  5646. // fall back to using the unprocessed url in that case
  5647. this.setTitle(url);
  5648. }
  5649. },
  5650. setTitle: function pdfViewSetTitle(title) {
  5651. if (this.isViewerEmbedded) {
  5652. // Embedded PDF viewers should not be changing their parent page's title.
  5653. return;
  5654. }
  5655. document.title = title;
  5656. },
  5657. /**
  5658. * Closes opened PDF document.
  5659. * @returns {Promise} - Returns the promise, which is resolved when all
  5660. * destruction is completed.
  5661. */
  5662. close: function pdfViewClose() {
  5663. var errorWrapper = document.getElementById('errorWrapper');
  5664. errorWrapper.setAttribute('hidden', 'true');
  5665. if (!this.pdfLoadingTask) {
  5666. return Promise.resolve();
  5667. }
  5668. var promise = this.pdfLoadingTask.destroy();
  5669. this.pdfLoadingTask = null;
  5670. if (this.pdfDocument) {
  5671. this.pdfDocument = null;
  5672. this.pdfThumbnailViewer.setDocument(null);
  5673. this.pdfViewer.setDocument(null);
  5674. this.pdfLinkService.setDocument(null, null);
  5675. }
  5676. if (typeof PDFBug !== 'undefined') {
  5677. PDFBug.cleanup();
  5678. }
  5679. return promise;
  5680. },
  5681. /**
  5682. * Opens PDF document specified by URL or array with additional arguments.
  5683. * @param {string|TypedArray|ArrayBuffer} file - PDF location or binary data.
  5684. * @param {Object} args - (optional) Additional arguments for the getDocument
  5685. * call, e.g. HTTP headers ('httpHeaders') or
  5686. * alternative data transport ('range').
  5687. * @returns {Promise} - Returns the promise, which is resolved when document
  5688. * is opened.
  5689. */
  5690. open: function pdfViewOpen(file, args) {
  5691. var scale = 0;
  5692. if (arguments.length > 2 || typeof args === 'number') {
  5693. console.warn('Call of open() with obsolete signature.');
  5694. if (typeof args === 'number') {
  5695. scale = args; // scale argument was found
  5696. }
  5697. args = arguments[4] || null;
  5698. if (arguments[3] && typeof arguments[3] === 'object') {
  5699. // The pdfDataRangeTransport argument is present.
  5700. args = Object.create(args);
  5701. args.range = arguments[3];
  5702. }
  5703. if (typeof arguments[2] === 'string') {
  5704. // The password argument is present.
  5705. args = Object.create(args);
  5706. args.password = arguments[2];
  5707. }
  5708. }
  5709. if (this.pdfLoadingTask) {
  5710. // We need to destroy already opened document.
  5711. return this.close().then(function () {
  5712. // Reload the preferences if a document was previously opened.
  5713. Preferences.reload();
  5714. // ... and repeat the open() call.
  5715. return this.open(file, args);
  5716. }.bind(this));
  5717. }
  5718. var parameters = Object.create(null);
  5719. if (typeof file === 'string') { // URL
  5720. this.setTitleUsingUrl(file);
  5721. parameters.url = file;
  5722. } else if (file && 'byteLength' in file) { // ArrayBuffer
  5723. parameters.data = file;
  5724. } else if (file.url && file.originalUrl) {
  5725. this.setTitleUsingUrl(file.originalUrl);
  5726. parameters.url = file.url;
  5727. }
  5728. if (args) {
  5729. for (var prop in args) {
  5730. parameters[prop] = args[prop];
  5731. }
  5732. }
  5733. var self = this;
  5734. self.downloadComplete = false;
  5735. var loadingTask = PDFJS.getDocument(parameters);
  5736. this.pdfLoadingTask = loadingTask;
  5737. loadingTask.onPassword = function passwordNeeded(updatePassword, reason) {
  5738. PasswordPrompt.updatePassword = updatePassword;
  5739. PasswordPrompt.reason = reason;
  5740. PasswordPrompt.open();
  5741. };
  5742. loadingTask.onProgress = function getDocumentProgress(progressData) {
  5743. self.progress(progressData.loaded / progressData.total);
  5744. };
  5745. // Listen for unsupported features to trigger the fallback UI.
  5746. loadingTask.onUnsupportedFeature = this.fallback.bind(this);
  5747. var result = loadingTask.promise.then(
  5748. function getDocumentCallback(pdfDocument) {
  5749. self.load(pdfDocument, scale);
  5750. },
  5751. function getDocumentError(exception) {
  5752. var message = exception && exception.message;
  5753. var loadingErrorMessage = mozL10n.get('loading_error', null,
  5754. 'An error occurred while loading the PDF.');
  5755. if (exception instanceof PDFJS.InvalidPDFException) {
  5756. // change error message also for other builds
  5757. loadingErrorMessage = mozL10n.get('invalid_file_error', null,
  5758. 'Invalid or corrupted PDF file.');
  5759. } else if (exception instanceof PDFJS.MissingPDFException) {
  5760. // special message for missing PDF's
  5761. loadingErrorMessage = mozL10n.get('missing_file_error', null,
  5762. 'Missing PDF file.');
  5763. } else if (exception instanceof PDFJS.UnexpectedResponseException) {
  5764. loadingErrorMessage = mozL10n.get('unexpected_response_error', null,
  5765. 'Unexpected server response.');
  5766. }
  5767. var moreInfo = {
  5768. message: message
  5769. };
  5770. self.error(loadingErrorMessage, moreInfo);
  5771. throw new Error(loadingErrorMessage);
  5772. }
  5773. );
  5774. if (args && args.length) {
  5775. PDFViewerApplication.pdfDocumentProperties.setFileSize(args.length);
  5776. }
  5777. return result;
  5778. },
  5779. download: function pdfViewDownload() {
  5780. function downloadByUrl() {
  5781. downloadManager.downloadUrl(url, filename);
  5782. }
  5783. var url = this.url.split('#')[0];
  5784. var filename = getPDFFileNameFromURL(url);
  5785. var downloadManager = new DownloadManager();
  5786. downloadManager.onerror = function (err) {
  5787. // This error won't really be helpful because it's likely the
  5788. // fallback won't work either (or is already open).
  5789. PDFViewerApplication.error('PDF failed to download.');
  5790. };
  5791. if (!this.pdfDocument) { // the PDF is not ready yet
  5792. downloadByUrl();
  5793. return;
  5794. }
  5795. if (!this.downloadComplete) { // the PDF is still downloading
  5796. downloadByUrl();
  5797. return;
  5798. }
  5799. this.pdfDocument.getData().then(
  5800. function getDataSuccess(data) {
  5801. var blob = PDFJS.createBlob(data, 'application/pdf');
  5802. downloadManager.download(blob, url, filename);
  5803. },
  5804. downloadByUrl // Error occurred try downloading with just the url.
  5805. ).then(null, downloadByUrl);
  5806. },
  5807. fallback: function pdfViewFallback(featureId) {
  5808. },
  5809. /**
  5810. * Show the error box.
  5811. * @param {String} message A message that is human readable.
  5812. * @param {Object} moreInfo (optional) Further information about the error
  5813. * that is more technical. Should have a 'message'
  5814. * and optionally a 'stack' property.
  5815. */
  5816. error: function pdfViewError(message, moreInfo) {
  5817. var moreInfoText = mozL10n.get('error_version_info',
  5818. {version: PDFJS.version || '?', build: PDFJS.build || '?'},
  5819. 'PDF.js v{{version}} (build: {{build}})') + '\n';
  5820. if (moreInfo) {
  5821. moreInfoText +=
  5822. mozL10n.get('error_message', {message: moreInfo.message},
  5823. 'Message: {{message}}');
  5824. if (moreInfo.stack) {
  5825. moreInfoText += '\n' +
  5826. mozL10n.get('error_stack', {stack: moreInfo.stack},
  5827. 'Stack: {{stack}}');
  5828. } else {
  5829. if (moreInfo.filename) {
  5830. moreInfoText += '\n' +
  5831. mozL10n.get('error_file', {file: moreInfo.filename},
  5832. 'File: {{file}}');
  5833. }
  5834. if (moreInfo.lineNumber) {
  5835. moreInfoText += '\n' +
  5836. mozL10n.get('error_line', {line: moreInfo.lineNumber},
  5837. 'Line: {{line}}');
  5838. }
  5839. }
  5840. }
  5841. var errorWrapper = document.getElementById('errorWrapper');
  5842. errorWrapper.removeAttribute('hidden');
  5843. var errorMessage = document.getElementById('errorMessage');
  5844. errorMessage.textContent = message;
  5845. var closeButton = document.getElementById('errorClose');
  5846. closeButton.onclick = function() {
  5847. errorWrapper.setAttribute('hidden', 'true');
  5848. };
  5849. var errorMoreInfo = document.getElementById('errorMoreInfo');
  5850. var moreInfoButton = document.getElementById('errorShowMore');
  5851. var lessInfoButton = document.getElementById('errorShowLess');
  5852. moreInfoButton.onclick = function() {
  5853. errorMoreInfo.removeAttribute('hidden');
  5854. moreInfoButton.setAttribute('hidden', 'true');
  5855. lessInfoButton.removeAttribute('hidden');
  5856. errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px';
  5857. };
  5858. lessInfoButton.onclick = function() {
  5859. errorMoreInfo.setAttribute('hidden', 'true');
  5860. moreInfoButton.removeAttribute('hidden');
  5861. lessInfoButton.setAttribute('hidden', 'true');
  5862. };
  5863. moreInfoButton.oncontextmenu = noContextMenuHandler;
  5864. lessInfoButton.oncontextmenu = noContextMenuHandler;
  5865. closeButton.oncontextmenu = noContextMenuHandler;
  5866. moreInfoButton.removeAttribute('hidden');
  5867. lessInfoButton.setAttribute('hidden', 'true');
  5868. errorMoreInfo.value = moreInfoText;
  5869. },
  5870. progress: function pdfViewProgress(level) {
  5871. var percent = Math.round(level * 100);
  5872. // When we transition from full request to range requests, it's possible
  5873. // that we discard some of the loaded data. This can cause the loading
  5874. // bar to move backwards. So prevent this by only updating the bar if it
  5875. // increases.
  5876. if (percent > this.loadingBar.percent || isNaN(percent)) {
  5877. this.loadingBar.percent = percent;
  5878. // When disableAutoFetch is enabled, it's not uncommon for the entire file
  5879. // to never be fetched (depends on e.g. the file structure). In this case
  5880. // the loading bar will not be completely filled, nor will it be hidden.
  5881. // To prevent displaying a partially filled loading bar permanently, we
  5882. // hide it when no data has been loaded during a certain amount of time.
  5883. if (PDFJS.disableAutoFetch && percent) {
  5884. if (this.disableAutoFetchLoadingBarTimeout) {
  5885. clearTimeout(this.disableAutoFetchLoadingBarTimeout);
  5886. this.disableAutoFetchLoadingBarTimeout = null;
  5887. }
  5888. this.loadingBar.show();
  5889. this.disableAutoFetchLoadingBarTimeout = setTimeout(function () {
  5890. this.loadingBar.hide();
  5891. this.disableAutoFetchLoadingBarTimeout = null;
  5892. }.bind(this), DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT);
  5893. }
  5894. }
  5895. },
  5896. load: function pdfViewLoad(pdfDocument, scale) {
  5897. var self = this;
  5898. scale = scale || UNKNOWN_SCALE;
  5899. this.findController.reset();
  5900. this.pdfDocument = pdfDocument;
  5901. this.pdfDocumentProperties.setDocumentAndUrl(pdfDocument, this.url);
  5902. var downloadedPromise = pdfDocument.getDownloadInfo().then(function() {
  5903. self.downloadComplete = true;
  5904. self.loadingBar.hide();
  5905. });
  5906. var pagesCount = pdfDocument.numPages;
  5907. document.getElementById('numPages').textContent =
  5908. mozL10n.get('page_of', {pageCount: pagesCount}, 'of {{pageCount}}');
  5909. document.getElementById('pageNumber').max = pagesCount;
  5910. var id = this.documentFingerprint = pdfDocument.fingerprint;
  5911. var store = this.store = new ViewHistory(id);
  5912. var baseDocumentUrl = null;
  5913. this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl);
  5914. var pdfViewer = this.pdfViewer;
  5915. pdfViewer.currentScale = scale;
  5916. pdfViewer.setDocument(pdfDocument);
  5917. var firstPagePromise = pdfViewer.firstPagePromise;
  5918. var pagesPromise = pdfViewer.pagesPromise;
  5919. var onePageRendered = pdfViewer.onePageRendered;
  5920. this.pageRotation = 0;
  5921. this.isInitialViewSet = false;
  5922. this.pdfThumbnailViewer.setDocument(pdfDocument);
  5923. firstPagePromise.then(function(pdfPage) {
  5924. downloadedPromise.then(function () {
  5925. var event = document.createEvent('CustomEvent');
  5926. event.initCustomEvent('documentload', true, true, {});
  5927. window.dispatchEvent(event);
  5928. });
  5929. self.loadingBar.setWidth(document.getElementById('viewer'));
  5930. if (!PDFJS.disableHistory && !self.isViewerEmbedded) {
  5931. // The browsing history is only enabled when the viewer is standalone,
  5932. // i.e. not when it is embedded in a web page.
  5933. if (!self.preferenceShowPreviousViewOnLoad) {
  5934. self.pdfHistory.clearHistoryState();
  5935. }
  5936. self.pdfHistory.initialize(self.documentFingerprint);
  5937. if (self.pdfHistory.initialDestination) {
  5938. self.initialDestination = self.pdfHistory.initialDestination;
  5939. } else if (self.pdfHistory.initialBookmark) {
  5940. self.initialBookmark = self.pdfHistory.initialBookmark;
  5941. }
  5942. }
  5943. var initialParams = {
  5944. destination: self.initialDestination,
  5945. bookmark: self.initialBookmark,
  5946. hash: null,
  5947. };
  5948. store.initializedPromise.then(function resolved() {
  5949. var storedHash = null;
  5950. if (self.preferenceShowPreviousViewOnLoad &&
  5951. store.get('exists', false)) {
  5952. var pageNum = store.get('page', '1');
  5953. var zoom = self.preferenceDefaultZoomValue ||
  5954. store.get('zoom', DEFAULT_SCALE_VALUE);
  5955. var left = store.get('scrollLeft', '0');
  5956. var top = store.get('scrollTop', '0');
  5957. storedHash = 'page=' + pageNum + '&zoom=' + zoom + ',' +
  5958. left + ',' + top;
  5959. } else if (self.preferenceDefaultZoomValue) {
  5960. storedHash = 'page=1&zoom=' + self.preferenceDefaultZoomValue;
  5961. }
  5962. self.setInitialView(storedHash, scale);
  5963. initialParams.hash = storedHash;
  5964. // Make all navigation keys work on document load,
  5965. // unless the viewer is embedded in a web page.
  5966. if (!self.isViewerEmbedded) {
  5967. self.pdfViewer.focus();
  5968. }
  5969. }, function rejected(reason) {
  5970. console.error(reason);
  5971. self.setInitialView(null, scale);
  5972. });
  5973. // For documents with different page sizes,
  5974. // ensure that the correct location becomes visible on load.
  5975. pagesPromise.then(function resolved() {
  5976. if (!initialParams.destination && !initialParams.bookmark &&
  5977. !initialParams.hash) {
  5978. return;
  5979. }
  5980. if (self.hasEqualPageSizes) {
  5981. return;
  5982. }
  5983. self.initialDestination = initialParams.destination;
  5984. self.initialBookmark = initialParams.bookmark;
  5985. self.pdfViewer.currentScaleValue = self.pdfViewer.currentScaleValue;
  5986. self.setInitialView(initialParams.hash, scale);
  5987. });
  5988. });
  5989. pagesPromise.then(function() {
  5990. if (self.supportsPrinting) {
  5991. pdfDocument.getJavaScript().then(function(javaScript) {
  5992. if (javaScript.length) {
  5993. console.warn('Warning: JavaScript is not supported');
  5994. self.fallback(PDFJS.UNSUPPORTED_FEATURES.javaScript);
  5995. }
  5996. // Hack to support auto printing.
  5997. var regex = /\bprint\s*\(/;
  5998. for (var i = 0, ii = javaScript.length; i < ii; i++) {
  5999. var js = javaScript[i];
  6000. if (js && regex.test(js)) {
  6001. setTimeout(function() {
  6002. window.print();
  6003. });
  6004. return;
  6005. }
  6006. }
  6007. });
  6008. }
  6009. });
  6010. // outline depends on pagesRefMap
  6011. var promises = [pagesPromise, this.animationStartedPromise];
  6012. Promise.all(promises).then(function() {
  6013. pdfDocument.getOutline().then(function(outline) {
  6014. var container = document.getElementById('outlineView');
  6015. self.outline = new PDFOutlineView({
  6016. container: container,
  6017. outline: outline,
  6018. linkService: self.pdfLinkService
  6019. });
  6020. self.outline.render();
  6021. document.getElementById('viewOutline').disabled = !outline;
  6022. if (!outline && !container.classList.contains('hidden')) {
  6023. self.switchSidebarView('thumbs');
  6024. }
  6025. if (outline &&
  6026. self.preferenceSidebarViewOnLoad === SidebarView.OUTLINE) {
  6027. self.switchSidebarView('outline', true);
  6028. }
  6029. });
  6030. pdfDocument.getAttachments().then(function(attachments) {
  6031. var container = document.getElementById('attachmentsView');
  6032. self.attachments = new PDFAttachmentView({
  6033. container: container,
  6034. attachments: attachments,
  6035. downloadManager: new DownloadManager()
  6036. });
  6037. self.attachments.render();
  6038. document.getElementById('viewAttachments').disabled = !attachments;
  6039. if (!attachments && !container.classList.contains('hidden')) {
  6040. self.switchSidebarView('thumbs');
  6041. }
  6042. if (attachments &&
  6043. self.preferenceSidebarViewOnLoad === SidebarView.ATTACHMENTS) {
  6044. self.switchSidebarView('attachments', true);
  6045. }
  6046. });
  6047. });
  6048. if (self.preferenceSidebarViewOnLoad === SidebarView.THUMBS) {
  6049. Promise.all([firstPagePromise, onePageRendered]).then(function () {
  6050. self.switchSidebarView('thumbs', true);
  6051. });
  6052. }
  6053. pdfDocument.getMetadata().then(function(data) {
  6054. var info = data.info, metadata = data.metadata;
  6055. self.documentInfo = info;
  6056. self.metadata = metadata;
  6057. // Provides some basic debug information
  6058. console.log('PDF ' + pdfDocument.fingerprint + ' [' +
  6059. info.PDFFormatVersion + ' ' + (info.Producer || '-').trim() +
  6060. ' / ' + (info.Creator || '-').trim() + ']' +
  6061. ' (PDF.js: ' + (PDFJS.version || '-') +
  6062. (!PDFJS.disableWebGL ? ' [WebGL]' : '') + ')');
  6063. var pdfTitle;
  6064. if (metadata && metadata.has('dc:title')) {
  6065. var title = metadata.get('dc:title');
  6066. // Ghostscript sometimes return 'Untitled', sets the title to 'Untitled'
  6067. if (title !== 'Untitled') {
  6068. pdfTitle = title;
  6069. }
  6070. }
  6071. if (!pdfTitle && info && info['Title']) {
  6072. pdfTitle = info['Title'];
  6073. }
  6074. if (pdfTitle) {
  6075. self.setTitle(pdfTitle + ' - ' + document.title);
  6076. }
  6077. if (info.IsAcroFormPresent) {
  6078. console.warn('Warning: AcroForm/XFA is not supported');
  6079. self.fallback(PDFJS.UNSUPPORTED_FEATURES.forms);
  6080. }
  6081. });
  6082. },
  6083. setInitialView: function pdfViewSetInitialView(storedHash, scale) {
  6084. this.isInitialViewSet = true;
  6085. // When opening a new file, when one is already loaded in the viewer,
  6086. // ensure that the 'pageNumber' element displays the correct value.
  6087. document.getElementById('pageNumber').value =
  6088. this.pdfViewer.currentPageNumber;
  6089. if (this.initialDestination) {
  6090. this.pdfLinkService.navigateTo(this.initialDestination);
  6091. this.initialDestination = null;
  6092. } else if (this.initialBookmark) {
  6093. this.pdfLinkService.setHash(this.initialBookmark);
  6094. this.pdfHistory.push({ hash: this.initialBookmark }, true);
  6095. this.initialBookmark = null;
  6096. } else if (storedHash) {
  6097. this.pdfLinkService.setHash(storedHash);
  6098. } else if (scale) {
  6099. this.pdfViewer.currentScaleValue = scale;
  6100. this.page = 1;
  6101. }
  6102. if (!this.pdfViewer.currentScaleValue) {
  6103. // Scale was not initialized: invalid bookmark or scale was not specified.
  6104. // Setting the default one.
  6105. this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  6106. }
  6107. },
  6108. cleanup: function pdfViewCleanup() {
  6109. if (!this.pdfDocument) {
  6110. return; // run cleanup when document is loaded
  6111. }
  6112. this.pdfViewer.cleanup();
  6113. this.pdfThumbnailViewer.cleanup();
  6114. this.pdfDocument.cleanup();
  6115. },
  6116. forceRendering: function pdfViewForceRendering() {
  6117. this.pdfRenderingQueue.printing = this.printing;
  6118. this.pdfRenderingQueue.isThumbnailViewEnabled = this.sidebarOpen;
  6119. this.pdfRenderingQueue.renderHighestPriority();
  6120. },
  6121. refreshThumbnailViewer: function pdfViewRefreshThumbnailViewer() {
  6122. var pdfViewer = this.pdfViewer;
  6123. var thumbnailViewer = this.pdfThumbnailViewer;
  6124. // set thumbnail images of rendered pages
  6125. var pagesCount = pdfViewer.pagesCount;
  6126. for (var pageIndex = 0; pageIndex < pagesCount; pageIndex++) {
  6127. var pageView = pdfViewer.getPageView(pageIndex);
  6128. if (pageView && pageView.renderingState === RenderingStates.FINISHED) {
  6129. var thumbnailView = thumbnailViewer.getThumbnail(pageIndex);
  6130. thumbnailView.setImage(pageView);
  6131. }
  6132. }
  6133. thumbnailViewer.scrollThumbnailIntoView(this.page);
  6134. },
  6135. switchSidebarView: function pdfViewSwitchSidebarView(view, openSidebar) {
  6136. if (openSidebar && !this.sidebarOpen) {
  6137. document.getElementById('sidebarToggle').click();
  6138. }
  6139. var thumbsView = document.getElementById('thumbnailView');
  6140. var outlineView = document.getElementById('outlineView');
  6141. var attachmentsView = document.getElementById('attachmentsView');
  6142. var thumbsButton = document.getElementById('viewThumbnail');
  6143. var outlineButton = document.getElementById('viewOutline');
  6144. var attachmentsButton = document.getElementById('viewAttachments');
  6145. switch (view) {
  6146. case 'thumbs':
  6147. var wasAnotherViewVisible = thumbsView.classList.contains('hidden');
  6148. thumbsButton.classList.add('toggled');
  6149. outlineButton.classList.remove('toggled');
  6150. attachmentsButton.classList.remove('toggled');
  6151. thumbsView.classList.remove('hidden');
  6152. outlineView.classList.add('hidden');
  6153. attachmentsView.classList.add('hidden');
  6154. this.forceRendering();
  6155. if (wasAnotherViewVisible) {
  6156. this.pdfThumbnailViewer.ensureThumbnailVisible(this.page);
  6157. }
  6158. break;
  6159. case 'outline':
  6160. if (outlineButton.disabled) {
  6161. return;
  6162. }
  6163. thumbsButton.classList.remove('toggled');
  6164. outlineButton.classList.add('toggled');
  6165. attachmentsButton.classList.remove('toggled');
  6166. thumbsView.classList.add('hidden');
  6167. outlineView.classList.remove('hidden');
  6168. attachmentsView.classList.add('hidden');
  6169. break;
  6170. case 'attachments':
  6171. if (attachmentsButton.disabled) {
  6172. return;
  6173. }
  6174. thumbsButton.classList.remove('toggled');
  6175. outlineButton.classList.remove('toggled');
  6176. attachmentsButton.classList.add('toggled');
  6177. thumbsView.classList.add('hidden');
  6178. outlineView.classList.add('hidden');
  6179. attachmentsView.classList.remove('hidden');
  6180. break;
  6181. }
  6182. },
  6183. beforePrint: function pdfViewSetupBeforePrint() {
  6184. if (!this.supportsPrinting) {
  6185. var printMessage = mozL10n.get('printing_not_supported', null,
  6186. 'Warning: Printing is not fully supported by this browser.');
  6187. this.error(printMessage);
  6188. return;
  6189. }
  6190. var alertNotReady = false;
  6191. var i, ii;
  6192. if (!this.pdfDocument || !this.pagesCount) {
  6193. alertNotReady = true;
  6194. } else {
  6195. for (i = 0, ii = this.pagesCount; i < ii; ++i) {
  6196. if (!this.pdfViewer.getPageView(i).pdfPage) {
  6197. alertNotReady = true;
  6198. break;
  6199. }
  6200. }
  6201. }
  6202. if (alertNotReady) {
  6203. var notReadyMessage = mozL10n.get('printing_not_ready', null,
  6204. 'Warning: The PDF is not fully loaded for printing.');
  6205. window.alert(notReadyMessage);
  6206. return;
  6207. }
  6208. this.printing = true;
  6209. this.forceRendering();
  6210. var body = document.querySelector('body');
  6211. body.setAttribute('data-mozPrintCallback', true);
  6212. if (!this.hasEqualPageSizes) {
  6213. console.warn('Not all pages have the same size. The printed result ' +
  6214. 'may be incorrect!');
  6215. }
  6216. // Insert a @page + size rule to make sure that the page size is correctly
  6217. // set. Note that we assume that all pages have the same size, because
  6218. // variable-size pages are not supported yet (at least in Chrome & Firefox).
  6219. // TODO(robwu): Use named pages when size calculation bugs get resolved
  6220. // (e.g. https://crbug.com/355116) AND when support for named pages is
  6221. // added (http://www.w3.org/TR/css3-page/#using-named-pages).
  6222. // In browsers where @page + size is not supported (such as Firefox,
  6223. // https://bugzil.la/851441), the next stylesheet will be ignored and the
  6224. // user has to select the correct paper size in the UI if wanted.
  6225. this.pageStyleSheet = document.createElement('style');
  6226. var pageSize = this.pdfViewer.getPageView(0).pdfPage.getViewport(1);
  6227. this.pageStyleSheet.textContent =
  6228. // "size:<width> <height>" is what we need. But also add "A4" because
  6229. // Firefox incorrectly reports support for the other value.
  6230. '@supports ((size:A4) and (size:1pt 1pt)) {' +
  6231. '@page { size: ' + pageSize.width + 'pt ' + pageSize.height + 'pt;}' +
  6232. // The canvas and each ancestor node must have a height of 100% to make
  6233. // sure that each canvas is printed on exactly one page.
  6234. '#printContainer {height:100%}' +
  6235. '#printContainer > div {width:100% !important;height:100% !important;}' +
  6236. '}';
  6237. body.appendChild(this.pageStyleSheet);
  6238. for (i = 0, ii = this.pagesCount; i < ii; ++i) {
  6239. this.pdfViewer.getPageView(i).beforePrint();
  6240. }
  6241. },
  6242. // Whether all pages of the PDF have the same width and height.
  6243. get hasEqualPageSizes() {
  6244. var firstPage = this.pdfViewer.getPageView(0);
  6245. for (var i = 1, ii = this.pagesCount; i < ii; ++i) {
  6246. var pageView = this.pdfViewer.getPageView(i);
  6247. if (pageView.width !== firstPage.width ||
  6248. pageView.height !== firstPage.height) {
  6249. return false;
  6250. }
  6251. }
  6252. return true;
  6253. },
  6254. afterPrint: function pdfViewSetupAfterPrint() {
  6255. var div = document.getElementById('printContainer');
  6256. while (div.hasChildNodes()) {
  6257. div.removeChild(div.lastChild);
  6258. }
  6259. if (this.pageStyleSheet && this.pageStyleSheet.parentNode) {
  6260. this.pageStyleSheet.parentNode.removeChild(this.pageStyleSheet);
  6261. this.pageStyleSheet = null;
  6262. }
  6263. this.printing = false;
  6264. this.forceRendering();
  6265. },
  6266. rotatePages: function pdfViewRotatePages(delta) {
  6267. var pageNumber = this.page;
  6268. this.pageRotation = (this.pageRotation + 360 + delta) % 360;
  6269. this.pdfViewer.pagesRotation = this.pageRotation;
  6270. this.pdfThumbnailViewer.pagesRotation = this.pageRotation;
  6271. this.forceRendering();
  6272. this.pdfViewer.scrollPageIntoView(pageNumber);
  6273. },
  6274. requestPresentationMode: function pdfViewRequestPresentationMode() {
  6275. if (!this.pdfPresentationMode) {
  6276. return;
  6277. }
  6278. this.pdfPresentationMode.request();
  6279. },
  6280. /**
  6281. * @param {number} delta - The delta value from the mouse event.
  6282. */
  6283. scrollPresentationMode: function pdfViewScrollPresentationMode(delta) {
  6284. if (!this.pdfPresentationMode) {
  6285. return;
  6286. }
  6287. this.pdfPresentationMode.mouseScroll(delta);
  6288. }
  6289. };
  6290. window.PDFView = PDFViewerApplication; // obsolete name, using it as an alias
  6291. var HOSTED_VIEWER_ORIGINS = ['null',
  6292. 'http://mozilla.github.io', 'https://mozilla.github.io'];
  6293. function validateFileURL(file) {
  6294. try {
  6295. var viewerOrigin = new URL(window.location.href).origin || 'null';
  6296. if (HOSTED_VIEWER_ORIGINS.indexOf(viewerOrigin) >= 0) {
  6297. // Hosted or local viewer, allow for any file locations
  6298. return;
  6299. }
  6300. var fileOrigin = new URL(file, window.location.href).origin;
  6301. // Removing of the following line will not guarantee that the viewer will
  6302. // start accepting URLs from foreign origin -- CORS headers on the remote
  6303. // server must be properly configured.
  6304. if (fileOrigin !== viewerOrigin) {
  6305. throw new Error('file origin does not match viewer\'s');
  6306. }
  6307. } catch (e) {
  6308. var message = e && e.message;
  6309. var loadingErrorMessage = mozL10n.get('loading_error', null,
  6310. 'An error occurred while loading the PDF.');
  6311. var moreInfo = {
  6312. message: message
  6313. };
  6314. PDFViewerApplication.error(loadingErrorMessage, moreInfo);
  6315. throw e;
  6316. }
  6317. }
  6318. function webViewerLoad(evt) {
  6319. configure(PDFJS);
  6320. PDFViewerApplication.initialize().then(webViewerInitialized);
  6321. }
  6322. function webViewerInitialized() {
  6323. var queryString = document.location.search.substring(1);
  6324. var params = parseQueryString(queryString);
  6325. var file = 'file' in params ? params.file : DEFAULT_URL;
  6326. validateFileURL(file);
  6327. var fileInput = document.createElement('input');
  6328. fileInput.id = 'fileInput';
  6329. fileInput.className = 'fileInput';
  6330. fileInput.setAttribute('type', 'file');
  6331. fileInput.oncontextmenu = noContextMenuHandler;
  6332. document.body.appendChild(fileInput);
  6333. if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
  6334. document.getElementById('openFile').setAttribute('hidden', 'true');
  6335. document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true');
  6336. } else {
  6337. document.getElementById('fileInput').value = null;
  6338. }
  6339. // �ֶ��޸� �뺣��
  6340. document.getElementById('openFile').setAttribute('hidden', 'true');
  6341. document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true');
  6342. document.getElementById('documentProperties').setAttribute('hidden', 'true');
  6343. // �ֶ��޸Ľ���
  6344. var locale = PDFJS.locale || navigator.language;
  6345. if (PDFViewerApplication.preferencePdfBugEnabled) {
  6346. // Special debugging flags in the hash section of the URL.
  6347. var hash = document.location.hash.substring(1);
  6348. var hashParams = parseQueryString(hash);
  6349. if ('disableworker' in hashParams) {
  6350. PDFJS.disableWorker = (hashParams['disableworker'] === 'true');
  6351. }
  6352. if ('disablerange' in hashParams) {
  6353. PDFJS.disableRange = (hashParams['disablerange'] === 'true');
  6354. }
  6355. if ('disablestream' in hashParams) {
  6356. PDFJS.disableStream = (hashParams['disablestream'] === 'true');
  6357. }
  6358. if ('disableautofetch' in hashParams) {
  6359. PDFJS.disableAutoFetch = (hashParams['disableautofetch'] === 'true');
  6360. }
  6361. if ('disablefontface' in hashParams) {
  6362. PDFJS.disableFontFace = (hashParams['disablefontface'] === 'true');
  6363. }
  6364. if ('disablehistory' in hashParams) {
  6365. PDFJS.disableHistory = (hashParams['disablehistory'] === 'true');
  6366. }
  6367. if ('webgl' in hashParams) {
  6368. PDFJS.disableWebGL = (hashParams['webgl'] !== 'true');
  6369. }
  6370. if ('useonlycsszoom' in hashParams) {
  6371. PDFJS.useOnlyCssZoom = (hashParams['useonlycsszoom'] === 'true');
  6372. }
  6373. if ('verbosity' in hashParams) {
  6374. PDFJS.verbosity = hashParams['verbosity'] | 0;
  6375. }
  6376. if ('ignorecurrentpositiononzoom' in hashParams) {
  6377. IGNORE_CURRENT_POSITION_ON_ZOOM =
  6378. (hashParams['ignorecurrentpositiononzoom'] === 'true');
  6379. }
  6380. if ('locale' in hashParams) {
  6381. locale = hashParams['locale'];
  6382. }
  6383. if ('textlayer' in hashParams) {
  6384. switch (hashParams['textlayer']) {
  6385. case 'off':
  6386. PDFJS.disableTextLayer = true;
  6387. break;
  6388. case 'visible':
  6389. case 'shadow':
  6390. case 'hover':
  6391. var viewer = document.getElementById('viewer');
  6392. viewer.classList.add('textLayer-' + hashParams['textlayer']);
  6393. break;
  6394. }
  6395. }
  6396. if ('pdfbug' in hashParams) {
  6397. PDFJS.pdfBug = true;
  6398. var pdfBug = hashParams['pdfbug'];
  6399. var enabled = pdfBug.split(',');
  6400. PDFBug.enable(enabled);
  6401. PDFBug.init();
  6402. }
  6403. }
  6404. mozL10n.setLanguage(locale);
  6405. if (!PDFViewerApplication.supportsPrinting) {
  6406. document.getElementById('print').classList.add('hidden');
  6407. document.getElementById('secondaryPrint').classList.add('hidden');
  6408. }
  6409. if (!PDFViewerApplication.supportsFullscreen) {
  6410. document.getElementById('presentationMode').classList.add('hidden');
  6411. document.getElementById('secondaryPresentationMode').
  6412. classList.add('hidden');
  6413. }
  6414. if (PDFViewerApplication.supportsIntegratedFind) {
  6415. document.getElementById('viewFind').classList.add('hidden');
  6416. }
  6417. // Suppress context menus for some controls
  6418. document.getElementById('scaleSelect').oncontextmenu = noContextMenuHandler;
  6419. var mainContainer = document.getElementById('mainContainer');
  6420. var outerContainer = document.getElementById('outerContainer');
  6421. mainContainer.addEventListener('transitionend', function(e) {
  6422. if (e.target === mainContainer) {
  6423. var event = document.createEvent('UIEvents');
  6424. event.initUIEvent('resize', false, false, window, 0);
  6425. window.dispatchEvent(event);
  6426. outerContainer.classList.remove('sidebarMoving');
  6427. }
  6428. }, true);
  6429. document.getElementById('sidebarToggle').addEventListener('click',
  6430. function() {
  6431. this.classList.toggle('toggled');
  6432. outerContainer.classList.add('sidebarMoving');
  6433. outerContainer.classList.toggle('sidebarOpen');
  6434. PDFViewerApplication.sidebarOpen =
  6435. outerContainer.classList.contains('sidebarOpen');
  6436. if (PDFViewerApplication.sidebarOpen) {
  6437. PDFViewerApplication.refreshThumbnailViewer();
  6438. }
  6439. PDFViewerApplication.forceRendering();
  6440. });
  6441. document.getElementById('viewThumbnail').addEventListener('click',
  6442. function() {
  6443. PDFViewerApplication.switchSidebarView('thumbs');
  6444. });
  6445. document.getElementById('viewOutline').addEventListener('click',
  6446. function() {
  6447. PDFViewerApplication.switchSidebarView('outline');
  6448. });
  6449. document.getElementById('viewOutline').addEventListener('dblclick',
  6450. function() {
  6451. PDFViewerApplication.outline.toggleOutlineTree();
  6452. });
  6453. document.getElementById('viewAttachments').addEventListener('click',
  6454. function() {
  6455. PDFViewerApplication.switchSidebarView('attachments');
  6456. });
  6457. document.getElementById('previous').addEventListener('click',
  6458. function() {
  6459. PDFViewerApplication.page--;
  6460. });
  6461. document.getElementById('next').addEventListener('click',
  6462. function() {
  6463. PDFViewerApplication.page++;
  6464. });
  6465. document.getElementById('zoomIn').addEventListener('click',
  6466. function() {
  6467. PDFViewerApplication.zoomIn();
  6468. });
  6469. document.getElementById('zoomOut').addEventListener('click',
  6470. function() {
  6471. PDFViewerApplication.zoomOut();
  6472. });
  6473. document.getElementById('pageNumber').addEventListener('click', function() {
  6474. this.select();
  6475. });
  6476. document.getElementById('pageNumber').addEventListener('change', function() {
  6477. // Handle the user inputting a floating point number.
  6478. PDFViewerApplication.page = (this.value | 0);
  6479. if (this.value !== (this.value | 0).toString()) {
  6480. this.value = PDFViewerApplication.page;
  6481. }
  6482. });
  6483. document.getElementById('scaleSelect').addEventListener('change', function() {
  6484. if (this.value === 'custom') {
  6485. return;
  6486. }
  6487. PDFViewerApplication.pdfViewer.currentScaleValue = this.value;
  6488. });
  6489. document.getElementById('presentationMode').addEventListener('click',
  6490. SecondaryToolbar.presentationModeClick.bind(SecondaryToolbar));
  6491. document.getElementById('openFile').addEventListener('click',
  6492. SecondaryToolbar.openFileClick.bind(SecondaryToolbar));
  6493. document.getElementById('print').addEventListener('click',
  6494. SecondaryToolbar.printClick.bind(SecondaryToolbar));
  6495. document.getElementById('download').addEventListener('click',
  6496. SecondaryToolbar.downloadClick.bind(SecondaryToolbar));
  6497. if (file && file.lastIndexOf('file:', 0) === 0) {
  6498. // file:-scheme. Load the contents in the main thread because QtWebKit
  6499. // cannot load file:-URLs in a Web Worker. file:-URLs are usually loaded
  6500. // very quickly, so there is no need to set up progress event listeners.
  6501. PDFViewerApplication.setTitleUsingUrl(file);
  6502. var xhr = new XMLHttpRequest();
  6503. xhr.onload = function() {
  6504. PDFViewerApplication.open(new Uint8Array(xhr.response));
  6505. };
  6506. try {
  6507. xhr.open('GET', file);
  6508. xhr.responseType = 'arraybuffer';
  6509. xhr.send();
  6510. } catch (e) {
  6511. PDFViewerApplication.error(mozL10n.get('loading_error', null,
  6512. 'An error occurred while loading the PDF.'), e);
  6513. }
  6514. return;
  6515. }
  6516. if (file) {
  6517. PDFViewerApplication.open(file);
  6518. }
  6519. }
  6520. document.addEventListener('DOMContentLoaded', webViewerLoad, true);
  6521. document.addEventListener('pagerendered', function (e) {
  6522. var pageNumber = e.detail.pageNumber;
  6523. var pageIndex = pageNumber - 1;
  6524. var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
  6525. if (PDFViewerApplication.sidebarOpen) {
  6526. var thumbnailView = PDFViewerApplication.pdfThumbnailViewer.
  6527. getThumbnail(pageIndex);
  6528. thumbnailView.setImage(pageView);
  6529. }
  6530. if (PDFJS.pdfBug && Stats.enabled && pageView.stats) {
  6531. Stats.add(pageNumber, pageView.stats);
  6532. }
  6533. if (pageView.error) {
  6534. PDFViewerApplication.error(mozL10n.get('rendering_error', null,
  6535. 'An error occurred while rendering the page.'), pageView.error);
  6536. }
  6537. // If the page is still visible when it has finished rendering,
  6538. // ensure that the page number input loading indicator is hidden.
  6539. if (pageNumber === PDFViewerApplication.page) {
  6540. var pageNumberInput = document.getElementById('pageNumber');
  6541. pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
  6542. }
  6543. }, true);
  6544. document.addEventListener('textlayerrendered', function (e) {
  6545. var pageIndex = e.detail.pageNumber - 1;
  6546. var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
  6547. }, true);
  6548. document.addEventListener('pagemode', function (evt) {
  6549. if (!PDFViewerApplication.initialized) {
  6550. return;
  6551. }
  6552. // Handle the 'pagemode' hash parameter, see also `PDFLinkService_setHash`.
  6553. var mode = evt.detail.mode;
  6554. switch (mode) {
  6555. case 'bookmarks':
  6556. // Note: Our code calls this property 'outline', even though the
  6557. // Open Parameter specification calls it 'bookmarks'.
  6558. mode = 'outline';
  6559. /* falls through */
  6560. case 'thumbs':
  6561. case 'attachments':
  6562. PDFViewerApplication.switchSidebarView(mode, true);
  6563. break;
  6564. case 'none':
  6565. if (PDFViewerApplication.sidebarOpen) {
  6566. document.getElementById('sidebarToggle').click();
  6567. }
  6568. break;
  6569. }
  6570. }, true);
  6571. document.addEventListener('namedaction', function (e) {
  6572. if (!PDFViewerApplication.initialized) {
  6573. return;
  6574. }
  6575. // Processing couple of named actions that might be useful.
  6576. // See also PDFLinkService.executeNamedAction
  6577. var action = e.detail.action;
  6578. switch (action) {
  6579. case 'GoToPage':
  6580. document.getElementById('pageNumber').focus();
  6581. break;
  6582. case 'Find':
  6583. if (!PDFViewerApplication.supportsIntegratedFind) {
  6584. PDFViewerApplication.findBar.toggle();
  6585. }
  6586. break;
  6587. }
  6588. }, true);
  6589. window.addEventListener('presentationmodechanged', function (e) {
  6590. var active = e.detail.active;
  6591. var switchInProgress = e.detail.switchInProgress;
  6592. PDFViewerApplication.pdfViewer.presentationModeState =
  6593. switchInProgress ? PresentationModeState.CHANGING :
  6594. active ? PresentationModeState.FULLSCREEN : PresentationModeState.NORMAL;
  6595. });
  6596. window.addEventListener('updateviewarea', function (evt) {
  6597. if (!PDFViewerApplication.initialized) {
  6598. return;
  6599. }
  6600. var location = evt.location;
  6601. PDFViewerApplication.store.initializedPromise.then(function() {
  6602. PDFViewerApplication.store.setMultiple({
  6603. 'exists': true,
  6604. 'page': location.pageNumber,
  6605. 'zoom': location.scale,
  6606. 'scrollLeft': location.left,
  6607. 'scrollTop': location.top
  6608. }).catch(function() {
  6609. // unable to write to storage
  6610. });
  6611. });
  6612. var href =
  6613. PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
  6614. document.getElementById('viewBookmark').href = href;
  6615. document.getElementById('secondaryViewBookmark').href = href;
  6616. // Update the current bookmark in the browsing history.
  6617. PDFViewerApplication.pdfHistory.updateCurrentBookmark(location.pdfOpenParams,
  6618. location.pageNumber);
  6619. // Show/hide the loading indicator in the page number input element.
  6620. var pageNumberInput = document.getElementById('pageNumber');
  6621. var currentPage =
  6622. PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1);
  6623. if (currentPage.renderingState === RenderingStates.FINISHED) {
  6624. pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
  6625. } else {
  6626. pageNumberInput.classList.add(PAGE_NUMBER_LOADING_INDICATOR);
  6627. }
  6628. }, true);
  6629. window.addEventListener('resize', function webViewerResize(evt) {
  6630. if (PDFViewerApplication.initialized) {
  6631. var currentScaleValue = PDFViewerApplication.pdfViewer.currentScaleValue;
  6632. if (currentScaleValue === 'auto' ||
  6633. currentScaleValue === 'page-fit' ||
  6634. currentScaleValue === 'page-width') {
  6635. // Note: the scale is constant for 'page-actual'.
  6636. PDFViewerApplication.pdfViewer.currentScaleValue = currentScaleValue;
  6637. } else if (!currentScaleValue) {
  6638. // Normally this shouldn't happen, but if the scale wasn't initialized
  6639. // we set it to the default value in order to prevent any issues.
  6640. // (E.g. the document being rendered with the wrong scale on load.)
  6641. PDFViewerApplication.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  6642. }
  6643. PDFViewerApplication.pdfViewer.update();
  6644. }
  6645. // Set the 'max-height' CSS property of the secondary toolbar.
  6646. SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
  6647. });
  6648. window.addEventListener('hashchange', function webViewerHashchange(evt) {
  6649. if (PDFViewerApplication.pdfHistory.isHashChangeUnlocked) {
  6650. var hash = document.location.hash.substring(1);
  6651. if (!hash) {
  6652. return;
  6653. }
  6654. if (!PDFViewerApplication.isInitialViewSet) {
  6655. PDFViewerApplication.initialBookmark = hash;
  6656. } else {
  6657. PDFViewerApplication.pdfLinkService.setHash(hash);
  6658. }
  6659. }
  6660. });
  6661. window.addEventListener('change', function webViewerChange(evt) {
  6662. var files = evt.target.files;
  6663. if (!files || files.length === 0) {
  6664. return;
  6665. }
  6666. var file = files[0];
  6667. if (!PDFJS.disableCreateObjectURL &&
  6668. typeof URL !== 'undefined' && URL.createObjectURL) {
  6669. PDFViewerApplication.open(URL.createObjectURL(file));
  6670. } else {
  6671. // Read the local file into a Uint8Array.
  6672. var fileReader = new FileReader();
  6673. fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
  6674. var buffer = evt.target.result;
  6675. var uint8Array = new Uint8Array(buffer);
  6676. PDFViewerApplication.open(uint8Array);
  6677. };
  6678. fileReader.readAsArrayBuffer(file);
  6679. }
  6680. PDFViewerApplication.setTitleUsingUrl(file.name);
  6681. // URL does not reflect proper document location - hiding some icons.
  6682. document.getElementById('viewBookmark').setAttribute('hidden', 'true');
  6683. document.getElementById('secondaryViewBookmark').
  6684. setAttribute('hidden', 'true');
  6685. document.getElementById('download').setAttribute('hidden', 'true');
  6686. document.getElementById('secondaryDownload').setAttribute('hidden', 'true');
  6687. }, true);
  6688. function selectScaleOption(value) {
  6689. var options = document.getElementById('scaleSelect').options;
  6690. var predefinedValueFound = false;
  6691. for (var i = 0, ii = options.length; i < ii; i++) {
  6692. var option = options[i];
  6693. if (option.value !== value) {
  6694. option.selected = false;
  6695. continue;
  6696. }
  6697. option.selected = true;
  6698. predefinedValueFound = true;
  6699. }
  6700. return predefinedValueFound;
  6701. }
  6702. window.addEventListener('localized', function localized(evt) {
  6703. document.getElementsByTagName('html')[0].dir = mozL10n.getDirection();
  6704. PDFViewerApplication.animationStartedPromise.then(function() {
  6705. // Adjust the width of the zoom box to fit the content.
  6706. // Note: If the window is narrow enough that the zoom box is not visible,
  6707. // we temporarily show it to be able to adjust its width.
  6708. var container = document.getElementById('scaleSelectContainer');
  6709. if (container.clientWidth === 0) {
  6710. container.setAttribute('style', 'display: inherit;');
  6711. }
  6712. if (container.clientWidth > 0) {
  6713. var select = document.getElementById('scaleSelect');
  6714. select.setAttribute('style', 'min-width: inherit;');
  6715. var width = select.clientWidth + SCALE_SELECT_CONTAINER_PADDING;
  6716. select.setAttribute('style', 'min-width: ' +
  6717. (width + SCALE_SELECT_PADDING) + 'px;');
  6718. container.setAttribute('style', 'min-width: ' + width + 'px; ' +
  6719. 'max-width: ' + width + 'px;');
  6720. }
  6721. // Set the 'max-height' CSS property of the secondary toolbar.
  6722. SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
  6723. });
  6724. }, true);
  6725. window.addEventListener('scalechange', function scalechange(evt) {
  6726. document.getElementById('zoomOut').disabled = (evt.scale === MIN_SCALE);
  6727. document.getElementById('zoomIn').disabled = (evt.scale === MAX_SCALE);
  6728. // Update the 'scaleSelect' DOM element.
  6729. var predefinedValueFound = selectScaleOption(evt.presetValue ||
  6730. '' + evt.scale);
  6731. if (!predefinedValueFound) {
  6732. var customScaleOption = document.getElementById('customScaleOption');
  6733. var customScale = Math.round(evt.scale * 10000) / 100;
  6734. customScaleOption.textContent =
  6735. mozL10n.get('page_scale_percent', { scale: customScale }, '{{scale}}%');
  6736. customScaleOption.selected = true;
  6737. }
  6738. if (!PDFViewerApplication.initialized) {
  6739. return;
  6740. }
  6741. PDFViewerApplication.pdfViewer.update();
  6742. }, true);
  6743. window.addEventListener('pagechange', function pagechange(evt) {
  6744. var page = evt.pageNumber;
  6745. if (evt.previousPageNumber !== page) {
  6746. document.getElementById('pageNumber').value = page;
  6747. if (PDFViewerApplication.sidebarOpen) {
  6748. PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(page);
  6749. }
  6750. }
  6751. var numPages = PDFViewerApplication.pagesCount;
  6752. document.getElementById('previous').disabled = (page <= 1);
  6753. document.getElementById('next').disabled = (page >= numPages);
  6754. document.getElementById('firstPage').disabled = (page <= 1);
  6755. document.getElementById('lastPage').disabled = (page >= numPages);
  6756. // we need to update stats
  6757. if (PDFJS.pdfBug && Stats.enabled) {
  6758. var pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1);
  6759. if (pageView.stats) {
  6760. Stats.add(page, pageView.stats);
  6761. }
  6762. }
  6763. }, true);
  6764. function handleMouseWheel(evt) {
  6765. var MOUSE_WHEEL_DELTA_FACTOR = 40;
  6766. var ticks = (evt.type === 'DOMMouseScroll') ? -evt.detail :
  6767. evt.wheelDelta / MOUSE_WHEEL_DELTA_FACTOR;
  6768. var direction = (ticks < 0) ? 'zoomOut' : 'zoomIn';
  6769. var pdfViewer = PDFViewerApplication.pdfViewer;
  6770. if (pdfViewer.isInPresentationMode) {
  6771. evt.preventDefault();
  6772. PDFViewerApplication.scrollPresentationMode(ticks *
  6773. MOUSE_WHEEL_DELTA_FACTOR);
  6774. } else if (evt.ctrlKey || evt.metaKey) {
  6775. var support = PDFViewerApplication.supportedMouseWheelZoomModifierKeys;
  6776. if ((evt.ctrlKey && !support.ctrlKey) ||
  6777. (evt.metaKey && !support.metaKey)) {
  6778. return;
  6779. }
  6780. // Only zoom the pages, not the entire viewer.
  6781. evt.preventDefault();
  6782. var previousScale = pdfViewer.currentScale;
  6783. PDFViewerApplication[direction](Math.abs(ticks));
  6784. var currentScale = pdfViewer.currentScale;
  6785. if (previousScale !== currentScale) {
  6786. // After scaling the page via zoomIn/zoomOut, the position of the upper-
  6787. // left corner is restored. When the mouse wheel is used, the position
  6788. // under the cursor should be restored instead.
  6789. var scaleCorrectionFactor = currentScale / previousScale - 1;
  6790. var rect = pdfViewer.container.getBoundingClientRect();
  6791. var dx = evt.clientX - rect.left;
  6792. var dy = evt.clientY - rect.top;
  6793. pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor;
  6794. pdfViewer.container.scrollTop += dy * scaleCorrectionFactor;
  6795. }
  6796. }
  6797. }
  6798. window.addEventListener('DOMMouseScroll', handleMouseWheel);
  6799. window.addEventListener('mousewheel', handleMouseWheel);
  6800. window.addEventListener('click', function click(evt) {
  6801. if (SecondaryToolbar.opened &&
  6802. PDFViewerApplication.pdfViewer.containsElement(evt.target)) {
  6803. SecondaryToolbar.close();
  6804. }
  6805. }, false);
  6806. window.addEventListener('keydown', function keydown(evt) {
  6807. if (OverlayManager.active) {
  6808. return;
  6809. }
  6810. var handled = false;
  6811. var cmd = (evt.ctrlKey ? 1 : 0) |
  6812. (evt.altKey ? 2 : 0) |
  6813. (evt.shiftKey ? 4 : 0) |
  6814. (evt.metaKey ? 8 : 0);
  6815. var pdfViewer = PDFViewerApplication.pdfViewer;
  6816. var isViewerInPresentationMode = pdfViewer && pdfViewer.isInPresentationMode;
  6817. // First, handle the key bindings that are independent whether an input
  6818. // control is selected or not.
  6819. if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
  6820. // either CTRL or META key with optional SHIFT.
  6821. switch (evt.keyCode) {
  6822. case 70: // f
  6823. if (!PDFViewerApplication.supportsIntegratedFind) {
  6824. PDFViewerApplication.findBar.open();
  6825. handled = true;
  6826. }
  6827. break;
  6828. case 71: // g
  6829. if (!PDFViewerApplication.supportsIntegratedFind) {
  6830. PDFViewerApplication.findBar.dispatchEvent('again',
  6831. cmd === 5 || cmd === 12);
  6832. handled = true;
  6833. }
  6834. break;
  6835. case 61: // FF/Mac '='
  6836. case 107: // FF '+' and '='
  6837. case 187: // Chrome '+'
  6838. case 171: // FF with German keyboard
  6839. if (!isViewerInPresentationMode) {
  6840. PDFViewerApplication.zoomIn();
  6841. }
  6842. handled = true;
  6843. break;
  6844. case 173: // FF/Mac '-'
  6845. case 109: // FF '-'
  6846. case 189: // Chrome '-'
  6847. if (!isViewerInPresentationMode) {
  6848. PDFViewerApplication.zoomOut();
  6849. }
  6850. handled = true;
  6851. break;
  6852. case 48: // '0'
  6853. case 96: // '0' on Numpad of Swedish keyboard
  6854. if (!isViewerInPresentationMode) {
  6855. // keeping it unhandled (to restore page zoom to 100%)
  6856. setTimeout(function () {
  6857. // ... and resetting the scale after browser adjusts its scale
  6858. pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  6859. });
  6860. handled = false;
  6861. }
  6862. break;
  6863. }
  6864. }
  6865. // CTRL or META without shift
  6866. if (cmd === 1 || cmd === 8) {
  6867. switch (evt.keyCode) {
  6868. case 83: // s
  6869. PDFViewerApplication.download();
  6870. handled = true;
  6871. break;
  6872. }
  6873. }
  6874. // CTRL+ALT or Option+Command
  6875. if (cmd === 3 || cmd === 10) {
  6876. switch (evt.keyCode) {
  6877. case 80: // p
  6878. PDFViewerApplication.requestPresentationMode();
  6879. handled = true;
  6880. break;
  6881. case 71: // g
  6882. // focuses input#pageNumber field
  6883. document.getElementById('pageNumber').select();
  6884. handled = true;
  6885. break;
  6886. }
  6887. }
  6888. if (handled) {
  6889. evt.preventDefault();
  6890. return;
  6891. }
  6892. // Some shortcuts should not get handled if a control/input element
  6893. // is selected.
  6894. var curElement = document.activeElement || document.querySelector(':focus');
  6895. var curElementTagName = curElement && curElement.tagName.toUpperCase();
  6896. if (curElementTagName === 'INPUT' ||
  6897. curElementTagName === 'TEXTAREA' ||
  6898. curElementTagName === 'SELECT') {
  6899. // Make sure that the secondary toolbar is closed when Escape is pressed.
  6900. if (evt.keyCode !== 27) { // 'Esc'
  6901. return;
  6902. }
  6903. }
  6904. var ensureViewerFocused = false;
  6905. if (cmd === 0) { // no control key pressed at all.
  6906. switch (evt.keyCode) {
  6907. case 38: // up arrow
  6908. case 33: // pg up
  6909. case 8: // backspace
  6910. if (!isViewerInPresentationMode &&
  6911. pdfViewer.currentScaleValue !== 'page-fit') {
  6912. break;
  6913. }
  6914. /* in presentation mode */
  6915. /* falls through */
  6916. case 37: // left arrow
  6917. // horizontal scrolling using arrow keys
  6918. if (pdfViewer.isHorizontalScrollbarEnabled) {
  6919. break;
  6920. }
  6921. /* falls through */
  6922. case 75: // 'k'
  6923. case 80: // 'p'
  6924. PDFViewerApplication.page--;
  6925. handled = true;
  6926. break;
  6927. case 27: // esc key
  6928. if (SecondaryToolbar.opened) {
  6929. SecondaryToolbar.close();
  6930. handled = true;
  6931. }
  6932. if (!PDFViewerApplication.supportsIntegratedFind &&
  6933. PDFViewerApplication.findBar.opened) {
  6934. PDFViewerApplication.findBar.close();
  6935. handled = true;
  6936. }
  6937. break;
  6938. case 40: // down arrow
  6939. case 34: // pg down
  6940. case 32: // spacebar
  6941. if (!isViewerInPresentationMode &&
  6942. pdfViewer.currentScaleValue !== 'page-fit') {
  6943. break;
  6944. }
  6945. /* falls through */
  6946. case 39: // right arrow
  6947. // horizontal scrolling using arrow keys
  6948. if (pdfViewer.isHorizontalScrollbarEnabled) {
  6949. break;
  6950. }
  6951. /* falls through */
  6952. case 74: // 'j'
  6953. case 78: // 'n'
  6954. PDFViewerApplication.page++;
  6955. handled = true;
  6956. break;
  6957. case 36: // home
  6958. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  6959. PDFViewerApplication.page = 1;
  6960. handled = true;
  6961. ensureViewerFocused = true;
  6962. }
  6963. break;
  6964. case 35: // end
  6965. if (isViewerInPresentationMode || (PDFViewerApplication.pdfDocument &&
  6966. PDFViewerApplication.page < PDFViewerApplication.pagesCount)) {
  6967. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  6968. handled = true;
  6969. ensureViewerFocused = true;
  6970. }
  6971. break;
  6972. case 72: // 'h'
  6973. if (!isViewerInPresentationMode) {
  6974. HandTool.toggle();
  6975. }
  6976. break;
  6977. case 82: // 'r'
  6978. PDFViewerApplication.rotatePages(90);
  6979. break;
  6980. }
  6981. }
  6982. if (cmd === 4) { // shift-key
  6983. switch (evt.keyCode) {
  6984. case 32: // spacebar
  6985. if (!isViewerInPresentationMode &&
  6986. pdfViewer.currentScaleValue !== 'page-fit') {
  6987. break;
  6988. }
  6989. PDFViewerApplication.page--;
  6990. handled = true;
  6991. break;
  6992. case 82: // 'r'
  6993. PDFViewerApplication.rotatePages(-90);
  6994. break;
  6995. }
  6996. }
  6997. if (!handled && !isViewerInPresentationMode) {
  6998. // 33=Page Up 34=Page Down 35=End 36=Home
  6999. // 37=Left 38=Up 39=Right 40=Down
  7000. // 32=Spacebar
  7001. if ((evt.keyCode >= 33 && evt.keyCode <= 40) ||
  7002. (evt.keyCode === 32 && curElementTagName !== 'BUTTON')) {
  7003. ensureViewerFocused = true;
  7004. }
  7005. }
  7006. if (cmd === 2) { // alt-key
  7007. switch (evt.keyCode) {
  7008. case 37: // left arrow
  7009. if (isViewerInPresentationMode) {
  7010. PDFViewerApplication.pdfHistory.back();
  7011. handled = true;
  7012. }
  7013. break;
  7014. case 39: // right arrow
  7015. if (isViewerInPresentationMode) {
  7016. PDFViewerApplication.pdfHistory.forward();
  7017. handled = true;
  7018. }
  7019. break;
  7020. }
  7021. }
  7022. if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) {
  7023. // The page container is not focused, but a page navigation key has been
  7024. // pressed. Change the focus to the viewer container to make sure that
  7025. // navigation by keyboard works as expected.
  7026. pdfViewer.focus();
  7027. }
  7028. if (handled) {
  7029. evt.preventDefault();
  7030. }
  7031. });
  7032. window.addEventListener('beforeprint', function beforePrint(evt) {
  7033. PDFViewerApplication.beforePrint();
  7034. });
  7035. window.addEventListener('afterprint', function afterPrint(evt) {
  7036. PDFViewerApplication.afterPrint();
  7037. });
  7038. (function animationStartedClosure() {
  7039. // The offsetParent is not set until the pdf.js iframe or object is visible.
  7040. // Waiting for first animation.
  7041. PDFViewerApplication.animationStartedPromise = new Promise(
  7042. function (resolve) {
  7043. window.requestAnimationFrame(resolve);
  7044. });
  7045. })();