viewer.js 279 KB

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