viewer.js 244 KB

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