viewer.js 254 KB

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